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
194
url
stringlengths
46
254
license
stringclasses
4 values
def _expand_key(self, master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Initialize round keys with raw key material. key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (self.n_rounds + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: # Run word through S-box in the fourth iteration when using a # 256-bit key. word = [s_box[b] for b in word] # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
Expands and returns a list of key matrices for the given master_key.
_expand_key
python
sajjadium/ctf-archives
ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
MIT
def encrypt_block(self, plaintext): """ Encrypts a single block of 16 byte long plaintext. """ assert len(plaintext) == 16 plain_state = bytes2matrix(plaintext) add_round_key(plain_state, self._key_matrices[0]) for i in range(1, self.n_rounds): if i in self.broken_rounds: sub_bytes_defect(plain_state) else: sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, self._key_matrices[i]) if self.n_rounds+1 in self.broken_rounds: sub_bytes_defect(plain_state) else: sub_bytes(plain_state) shift_rows(plain_state) add_round_key(plain_state, self._key_matrices[-1]) return matrix2bytes(plain_state)
Encrypts a single block of 16 byte long plaintext.
encrypt_block
python
sajjadium/ctf-archives
ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
MIT
def decrypt_block(self, ciphertext): """ Decrypts a single block of 16 byte long ciphertext. """ assert len(ciphertext) == 16 cipher_state = bytes2matrix(ciphertext) add_round_key(cipher_state, self._key_matrices[-1]) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) for i in range(self.n_rounds - 1, 0, -1): add_round_key(cipher_state, self._key_matrices[i]) inv_mix_columns(cipher_state) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) add_round_key(cipher_state, self._key_matrices[0]) return matrix2bytes(cipher_state)
Decrypts a single block of 16 byte long ciphertext.
decrypt_block
python
sajjadium/ctf-archives
ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KITCTFCTF/2023/crypto/number-lock/number-lock.py
MIT
def render_emails(address): id = 0 render = """ <table> <tr> <th id="th-left">From</th> <th>Subject</th> <th id="th-right">Date</th> </tr> """ overlays = "" m = mails[address].copy() for email in m: render += f""" <tr id="{id}"> <td>{email['sender']}</td> <td>{email['subject']}</td> <td>{email['timestamp']}</td> </tr> """ overlays += f""" <div id="overlay-{id}" class="overlay"> <div class="email-details"> <h1>{email['subject']} - from: {email['sender']} to {email['rcpt']}</h1> <p>{email['body']}</p> </div> </div> """ id +=1 render += "</table>" render += overlays return render
overlays = "" m = mails[address].copy() for email in m: render += f
render_emails
python
sajjadium/ctf-archives
ctfs/KITCTFCTF/2023/web/Wanky_Mail/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/KITCTFCTF/2023/web/Wanky_Mail/app.py
MIT
def forward(self, x: Tensor) -> Tensor: """ Arguments: x: Tensor, shape ``[batch_size, seq_len, embedding_dim]`` """ x = x + self.pe[:, :x.size(1)] return x
Arguments: x: Tensor, shape ``[batch_size, seq_len, embedding_dim]``
forward
python
sajjadium/ctf-archives
ctfs/TSG/2023/rev/Natural_Flag_Processing_2/main.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TSG/2023/rev/Natural_Flag_Processing_2/main.py
MIT
def api_new(): """Add a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['title'], str) assert isinstance(data['content'], str) except: return flask.abort(400, "Invalid request") err, post_id = db.add(data['title'], get_username(), data['content']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'id': post_id})
Add a blog post
api_new
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def api_delete(): """Delete a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['id'], str) except: return flask.abort(400, "Invalid request") err = db.delete(data['id']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'})
Delete a blog post
api_delete
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def api_export(): """Export blog posts""" db = get_database() if db is None: return flask.redirect('/login') err, blob = db.export_posts(get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'export': blob})
Export blog posts
api_export
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def api_import(): """Import blog posts""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['import'], str) except: return flask.abort(400, "Invalid request") err = db.import_posts(data['import'], get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'})
Import blog posts
api_import
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def __iter__(self): """Return blog posts sorted by publish date""" def enumerate_posts(workdir): posts = [] for path in glob.glob(f'{workdir}/*.json'): with open(path, "rb") as f: posts.append(json.loads(f.read().decode('latin-1'))) for post in sorted(posts, key=lambda post: datetime.datetime.strptime( post['date'], "%Y/%m/%d %H:%M:%S" ))[::-1]: yield post return enumerate_posts(self.workdir)
Return blog posts sorted by publish date
__iter__
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def to_snake(s): """Convert string to snake case""" for i, c in enumerate(s): if not c.isalnum(): s = s[:i] + '_' + s[i+1:] return s
Convert string to snake case
to_snake
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def add(self, title, author, content): """Add new blog post""" # Validate title and content if len(title) == 0: return 'Title is emptry', None if len(title) > 64: return 'Title is too long', None if len(content) == 0 : return 'HTML is empty', None if len(content) > 1024*64: return 'HTML is too long', None if '{%' in content: return 'The pattern "{%" is forbidden', None for m in re.finditer(r"{{", content): p = m.start() if not (content[p:p+len('{{title}}')] == '{{title}}' or \ content[p:p+len('{{author}}')] == '{{author}}' or \ content[p:p+len('{{date}}')] == '{{date}}'): return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None # Save the blog post now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") post_id = Database.to_snake(title) data = { 'title': title, 'id': post_id, 'date': now, 'author': author, 'content': content } with open(f'{self.workdir}/{post_id}.json', "w") as f: json.dump(data, f) return None, post_id
Add new blog post
add
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def read(self, title): """Load a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are looking for does not exist', None with open(f'{self.workdir}/{post_id}.json', "rb") as f: return None, json.loads(f.read().decode('latin-1'))
Load a blog post
read
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def delete(self, title): """Delete a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are trying to delete does not exist' os.unlink(f'{self.workdir}/{post_id}.json')
Delete a blog post
delete
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def export_posts(self, username, passhash): """Export all blog posts with encryption and signature""" buf = io.BytesIO() with zipfile.ZipFile(buf, 'a', zipfile.ZIP_STORED) as z: # Archive blog posts for path in glob.glob(f'{self.workdir}/*.json'): z.write(path) # Add signature so that anyone else cannot import this backup z.comment = f'SIGNATURE:{username}:{passhash}'.encode() # Encrypt archive so that anyone else cannot read the contents buf.seek(0) iv = os.urandom(16) cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv) encbuf = iv + cipher.encrypt(buf.read()) return None, base64.b64encode(encbuf).decode()
Export all blog posts with encryption and signature
export_posts
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def import_posts(self, b64encbuf, username, passhash): """Import blog posts from backup file""" encbuf = base64.b64decode(b64encbuf) cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16]) buf = io.BytesIO(cipher.decrypt(encbuf[16:])) try: with zipfile.ZipFile(buf, 'r', zipfile.ZIP_STORED) as z: # Check signature if z.comment != f'SIGNATURE:{username}:{passhash}'.encode(): return 'This is not your database' # Extract archive z.extractall() except: return 'The database is broken' return None
Import blog posts from backup file
import_posts
python
sajjadium/ctf-archives
ctfs/ASIS/2022/Quals/web/hugeblog/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/ASIS/2022/Quals/web/hugeblog/app.py
MIT
def _bytes2matrix(self, text): """ Converts a 16-byte array into a 4x4 matrix. """ return [list(text[i:i+4]) for i in range(0, len(text), 4)]
Converts a 16-byte array into a 4x4 matrix.
_bytes2matrix
python
sajjadium/ctf-archives
ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/oracle.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/oracle.py
MIT
def _matrix2bytes(self, matrix): """ Converts a 4x4 matrix into a 16-byte array. """ return bytes(sum(matrix, []))
Converts a 4x4 matrix into a 16-byte array.
_matrix2bytes
python
sajjadium/ctf-archives
ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/oracle.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/oracle.py
MIT
def decode(encoded_str): ''' Decode Base91 string to a bytearray ''' v = -1 b = 0 n = 0 out = bytearray() for strletter in encoded_str: if not strletter in decode_table: continue c = decode_table[strletter] if(v < 0): v = c else: v += c*91 b |= v << n n += 13 if (v & 8191)>88 else 14 while True: out += struct.pack('B', b&255) b >>= 8 n -= 8 if not n>7: break v = -1 if v+1: out += struct.pack('B', (b | v << n) & 255 ) return out
Decode Base91 string to a bytearray
decode
python
sajjadium/ctf-archives
ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
MIT
def encode(bindata): ''' Encode a bytearray to a Base91 string ''' b = 0 n = 0 out = '' for count in range(len(bindata)): byte = bindata[count:count+1] b |= struct.unpack('B', byte)[0] << n n += 8 if n>13: v = b & 8191 if v > 88: b >>= 13 n -= 13 else: v = b & 16383 b >>= 14 n -= 14 out += base91_alphabet[v % 91] + base91_alphabet[v // 91] if n: out += base91_alphabet[b % 91] if n>7 or b>90: out += base91_alphabet[b // 91] return out
Encode a bytearray to a Base91 string
encode
python
sajjadium/ctf-archives
ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2023/web/Based_Encoding/based91.py
MIT
def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
Performs a call to reCaptcha API to validate the given response
verify
python
sajjadium/ctf-archives
ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/recaptcha.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/recaptcha.py
MIT
def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
Performs a call to reCaptcha API to validate the given response
verify
python
sajjadium/ctf-archives
ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/recaptcha.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/recaptcha.py
MIT
def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
Performs a call to reCaptcha API to validate the given response
verify
python
sajjadium/ctf-archives
ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/recaptcha.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/recaptcha.py
MIT
def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
Performs a call to reCaptcha API to validate the given response
verify
python
sajjadium/ctf-archives
ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/recaptcha.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/recaptcha.py
MIT
def bytes2matrix(text): """ Converts a 16-byte array into a 4x4 matrix. """ return [list(text[i:i+4]) for i in range(0, len(text), 4)]
Converts a 16-byte array into a 4x4 matrix.
bytes2matrix
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def matrix2bytes(matrix): """ Converts a 4x4 matrix into a 16-byte array. """ return bytes(sum(matrix, []))
Converts a 4x4 matrix into a 16-byte array.
matrix2bytes
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i^j for i, j in zip(a, b))
Returns a new byte array with the elements xor'ed.
xor_bytes
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def inc_bytes(a): """ Returns a new byte array with the value increment by 1 """ out = list(a) for i in reversed(range(len(out))): if out[i] == 0xFF: out[i] = 0 else: out[i] += 1 break return bytes(out)
Returns a new byte array with the value increment by 1
inc_bytes
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def __init__(self, master_key): """ Initializes the object with a given key. """ assert len(master_key) in A2S.rounds_by_key_size self.n_rounds = A2S.rounds_by_key_size[len(master_key)] self._key_matrices = self._expand_key(master_key)
Initializes the object with a given key.
__init__
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def _expand_key(self, master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Initialize round keys with raw key material. key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 # Each iteration has exactly as many columns as the key material. columns_per_iteration = len(key_columns) i = 1 while len(key_columns) < (self.n_rounds + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: # Run word through S-box in the fourth iteration when using a # 256-bit key. word = [s_box[b] for b in word] # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
Expands and returns a list of key matrices for the given master_key.
_expand_key
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def encrypt_block(self, plaintext): """ Encrypts a single block of 16 byte long plaintext. """ assert len(plaintext) == 16 plain_state = bytes2matrix(plaintext) add_round_key(plain_state, self._key_matrices[0]) for i in range(1, self.n_rounds): sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, self._key_matrices[i]) sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) # added mix_columns add_round_key(plain_state, self._key_matrices[-1]) return matrix2bytes(plain_state)
Encrypts a single block of 16 byte long plaintext.
encrypt_block
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def decrypt_block(self, ciphertext): """ Decrypts a single block of 16 byte long ciphertext. """ assert len(ciphertext) == 16 cipher_state = bytes2matrix(ciphertext) add_round_key(cipher_state, self._key_matrices[-1]) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) for i in range(self.n_rounds - 1, 0, -1): add_round_key(cipher_state, self._key_matrices[i]) inv_mix_columns(cipher_state) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) add_round_key(cipher_state, self._key_matrices[0]) return matrix2bytes(cipher_state)
Decrypts a single block of 16 byte long ciphertext.
decrypt_block
python
sajjadium/ctf-archives
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
MIT
def _chkpath(method, path): """Return an HTTP status for the given filesystem path.""" if method.lower() in ('put', 'delete'): return 501, "Not Implemented" # TODO elif method.lower() not in ('get', 'head'): return 405, "Method Not Allowed" elif os.path.isdir(path): return 400, "Path Not A File" elif not os.path.isfile(path): return 404, "File Not Found" elif not os.access(path, os.R_OK): return 403, "Access Denied" else: return 200, "OK"
Return an HTTP status for the given filesystem path.
_chkpath
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
MIT
def send(self, req, **kwargs): # pylint: disable=unused-argument """Return the file specified by the given request @type req: C{PreparedRequest} @todo: Should I bother filling `response.headers` and processing If-Modified-Since and friends using `os.stat`? """ path = os.path.normcase(os.path.normpath(url2pathname(req.path_url))) response = requests.Response() response.status_code, response.reason = self._chkpath(req.method, path) if response.status_code == 200 and req.method.lower() != 'head': try: response.raw = open(path, 'rb') except (OSError, IOError) as err: response.status_code = 500 response.reason = str(err) if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url response.request = req response.connection = self return response
Return the file specified by the given request @type req: C{PreparedRequest} @todo: Should I bother filling `response.headers` and processing If-Modified-Since and friends using `os.stat`?
send
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/ImageServicesViewer/container/images-services/src/bot.py
MIT
def greeting(): bot = "" css = """ <br><br> <center> <strong><font size=5 color='purple'>Get New Year Quotes From Our New Year Bot!</font></strong> <br>_[<img src="https://i.imgur.com/uYBBhWn.gif" width="5%" />]_ </center> <style> .centered { position: fixed; /* or absolute */ top: 25%; left: 35%; } </style> """ front = """ <form action="/" method="POST" > <select name="type"> <option value="greeting_all">All</option> <option value="NewYearCommonList">Common</option> <option value="NewYearHealthList">Health</option> <option value="NewYearFamilyList">Family</option> <option value="NewYearWealthList">Wealth</option> </select> <input type="text" hidden name="number" value="%s" /> <input type="submit" value="Ask" /><br> </form> """%random.randint(0,3) greeting = "" try: debug = request.args.get("debug") if request.method == 'POST': greetType = request.form["type"] greetNumber = request.form["number"] if greetType == "greeting_all": greeting = random_greet(random.choice(NewYearCategoryList)) else: try: if greetType != None and greetNumber != None: greetNumber = re.sub(r'\s+', '', greetNumber) if greetType.isidentifier() == True and botValidator(greetNumber) == True: if len("%s[%s]" % (greetType, greetNumber)) > 20: greeting = fail else: greeting = eval("%s[%s]" % (greetType, greetNumber)) try: if greeting != fail and debug != None: greeting += "<br>You're choosing %s, it has %s quotes"%(greetType, len(eval(greetType))) except: pass else: greeting = fail else: greeting = random_greet(random.choice(NewYearCategoryList)) except: greeting = fail pass else: greeting = random_greet(random.choice(NewYearCategoryList)) if fail not in greeting: bot_list = ["( ´ ∀ `)ノ~ ♡", "(✿◕ᴗ◕)つ━━✫・*。", "(๑˘ᵕ˘)"] else: bot_list = ["(≖ ︿ ≖ ✿)", "ᕙ(⇀‸↼‶)ᕗ", "(≖ ︿ ≖ ✿)ꐦꐦ", "┌( ಠ_ಠ )┘"] bot = random.choice(bot_list) except: pass return "%s<div class='centered'>%s<strong><font color='red'>%s<br>NewYearBot >> </font></strong>%s</div>"%(css, front, bot, greeting)
front =
greeting
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/NewYearBot/main.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/NewYearBot/main.py
MIT
def _chkpath(method, path): """Return an HTTP status for the given filesystem path.""" if method.lower() in ('put', 'delete'): return 501, "Not Implemented" # TODO elif method.lower() not in ('get', 'head'): return 405, "Method Not Allowed" elif os.path.isdir(path): return 400, "Path Not A File" elif not os.path.isfile(path): return 404, "File Not Found" elif not os.access(path, os.R_OK): return 403, "Access Denied" else: return 200, "OK"
Return an HTTP status for the given filesystem path.
_chkpath
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/AdminLairayOldSchool/container/images-services/src/bot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/AdminLairayOldSchool/container/images-services/src/bot.py
MIT
def send(self, req, **kwargs): # pylint: disable=unused-argument """Return the file specified by the given request @type req: C{PreparedRequest} @todo: Should I bother filling `response.headers` and processing If-Modified-Since and friends using `os.stat`? """ path = os.path.normcase(os.path.normpath(url2pathname(req.path_url))) response = requests.Response() response.status_code, response.reason = self._chkpath(req.method, path) if response.status_code == 200 and req.method.lower() != 'head': try: response.raw = open(path, 'rb') except (OSError, IOError) as err: response.status_code = 500 response.reason = str(err) if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url response.request = req response.connection = self return response
Return the file specified by the given request @type req: C{PreparedRequest} @todo: Should I bother filling `response.headers` and processing If-Modified-Since and friends using `os.stat`?
send
python
sajjadium/ctf-archives
ctfs/TetCTF/2023/web/AdminLairayOldSchool/container/images-services/src/bot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2023/web/AdminLairayOldSchool/container/images-services/src/bot.py
MIT
def get_shares_v2(password: str, n: int, t: int) -> Tuple[int, List[str]]: """ Get password shares. Args: password: the password to be shared. n: the number of non-master shares returned. t: the minimum number of non-master shares needed to recover the password. Returns: the shares, including the master share (n + 1 shares in total). """ assert n <= MASTER_SHARE_SZ master_share = randbits(MASTER_SHARE_SZ) unprocessed_non_master_shares = get_shares(password, n, t) non_master_shares = [] for i, share in enumerate(unprocessed_non_master_shares): v = CHAR_TO_INT[share[-1]] if (master_share >> i) & 1: v = (v + P // 2) % P non_master_shares.append(share[:-1] + INT_TO_CHAR[v]) return master_share, non_master_shares
Get password shares. Args: password: the password to be shared. n: the number of non-master shares returned. t: the minimum number of non-master shares needed to recover the password. Returns: the shares, including the master share (n + 1 shares in total).
get_shares_v2
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/shares_v2/shares_v2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/shares_v2/shares_v2.py
MIT
def get_shares(password: str, n: int, t: int) -> List[str]: """ Get password shares. Args: password: the password to be shared. n: the number of shares returned. t: the minimum number of shares needed to recover the password. Returns: the shares. """ assert len(password) <= t assert n > 0 ffes = [CHAR_TO_INT[c] for c in password] ffes += [randbelow(P) for _ in range(t - len(password))] result = [] for _ in range(n): coeffs = [randbelow(P) for _ in range(len(ffes))] s = sum([x * y for x, y in zip(coeffs, ffes)]) % P coeffs.append(s) result.append("".join(INT_TO_CHAR[i] for i in coeffs)) return result
Get password shares. Args: password: the password to be shared. n: the number of shares returned. t: the minimum number of shares needed to recover the password. Returns: the shares.
get_shares
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/shares/shares.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/shares/shares.py
MIT
def op(x1, x2): """Returns `(x1 + x2 + 2 * C * x1 * x2) / (1 - x1 * x2)`.""" if x2 == INFINITY: x1, x2 = x2, x1 if x1 == INFINITY: if x2 == INFINITY: return (-2 * C) % p elif x2 == 0: return INFINITY else: return -(1 + 2 * C * x2) * pow(x2, -1, p) % p if x1 * x2 == 1: return INFINITY return (x1 + x2 + 2 * C * x1 * x2) * pow(1 - x1 * x2, -1, p) % p
Returns `(x1 + x2 + 2 * C * x1 * x2) / (1 - x1 * x2)`.
op
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/algebra/algebra.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/algebra/algebra.py
MIT
def repeated_op(x, k): """Returns `x op x op ... op x` (`x` appears `k` times)""" s = 0 while k > 0: if k & 1: s = op(s, x) k = k >> 1 x = op(x, x) return s
Returns `x op x op ... op x` (`x` appears `k` times)
repeated_op
python
sajjadium/ctf-archives
ctfs/TetCTF/2022/crypto/algebra/algebra.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TetCTF/2022/crypto/algebra/algebra.py
MIT
def merge_dicts(dict1, dict2) -> dict: """ Recursively merges dict2 into dict1 :param dict1: :param dict2: :return: """ if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict2 for k in dict2: dict1[k] = merge_dicts(dict1[k], dict2[k]) if k in dict1 else dict2[k] return dict1
Recursively merges dict2 into dict1 :param dict1: :param dict2: :return:
merge_dicts
python
sajjadium/ctf-archives
ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
MIT
def load_config() -> dict: """ load conf based on environment :return: """ try: with open(current_dir + "config.yaml", "r", encoding="utf-8") as conf_main: conf = (yaml.safe_load(conf_main)) env = "dev" if os.environ.get("SCRIPT_ENV") == "production": env = "prod" elif os.environ.get("SCRIPT_ENV") == "staging": env = "staging" with open(current_dir + "config_%s.yaml" % env, "r", encoding="utf-8") as conf_f: conf = merge_dicts(conf, yaml.safe_load(conf_f)) return conf except FileNotFoundError: return {}
load conf based on environment :return:
load_config
python
sajjadium/ctf-archives
ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2023/web/imagexif/backend/src/common/config.py
MIT
def create_user(db: Session, user_create: UserCreate, ip_addr: str): """ username = Column(String, unique=True, nullable=False) password = Column(String, nullable=False) uploaded_model = Column(Boolean, nullable=False) registered_ip = Column(String, unique=True, nullable=False) """ db_user = User(username=user_create.username, password=hashlib.sha3_512(bytes(user_create.password, 'utf-8')).hexdigest(), uploaded_model=False, registered_ip=ip_addr, last_activity=datetime.now(), participated=0, ranking=0, register_date=datetime.now() ) db.add(db_user) db.commit()
username = Column(String, unique=True, nullable=False) password = Column(String, nullable=False) uploaded_model = Column(Boolean, nullable=False) registered_ip = Column(String, unique=True, nullable=False)
create_user
python
sajjadium/ctf-archives
ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_crud.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_crud.py
MIT
def __init__(self,key,rounds=32): """Create a PRESENT cipher object key: the key as a 128-bit or 80-bit rawstring rounds: the number of rounds as an integer, 32 by default """ self.rounds = rounds if len(key) * 8 == 80: self.roundkeys = generateRoundkeys80(byte2number(key),self.rounds) elif len(key) * 8 == 128: self.roundkeys = generateRoundkeys128(byte2number(key),self.rounds) else: raise (ValueError, "Key must be a 128-bit or 80-bit rawstring")
Create a PRESENT cipher object key: the key as a 128-bit or 80-bit rawstring rounds: the number of rounds as an integer, 32 by default
__init__
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def encrypt(self,block): """Encrypt 1 block (8 bytes) Input: plaintext block as raw string Output: ciphertext block as raw string """ state = byte2number(block) for i in range(self.rounds-1): state = addRoundKey(state,self.roundkeys[i]) state = sBoxLayer(state) state = pLayer(state) cipher = addRoundKey(state,self.roundkeys[-1]) return number2byte_N(cipher,8)
Encrypt 1 block (8 bytes) Input: plaintext block as raw string Output: ciphertext block as raw string
encrypt
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def decrypt(self,block): """Decrypt 1 block (8 bytes) Input: ciphertext block as raw string Output: plaintext block as raw string """ state = byte2number(block) for i in range(self.rounds-1): state = addRoundKey(state,self.roundkeys[-i-1]) state = pLayer_dec(state) state = sBoxLayer_dec(state) decipher = addRoundKey(state,self.roundkeys[0]) return number2byte_N(decipher,8)
Decrypt 1 block (8 bytes) Input: ciphertext block as raw string Output: plaintext block as raw string
decrypt
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def generateRoundkeys80(key,rounds): """Generate the roundkeys for a 80-bit key Input: key: the key as a 80-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers""" roundkeys = [] for i in range(1,rounds+1): # (K1 ... K32) # rawkey: used in comments to show what happens at bitlevel # rawKey[0:64] roundkeys.append(key >>16) #1. Shift #rawKey[19:len(rawKey)]+rawKey[0:19] key = ((key & (2**19-1)) << 61) + (key >> 19) #2. SBox #rawKey[76:80] = S(rawKey[76:80]) key = (Sbox[key >> 76] << 76)+(key & (2**76-1)) #3. Salt #rawKey[15:20] ^ i key ^= i << 15 return roundkeys
Generate the roundkeys for a 80-bit key Input: key: the key as a 80-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers
generateRoundkeys80
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def generateRoundkeys128(key,rounds): """Generate the roundkeys for a 128-bit key Input: key: the key as a 128-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers""" roundkeys = [] for i in range(1,rounds+1): # (K1 ... K32) # rawkey: used in comments to show what happens at bitlevel roundkeys.append(key >>64) #1. Shift key = ((key & (2**67-1)) << 61) + (key >> 67) #2. SBox key = (Sbox[key >> 124] << 124)+(Sbox[(key >> 120) & 0xF] << 120)+(key & (2**120-1)) #3. Salt #rawKey[62:67] ^ i key ^= i << 62 return roundkeys
Generate the roundkeys for a 128-bit key Input: key: the key as a 128-bit integer rounds: the number of rounds as an integer Output: list of 64-bit roundkeys as integers
generateRoundkeys128
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def sBoxLayer(state): """SBox function for encryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(16): output += Sbox[( state >> (i*4)) & 0xF] << (i*4) return output
SBox function for encryption Input: 64-bit integer Output: 64-bit integer
sBoxLayer
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def sBoxLayer_dec(state): """Inverse SBox function for decryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(16): output += Sbox_inv[( state >> (i*4)) & 0xF] << (i*4) return output
Inverse SBox function for decryption Input: 64-bit integer Output: 64-bit integer
sBoxLayer_dec
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def pLayer(state): """Permutation layer for encryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(64): output += ((state >> i) & 0x01) << PBox[i] return output
Permutation layer for encryption Input: 64-bit integer Output: 64-bit integer
pLayer
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def pLayer_dec(state): """Permutation layer for decryption Input: 64-bit integer Output: 64-bit integer""" output = 0 for i in range(64): output += ((state >> i) & 0x01) << PBox_inv[i] return output
Permutation layer for decryption Input: 64-bit integer Output: 64-bit integer
pLayer_dec
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def byte2number(i): """ Convert a string to a number Input: byte (big-endian) Output: long or integer """ return int.from_bytes(i, 'big')
Convert a string to a number Input: byte (big-endian) Output: long or integer
byte2number
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def number2byte_N(i, N): """Convert a number to a string of fixed size i: long or integer N: length of byte Output: string (big-endian) """ return i.to_bytes(N, byteorder='big')
Convert a number to a string of fixed size i: long or integer N: length of byte Output: string (big-endian)
number2byte_N
python
sajjadium/ctf-archives
ctfs/LINE/2022/crypto/forward-or/present.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/crypto/forward-or/present.py
MIT
def merge_dicts(dict1, dict2) -> dict: """ Recursively merges dict2 into dict1 :param dict1: :param dict2: :return: """ if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict2 for k in dict2: dict1[k] = merge_dicts(dict1[k], dict2[k]) if k in dict1 else dict2[k] return dict1
Recursively merges dict2 into dict1 :param dict1: :param dict2: :return:
merge_dicts
python
sajjadium/ctf-archives
ctfs/LINE/2022/web/me7ball/backend/src/common/config.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/web/me7ball/backend/src/common/config.py
MIT
def load_config() -> dict: """ load conf based on environment :return: """ try: with open(current_dir + "config.yaml", "r", encoding="utf-8") as conf_main: conf = (yaml.safe_load(conf_main)) env = "dev" if os.environ.get("SCRIPT_ENV") == "production": env = "prod" elif os.environ.get("SCRIPT_ENV") == "staging": env = "staging" with open(current_dir + "config_%s.yaml" % env, "r", encoding="utf-8") as conf_f: conf = merge_dicts(conf, yaml.safe_load(conf_f)) return conf except FileNotFoundError: return {}
load conf based on environment :return:
load_config
python
sajjadium/ctf-archives
ctfs/LINE/2022/web/me7ball/backend/src/common/config.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/web/me7ball/backend/src/common/config.py
MIT
def get_common_logger(name: str, log_level: str = "DEBUG", log_file_path: str = None, std_out: bool = True, backup_count: int = 180): """ :param name: :param log_level: :param log_file_path: :param std_out: :param backup_count: :return: """ logger = getLogger(name) if log_level == "WARN": log_level = WARN elif log_level == "INFO": log_level = INFO else: log_level = DEBUG formatter = Formatter("%(asctime)s %(levelname)s %(module)s %(lineno)s :%(message)s") if log_file_path is not None: os.makedirs(os.path.dirname(log_file_path), exist_ok=True) handler = TimedRotatingFileHandler(filename=log_file_path, when="midnight", backupCount=backup_count, encoding="utf-8", delay=True) handler.setLevel(log_level) handler.setFormatter(formatter) logger.addHandler(handler) if std_out: handler = StreamHandler(sys.stdout) handler.setLevel(log_level) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(log_level) logger.propagate = False return logger
:param name: :param log_level: :param log_file_path: :param std_out: :param backup_count: :return:
get_common_logger
python
sajjadium/ctf-archives
ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
MIT
def set_logger(name: str, log_conf: dict, backup_count: int = 180): """ set the logger for different usage :param name: :param log_conf: :param backup_count: :return: """ return get_common_logger(name, log_level=log_conf["level"], log_file_path=os.path.dirname(__file__) + "/../.." + log_conf["log_file_path"], std_out=log_conf["std_out"], backup_count=backup_count)
set the logger for different usage :param name: :param log_conf: :param backup_count: :return:
set_logger
python
sajjadium/ctf-archives
ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py
MIT
def visit(baseUrl: str, link: str) -> str: """Visit the website""" p = multiprocessing.Process(target=_visit, args=(baseUrl, link)) p.start() return f"Visiting {link}"
Visit the website
visit
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
MIT
def _visit(baseUrl:str, link: str) -> str: """Visit the website""" with webdriver.Chrome(ChromeDriverManager().install(), options=options) as driver: try: driver.get(f'{baseUrl}/') cookie = {"name": "flag", "value": COOKIE["flag"]} driver.add_cookie(cookie) driver.get(link) return f"Visited {link}" except: return f"Connection Error: {link}"
Visit the website
_visit
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
MIT
def route_traffic() -> Response: """Route the traffic to upstream""" microservice = request.args.get("service", "home_page") route = routes.get(microservice, None) if route is None: return abort(404) # Fetch the required page with arguments appended raw_query_param = request.query_string.decode() print(f"Requesting {route} with q_str {raw_query_param}", file=sys.stderr) res = get(f"{route}/?{raw_query_param}") headers = [ (k, v) for k, v in res.raw.headers.items() if k.lower() not in excluded_headers ] return Response(res.content, res.status_code, headers)
Route the traffic to upstream
route_traffic
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
MIT
def not_found(e) -> Response: """404 error""" return Response(f"""Error 404: This page is not found: {e}""", 404)
404 error
not_found
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
MIT
async def index(request: Request): """ The base service for admin site """ # Currently Work in Progress requested_service = request.query_params.get("service", None) if requested_service is None: return {"message": "requested service is not found"} # Filter external parties who are not local if requested_service == "admin_page": return {"message": "admin page is currently not a requested service"} # Legit admin on localhost requested_url = request.query_params.get("url", None) if requested_url is None: return {"message": "URL is not found"} # Testing the URL with admin response = get(requested_url, cookies={"cookie": admin_cookie}) return Response(response.content, response.status_code)
The base service for admin site
index
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/admin_page/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/admin_page/app.py
MIT
def homepage() -> Response: """The homepage for the app""" cookie = request.cookies.get("cookie", "Guest Pleb") # If admin, give flag if cookie == admin_cookie: return render_template("flag.html", flag=FLAG, user="admin") # Otherwise, render normal page response = make_response(render_template("index.html", user=cookie)) response.set_cookie("cookie", cookie) return response
The homepage for the app
homepage
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/homepage/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/homepage/app.py
MIT
def is_sus(microservice: str, cookies: dict) -> bool: """Check if the arguments are sus""" acc = [val for val in cookies.values()] acc.append(microservice) for word in acc: for char in word: if char in banned_chars: return True return False
Check if the arguments are sus
is_sus
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
MIT
def route_traffic() -> Response: """Route the traffic to upstream""" microservice = request.args.get("service", "homepage") route = routes.get(microservice, None) if route is None: return abort(404) # My WAF if is_sus(request.args.to_dict(), request.cookies.to_dict()): return Response("Why u attacking me???\nGlad This WAF is working!", 400) # Fetch the required page with arguments appended with Session() as s: for k, v in request.cookies.items(): s.cookies.set(k, v) res = s.get(route, params={k: v for k, v in request.args.items()}) headers = [ (k, v) for k, v in res.raw.headers.items() if k.lower() not in excluded_headers ] return Response(res.content.decode(), res.status_code, headers)
Route the traffic to upstream
route_traffic
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
MIT
def index() -> Response: """ The base service for admin site """ user = request.cookies.get("user", "user") # Currently Work in Progress return render_template_string( f"Sorry {user}, the admin page is currently not open." )
The base service for admin site
index
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/admin_page/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/admin_page/app.py
MIT
def homepage() -> Response: """The homepage for the app""" cookie = request.cookies.get("cookie", "") # Render normal page response = make_response(render_template("index.html", user=cookie)) response.set_cookie("cookie", cookie if len(cookie) > 0 else "user") return response
The homepage for the app
homepage
python
sajjadium/ctf-archives
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/homepage/app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/homepage/app.py
MIT
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 mint(resource, bits=20, now=None, ext='', saltchars=8, stamp_seconds=False): """Mint a new hashcash stamp for 'resource' with 'bits' of collision 20 bits of collision is the default. 'ext' lets you add your own extensions to a minted stamp. Specify an extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val' FWIW, urllib.urlencode(dct).replace('&',';') comes close to the hashcash extension format. 'saltchars' specifies the length of the salt used; this version defaults 8 chars, rather than the C version's 16 chars. This still provides about 17 million salts per resource, per timestamp, before birthday paradox collisions occur. Really paranoid users can use a larger salt though. 'stamp_seconds' lets you add the option time elements to the datestamp. If you want more than just day, you get all the way down to seconds, even though the spec also allows hours/minutes without seconds. """ ver = "1" now = now or time() if stamp_seconds: ts = strftime("%y%m%d%H%M%S", localtime(now)) else: ts = strftime("%y%m%d", localtime(now)) challenge = "%s:"*6 % (ver, bits, ts, resource, ext, _salt(saltchars)) return challenge + _mint(challenge, bits)
Mint a new hashcash stamp for 'resource' with 'bits' of collision 20 bits of collision is the default. 'ext' lets you add your own extensions to a minted stamp. Specify an extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val' FWIW, urllib.urlencode(dct).replace('&',';') comes close to the hashcash extension format. 'saltchars' specifies the length of the salt used; this version defaults 8 chars, rather than the C version's 16 chars. This still provides about 17 million salts per resource, per timestamp, before birthday paradox collisions occur. Really paranoid users can use a larger salt though. 'stamp_seconds' lets you add the option time elements to the datestamp. If you want more than just day, you get all the way down to seconds, even though the spec also allows hours/minutes without seconds.
mint
python
sajjadium/ctf-archives
ctfs/Union/2021/pwn/nutty/hashcash.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Union/2021/pwn/nutty/hashcash.py
MIT
def _mint(challenge, bits): """Answer a 'generalized hashcash' challenge' Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter' This internal function accepts a generalized prefix 'challenge', and returns only a suffix that produces the requested SHA leading zeros. NOTE: Number of requested bits is rounded up to the nearest multiple of 4 """ counter = 0 hex_digits = int(ceil(bits/4.)) zeros = '0'*hex_digits while 1: digest = sha(challenge+hex(counter)[2:]).hexdigest() if digest[:hex_digits] == zeros: tries[0] = counter return hex(counter)[2:] counter += 1
Answer a 'generalized hashcash' challenge' Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter' This internal function accepts a generalized prefix 'challenge', and returns only a suffix that produces the requested SHA leading zeros. NOTE: Number of requested bits is rounded up to the nearest multiple of 4
_mint
python
sajjadium/ctf-archives
ctfs/Union/2021/pwn/nutty/hashcash.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Union/2021/pwn/nutty/hashcash.py
MIT
def check(stamp, resource=None, bits=None, check_expiration=None, ds_callback=None): """Check whether a stamp is valid Optionally, the stamp may be checked for a specific resource, and/or it may require a minimum bit value, and/or it may be checked for expiration, and/or it may be checked for double spending. If 'check_expiration' is specified, it should contain the number of seconds old a date field may be. Indicating days might be easier in many cases, e.g. >>> from hashcash import DAYS >>> check(stamp, check_expiration=28*DAYS) NOTE: Every valid (version 1) stamp must meet its claimed bit value NOTE: Check floor of 4-bit multiples (overly permissive in acceptance) """ if stamp.startswith('0:'): # Version 0 try: date, res, suffix = stamp[2:].split(':') except ValueError: #ERR.write("Malformed version 0 hashcash stamp!\n") return False if resource is not None and resource != res: return False elif check_expiration is not None: good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration)) if date < good_until: return False elif callable(ds_callback) and ds_callback(stamp): return False elif type(bits) is not int: return True else: hex_digits = int(floor(bits/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) elif stamp.startswith('1:'): # Version 1 try: claim, date, res, ext, rand, counter = stamp[2:].split(':') except ValueError: #ERR.write("Malformed version 1 hashcash stamp!\n") return False if resource is not None and resource != res: return False elif type(bits) is int and bits > int(claim): return False elif check_expiration is not None: good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration)) if date < good_until: return False elif callable(ds_callback) and ds_callback(stamp): return False else: hex_digits = int(floor(int(claim)/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) else: # Unknown ver or generalized hashcash #ERR.write("Unknown hashcash version: Minimal authentication!\n") if type(bits) is not int: return True elif resource is not None and stamp.find(resource) < 0: return False else: hex_digits = int(floor(bits/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits)
Check whether a stamp is valid Optionally, the stamp may be checked for a specific resource, and/or it may require a minimum bit value, and/or it may be checked for expiration, and/or it may be checked for double spending. If 'check_expiration' is specified, it should contain the number of seconds old a date field may be. Indicating days might be easier in many cases, e.g. >>> from hashcash import DAYS >>> check(stamp, check_expiration=28*DAYS) NOTE: Every valid (version 1) stamp must meet its claimed bit value NOTE: Check floor of 4-bit multiples (overly permissive in acceptance)
check
python
sajjadium/ctf-archives
ctfs/Union/2021/pwn/nutty/hashcash.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Union/2021/pwn/nutty/hashcash.py
MIT
def is_doublespent(stamp): """Placeholder for double spending callback function The check() function may accept a 'ds_callback' argument, e.g. check(stamp, "[email protected]", bits=20, ds_callback=is_doublespent) This placeholder simply reports stamps as not being double spent. """ return False
Placeholder for double spending callback function The check() function may accept a 'ds_callback' argument, e.g. check(stamp, "[email protected]", bits=20, ds_callback=is_doublespent) This placeholder simply reports stamps as not being double spent.
is_doublespent
python
sajjadium/ctf-archives
ctfs/Union/2021/pwn/nutty/hashcash.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Union/2021/pwn/nutty/hashcash.py
MIT
def expand_key(master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Round constants https://en.wikipedia.org/wiki/AES_key_schedule#Round_constants r_con = ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ) # Initialize round keys with raw key material. key_columns = [list(master_key[4*i:4*i+4]) for i in range(16)] iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (N_ROUNDS + 1) * 16: # Copy previous word. word = key_columns[-1].copy() # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 # XOR with equivalent word from previous iteration. word = [i^j for i, j in zip(word, key_columns[-iteration_size])] key_columns.append(word) full_key_stream = [ kb for key_column in key_columns for kb in key_column ] return [full_key_stream[i*64:(i+1)*64] for i in range(0,N_ROUNDS + 1, 1)]
Expands and returns a list of key matrices for the given master_key.
expand_key
python
sajjadium/ctf-archives
ctfs/UMDCTF/2024/crypto/haes/haes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UMDCTF/2024/crypto/haes/haes.py
MIT
def expand_key(master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Round constants https://en.wikipedia.org/wiki/AES_key_schedule#Round_constants r_con = ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ) # Initialize round keys with raw key material. key_columns = [list(master_key[4*i:4*i+4]) for i in range(16)] iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (N_ROUNDS + 1) * 16: # Copy previous word. word = key_columns[-1].copy() # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 # XOR with equivalent word from previous iteration. word = [i^j for i, j in zip(word, key_columns[-iteration_size])] key_columns.append(word) full_key_stream = [ kb for key_column in key_columns for kb in key_column ] return [full_key_stream[i*64:(i+1)*64] for i in range(0,N_ROUNDS + 1, 1)]
Expands and returns a list of key matrices for the given master_key.
expand_key
python
sajjadium/ctf-archives
ctfs/UMDCTF/2024/crypto/haes_2/haes_2.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/UMDCTF/2024/crypto/haes_2/haes_2.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