repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_python_api.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_python_api.py
from ctypes import * import unittest, sys from test import support ################################################################ # This section should be moved into ctypes\__init__.py, when it's ready. from _ctypes import PyObj_FromPtr ################################################################ from sys import getrefcount as grc if sys.version_info > (2, 4): c_py_ssize_t = c_size_t else: c_py_ssize_t = c_int class PythonAPITestCase(unittest.TestCase): def test_PyBytes_FromStringAndSize(self): PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize PyBytes_FromStringAndSize.restype = py_object PyBytes_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t self.assertEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc") @support.refcount_test def test_PyString_FromString(self): pythonapi.PyBytes_FromString.restype = py_object pythonapi.PyBytes_FromString.argtypes = (c_char_p,) s = b"abc" refcnt = grc(s) pyob = pythonapi.PyBytes_FromString(s) self.assertEqual(grc(s), refcnt) self.assertEqual(s, pyob) del pyob self.assertEqual(grc(s), refcnt) @support.refcount_test def test_PyLong_Long(self): ref42 = grc(42) pythonapi.PyLong_FromLong.restype = py_object self.assertEqual(pythonapi.PyLong_FromLong(42), 42) self.assertEqual(grc(42), ref42) pythonapi.PyLong_AsLong.argtypes = (py_object,) pythonapi.PyLong_AsLong.restype = c_long res = pythonapi.PyLong_AsLong(42) self.assertEqual(grc(res), ref42 + 1) del res self.assertEqual(grc(42), ref42) @support.refcount_test def test_PyObj_FromPtr(self): s = "abc def ghi jkl" ref = grc(s) # id(python-object) is the address pyobj = PyObj_FromPtr(id(s)) self.assertIs(s, pyobj) self.assertEqual(grc(s), ref + 1) del pyobj self.assertEqual(grc(s), ref) def test_PyOS_snprintf(self): PyOS_snprintf = pythonapi.PyOS_snprintf PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p buf = c_buffer(256) PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes") self.assertEqual(buf.value, b"Hello from ctypes") PyOS_snprintf(buf, sizeof(buf), b"Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3) self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)") # not enough arguments self.assertRaises(TypeError, PyOS_snprintf, buf) def test_pyobject_repr(self): self.assertEqual(repr(py_object()), "py_object(<NULL>)") self.assertEqual(repr(py_object(42)), "py_object(42)") self.assertEqual(repr(py_object(object)), "py_object(%r)" % object) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_returnfuncptrs.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_returnfuncptrs.py
import unittest from ctypes import * import _ctypes_test class ReturnFuncPtrTestCase(unittest.TestCase): def test_with_prototype(self): # The _ctypes_test shared lib/dll exports quite some functions for testing. # The get_strchr function returns a *pointer* to the C strchr function. dll = CDLL(_ctypes_test.__file__) get_strchr = dll.get_strchr get_strchr.restype = CFUNCTYPE(c_char_p, c_char_p, c_char) strchr = get_strchr() self.assertEqual(strchr(b"abcdef", b"b"), b"bcdef") self.assertEqual(strchr(b"abcdef", b"x"), None) self.assertEqual(strchr(b"abcdef", 98), b"bcdef") self.assertEqual(strchr(b"abcdef", 107), None) self.assertRaises(ArgumentError, strchr, b"abcdef", 3.0) self.assertRaises(TypeError, strchr, b"abcdef") def test_without_prototype(self): dll = CDLL(_ctypes_test.__file__) get_strchr = dll.get_strchr # the default 'c_int' would not work on systems where sizeof(int) != sizeof(void *) get_strchr.restype = c_void_p addr = get_strchr() # _CFuncPtr instances are now callable with an integer argument # which denotes a function address: strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)(addr) self.assertTrue(strchr(b"abcdef", b"b"), "bcdef") self.assertEqual(strchr(b"abcdef", b"x"), None) self.assertRaises(ArgumentError, strchr, b"abcdef", 3.0) self.assertRaises(TypeError, strchr, b"abcdef") def test_from_dll(self): dll = CDLL(_ctypes_test.__file__) # _CFuncPtr instances are now callable with a tuple argument # which denotes a function name and a dll: strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)(("my_strchr", dll)) self.assertTrue(strchr(b"abcdef", b"b"), "bcdef") self.assertEqual(strchr(b"abcdef", b"x"), None) self.assertRaises(ArgumentError, strchr, b"abcdef", 3.0) self.assertRaises(TypeError, strchr, b"abcdef") # Issue 6083: Reference counting bug def test_from_dll_refcount(self): class BadSequence(tuple): def __getitem__(self, key): if key == 0: return "my_strchr" if key == 1: return CDLL(_ctypes_test.__file__) raise IndexError # _CFuncPtr instances are now callable with a tuple argument # which denotes a function name and a dll: strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)( BadSequence(("my_strchr", CDLL(_ctypes_test.__file__)))) self.assertTrue(strchr(b"abcdef", b"b"), "bcdef") self.assertEqual(strchr(b"abcdef", b"x"), None) self.assertRaises(ArgumentError, strchr, b"abcdef", 3.0) self.assertRaises(TypeError, strchr, b"abcdef") if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_as_parameter.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_as_parameter.py
import unittest from ctypes import * from ctypes.test import need_symbol import _ctypes_test dll = CDLL(_ctypes_test.__file__) try: CALLBACK_FUNCTYPE = WINFUNCTYPE except NameError: # fake to enable this test on Linux CALLBACK_FUNCTYPE = CFUNCTYPE class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] class BasicWrapTestCase(unittest.TestCase): def wrap(self, param): return param @need_symbol('c_wchar') def test_wchar_parm(self): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] result = f(self.wrap(1), self.wrap("x"), self.wrap(3), self.wrap(4), self.wrap(5.0), self.wrap(6.0)) self.assertEqual(result, 139) self.assertIs(type(result), int) def test_pointers(self): f = dll._testfunc_p_p f.restype = POINTER(c_int) f.argtypes = [POINTER(c_int)] # This only works if the value c_int(42) passed to the # function is still alive while the pointer (the result) is # used. v = c_int(42) self.assertEqual(pointer(v).contents.value, 42) result = f(self.wrap(pointer(v))) self.assertEqual(type(result), POINTER(c_int)) self.assertEqual(result.contents.value, 42) # This on works... result = f(self.wrap(pointer(v))) self.assertEqual(result.contents.value, v.value) p = pointer(c_int(99)) result = f(self.wrap(p)) self.assertEqual(result.contents.value, 99) def test_shorts(self): f = dll._testfunc_callback_i_if args = [] expected = [262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] def callback(v): args.append(v) return v CallBack = CFUNCTYPE(c_int, c_int) cb = CallBack(callback) f(self.wrap(2**18), self.wrap(cb)) self.assertEqual(args, expected) ################################################################ def test_callbacks(self): f = dll._testfunc_callback_i_if f.restype = c_int f.argtypes = None MyCallback = CFUNCTYPE(c_int, c_int) def callback(value): #print "called back with", value return value cb = MyCallback(callback) result = f(self.wrap(-10), self.wrap(cb)) self.assertEqual(result, -18) # test with prototype f.argtypes = [c_int, MyCallback] cb = MyCallback(callback) result = f(self.wrap(-10), self.wrap(cb)) self.assertEqual(result, -18) result = f(self.wrap(-10), self.wrap(cb)) self.assertEqual(result, -18) AnotherCallback = CALLBACK_FUNCTYPE(c_int, c_int, c_int, c_int, c_int) # check that the prototype works: we call f with wrong # argument types cb = AnotherCallback(callback) self.assertRaises(ArgumentError, f, self.wrap(-10), self.wrap(cb)) def test_callbacks_2(self): # Can also use simple datatypes as argument type specifiers # for the callback function. # In this case the call receives an instance of that type f = dll._testfunc_callback_i_if f.restype = c_int MyCallback = CFUNCTYPE(c_int, c_int) f.argtypes = [c_int, MyCallback] def callback(value): #print "called back with", value self.assertEqual(type(value), int) return value cb = MyCallback(callback) result = f(self.wrap(-10), self.wrap(cb)) self.assertEqual(result, -18) def test_longlong_callbacks(self): f = dll._testfunc_callback_q_qf f.restype = c_longlong MyCallback = CFUNCTYPE(c_longlong, c_longlong) f.argtypes = [c_longlong, MyCallback] def callback(value): self.assertIsInstance(value, int) return value & 0x7FFFFFFF cb = MyCallback(callback) self.assertEqual(13577625587, int(f(self.wrap(1000000000000), self.wrap(cb)))) def test_byval(self): # without prototype ptin = POINT(1, 2) ptout = POINT() # EXPORT int _testfunc_byval(point in, point *pout) result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 3, 1, 2 self.assertEqual(got, expected) # with prototype ptin = POINT(101, 102) ptout = POINT() dll._testfunc_byval.argtypes = (POINT, POINTER(POINT)) dll._testfunc_byval.restype = c_int result = dll._testfunc_byval(self.wrap(ptin), byref(ptout)) got = result, ptout.x, ptout.y expected = 203, 101, 102 self.assertEqual(got, expected) def test_struct_return_2H(self): class S2H(Structure): _fields_ = [("x", c_short), ("y", c_short)] dll.ret_2h_func.restype = S2H dll.ret_2h_func.argtypes = [S2H] inp = S2H(99, 88) s2h = dll.ret_2h_func(self.wrap(inp)) self.assertEqual((s2h.x, s2h.y), (99*2, 88*3)) # Test also that the original struct was unmodified (i.e. was passed by # value) self.assertEqual((inp.x, inp.y), (99, 88)) def test_struct_return_8H(self): class S8I(Structure): _fields_ = [("a", c_int), ("b", c_int), ("c", c_int), ("d", c_int), ("e", c_int), ("f", c_int), ("g", c_int), ("h", c_int)] dll.ret_8i_func.restype = S8I dll.ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = dll.ret_8i_func(self.wrap(inp)) self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) def test_recursive_as_param(self): from ctypes import c_int class A(object): pass a = A() a._as_parameter_ = a with self.assertRaises(RecursionError): c_int.from_param(a) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class AsParamWrapper(object): def __init__(self, param): self._as_parameter_ = param class AsParamWrapperTestCase(BasicWrapTestCase): wrap = AsParamWrapper #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class AsParamPropertyWrapper(object): def __init__(self, param): self._param = param def getParameter(self): return self._param _as_parameter_ = property(getParameter) class AsParamPropertyWrapperTestCase(BasicWrapTestCase): wrap = AsParamPropertyWrapper #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_errno.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_errno.py
import unittest, os, errno import threading from ctypes import * from ctypes.util import find_library class Test(unittest.TestCase): def test_open(self): libc_name = find_library("c") if libc_name is None: raise unittest.SkipTest("Unable to find C library") libc = CDLL(libc_name, use_errno=True) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open(b"", 0), -1) self.assertEqual(get_errno(), errno.ENOENT) self.assertEqual(set_errno(32), errno.ENOENT) self.assertEqual(get_errno(), 32) def _worker(): set_errno(0) libc = CDLL(libc_name, use_errno=False) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open(b"", 0), -1) self.assertEqual(get_errno(), 0) t = threading.Thread(target=_worker) t.start() t.join() self.assertEqual(get_errno(), 32) set_errno(0) @unittest.skipUnless(os.name == "nt", 'Test specific to Windows') def test_GetLastError(self): dll = WinDLL("kernel32", use_last_error=True) GetModuleHandle = dll.GetModuleHandleA GetModuleHandle.argtypes = [c_wchar_p] self.assertEqual(0, GetModuleHandle("foo")) self.assertEqual(get_last_error(), 126) self.assertEqual(set_last_error(32), 126) self.assertEqual(get_last_error(), 32) def _worker(): set_last_error(0) dll = WinDLL("kernel32", use_last_error=False) GetModuleHandle = dll.GetModuleHandleW GetModuleHandle.argtypes = [c_wchar_p] GetModuleHandle("bar") self.assertEqual(get_last_error(), 0) t = threading.Thread(target=_worker) t.start() t.join() self.assertEqual(get_last_error(), 32) set_last_error(0) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_functions.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_functions.py
""" Here is probably the place to write the docs, since the test-cases show how the type behave. Later... """ from ctypes import * from ctypes.test import need_symbol import sys, unittest try: WINFUNCTYPE except NameError: # fake to enable this test on Linux WINFUNCTYPE = CFUNCTYPE import _ctypes_test dll = CDLL(_ctypes_test.__file__) if sys.platform == "win32": windll = WinDLL(_ctypes_test.__file__) class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] class RECT(Structure): _fields_ = [("left", c_int), ("top", c_int), ("right", c_int), ("bottom", c_int)] class FunctionTestCase(unittest.TestCase): def test_mro(self): # in Python 2.3, this raises TypeError: MRO conflict among bases classes, # in Python 2.2 it works. # # But in early versions of _ctypes.c, the result of tp_new # wasn't checked, and it even crashed Python. # Found by Greg Chapman. try: class X(object, Array): _length_ = 5 _type_ = "i" except TypeError: pass from _ctypes import _Pointer try: class X(object, _Pointer): pass except TypeError: pass from _ctypes import _SimpleCData try: class X(object, _SimpleCData): _type_ = "i" except TypeError: pass try: class X(object, Structure): _fields_ = [] except TypeError: pass @need_symbol('c_wchar') def test_wchar_parm(self): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] result = f(1, "x", 3, 4, 5.0, 6.0) self.assertEqual(result, 139) self.assertEqual(type(result), int) @need_symbol('c_wchar') def test_wchar_result(self): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_wchar result = f(0, 0, 0, 0, 0, 0) self.assertEqual(result, '\x00') def test_voidresult(self): f = dll._testfunc_v f.restype = None f.argtypes = [c_int, c_int, POINTER(c_int)] result = c_int() self.assertEqual(None, f(1, 2, byref(result))) self.assertEqual(result.value, 3) def test_intresult(self): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_int result = f(1, 2, 3, 4, 5.0, 6.0) self.assertEqual(result, 21) self.assertEqual(type(result), int) result = f(-1, -2, -3, -4, -5.0, -6.0) self.assertEqual(result, -21) self.assertEqual(type(result), int) # If we declare the function to return a short, # is the high part split off? f.restype = c_short result = f(1, 2, 3, 4, 5.0, 6.0) self.assertEqual(result, 21) self.assertEqual(type(result), int) result = f(1, 2, 3, 0x10004, 5.0, 6.0) self.assertEqual(result, 21) self.assertEqual(type(result), int) # You cannot assign character format codes as restype any longer self.assertRaises(TypeError, setattr, f, "restype", "i") def test_floatresult(self): f = dll._testfunc_f_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_float result = f(1, 2, 3, 4, 5.0, 6.0) self.assertEqual(result, 21) self.assertEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) self.assertEqual(result, -21) self.assertEqual(type(result), float) def test_doubleresult(self): f = dll._testfunc_d_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_double result = f(1, 2, 3, 4, 5.0, 6.0) self.assertEqual(result, 21) self.assertEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) self.assertEqual(result, -21) self.assertEqual(type(result), float) def test_longdoubleresult(self): f = dll._testfunc_D_bhilfD f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble] f.restype = c_longdouble result = f(1, 2, 3, 4, 5.0, 6.0) self.assertEqual(result, 21) self.assertEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) self.assertEqual(result, -21) self.assertEqual(type(result), float) @need_symbol('c_longlong') def test_longlongresult(self): f = dll._testfunc_q_bhilfd f.restype = c_longlong f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] result = f(1, 2, 3, 4, 5.0, 6.0) self.assertEqual(result, 21) f = dll._testfunc_q_bhilfdq f.restype = c_longlong f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double, c_longlong] result = f(1, 2, 3, 4, 5.0, 6.0, 21) self.assertEqual(result, 42) def test_stringresult(self): f = dll._testfunc_p_p f.argtypes = None f.restype = c_char_p result = f(b"123") self.assertEqual(result, b"123") result = f(None) self.assertEqual(result, None) def test_pointers(self): f = dll._testfunc_p_p f.restype = POINTER(c_int) f.argtypes = [POINTER(c_int)] # This only works if the value c_int(42) passed to the # function is still alive while the pointer (the result) is # used. v = c_int(42) self.assertEqual(pointer(v).contents.value, 42) result = f(pointer(v)) self.assertEqual(type(result), POINTER(c_int)) self.assertEqual(result.contents.value, 42) # This on works... result = f(pointer(v)) self.assertEqual(result.contents.value, v.value) p = pointer(c_int(99)) result = f(p) self.assertEqual(result.contents.value, 99) arg = byref(v) result = f(arg) self.assertNotEqual(result.contents, v.value) self.assertRaises(ArgumentError, f, byref(c_short(22))) # It is dangerous, however, because you don't control the lifetime # of the pointer: result = f(byref(c_int(99))) self.assertNotEqual(result.contents, 99) def test_errors(self): f = dll._testfunc_p_p f.restype = c_int class X(Structure): _fields_ = [("y", c_int)] self.assertRaises(TypeError, f, X()) #cannot convert parameter ################################################################ def test_shorts(self): f = dll._testfunc_callback_i_if args = [] expected = [262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] def callback(v): args.append(v) return v CallBack = CFUNCTYPE(c_int, c_int) cb = CallBack(callback) f(2**18, cb) self.assertEqual(args, expected) ################################################################ def test_callbacks(self): f = dll._testfunc_callback_i_if f.restype = c_int f.argtypes = None MyCallback = CFUNCTYPE(c_int, c_int) def callback(value): #print "called back with", value return value cb = MyCallback(callback) result = f(-10, cb) self.assertEqual(result, -18) # test with prototype f.argtypes = [c_int, MyCallback] cb = MyCallback(callback) result = f(-10, cb) self.assertEqual(result, -18) AnotherCallback = WINFUNCTYPE(c_int, c_int, c_int, c_int, c_int) # check that the prototype works: we call f with wrong # argument types cb = AnotherCallback(callback) self.assertRaises(ArgumentError, f, -10, cb) def test_callbacks_2(self): # Can also use simple datatypes as argument type specifiers # for the callback function. # In this case the call receives an instance of that type f = dll._testfunc_callback_i_if f.restype = c_int MyCallback = CFUNCTYPE(c_int, c_int) f.argtypes = [c_int, MyCallback] def callback(value): #print "called back with", value self.assertEqual(type(value), int) return value cb = MyCallback(callback) result = f(-10, cb) self.assertEqual(result, -18) @need_symbol('c_longlong') def test_longlong_callbacks(self): f = dll._testfunc_callback_q_qf f.restype = c_longlong MyCallback = CFUNCTYPE(c_longlong, c_longlong) f.argtypes = [c_longlong, MyCallback] def callback(value): self.assertIsInstance(value, int) return value & 0x7FFFFFFF cb = MyCallback(callback) self.assertEqual(13577625587, f(1000000000000, cb)) def test_errors(self): self.assertRaises(AttributeError, getattr, dll, "_xxx_yyy") self.assertRaises(ValueError, c_int.in_dll, dll, "_xxx_yyy") def test_byval(self): # without prototype ptin = POINT(1, 2) ptout = POINT() # EXPORT int _testfunc_byval(point in, point *pout) result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 3, 1, 2 self.assertEqual(got, expected) # with prototype ptin = POINT(101, 102) ptout = POINT() dll._testfunc_byval.argtypes = (POINT, POINTER(POINT)) dll._testfunc_byval.restype = c_int result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 203, 101, 102 self.assertEqual(got, expected) def test_struct_return_2H(self): class S2H(Structure): _fields_ = [("x", c_short), ("y", c_short)] dll.ret_2h_func.restype = S2H dll.ret_2h_func.argtypes = [S2H] inp = S2H(99, 88) s2h = dll.ret_2h_func(inp) self.assertEqual((s2h.x, s2h.y), (99*2, 88*3)) @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') def test_struct_return_2H_stdcall(self): class S2H(Structure): _fields_ = [("x", c_short), ("y", c_short)] windll.s_ret_2h_func.restype = S2H windll.s_ret_2h_func.argtypes = [S2H] s2h = windll.s_ret_2h_func(S2H(99, 88)) self.assertEqual((s2h.x, s2h.y), (99*2, 88*3)) def test_struct_return_8H(self): class S8I(Structure): _fields_ = [("a", c_int), ("b", c_int), ("c", c_int), ("d", c_int), ("e", c_int), ("f", c_int), ("g", c_int), ("h", c_int)] dll.ret_8i_func.restype = S8I dll.ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = dll.ret_8i_func(inp) self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') def test_struct_return_8H_stdcall(self): class S8I(Structure): _fields_ = [("a", c_int), ("b", c_int), ("c", c_int), ("d", c_int), ("e", c_int), ("f", c_int), ("g", c_int), ("h", c_int)] windll.s_ret_8i_func.restype = S8I windll.s_ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = windll.s_ret_8i_func(inp) self.assertEqual( (s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) def test_sf1651235(self): # see http://www.python.org/sf/1651235 proto = CFUNCTYPE(c_int, RECT, POINT) def callback(*args): return 0 callback = proto(callback) self.assertRaises(ArgumentError, lambda: callback((1, 2, 3, 4), POINT())) if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_objects.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_objects.py
r''' This tests the '_objects' attribute of ctypes instances. '_objects' holds references to objects that must be kept alive as long as the ctypes instance, to make sure that the memory buffer is valid. WARNING: The '_objects' attribute is exposed ONLY for debugging ctypes itself, it MUST NEVER BE MODIFIED! '_objects' is initialized to a dictionary on first use, before that it is None. Here is an array of string pointers: >>> from ctypes import * >>> array = (c_char_p * 5)() >>> print(array._objects) None >>> The memory block stores pointers to strings, and the strings itself assigned from Python must be kept. >>> array[4] = b'foo bar' >>> array._objects {'4': b'foo bar'} >>> array[4] b'foo bar' >>> It gets more complicated when the ctypes instance itself is contained in a 'base' object. >>> class X(Structure): ... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)] ... >>> x = X() >>> print(x._objects) None >>> The'array' attribute of the 'x' object shares part of the memory buffer of 'x' ('_b_base_' is either None, or the root object owning the memory block): >>> print(x.array._b_base_) # doctest: +ELLIPSIS <ctypes.test.test_objects.X object at 0x...> >>> >>> x.array[0] = b'spam spam spam' >>> x._objects {'0:2': b'spam spam spam'} >>> x.array._b_base_._objects {'0:2': b'spam spam spam'} >>> ''' import unittest, doctest import ctypes.test.test_objects class TestCase(unittest.TestCase): def test(self): failures, tests = doctest.testmod(ctypes.test.test_objects) self.assertFalse(failures, 'doctests failed, see output above') if __name__ == '__main__': doctest.testmod(ctypes.test.test_objects)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_macholib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_macholib.py
import os import sys import unittest # Bob Ippolito: # # Ok.. the code to find the filename for __getattr__ should look # something like: # # import os # from macholib.dyld import dyld_find # # def find_lib(name): # possible = ['lib'+name+'.dylib', name+'.dylib', # name+'.framework/'+name] # for dylib in possible: # try: # return os.path.realpath(dyld_find(dylib)) # except ValueError: # pass # raise ValueError, "%s not found" % (name,) # # It'll have output like this: # # >>> find_lib('pthread') # '/usr/lib/libSystem.B.dylib' # >>> find_lib('z') # '/usr/lib/libz.1.dylib' # >>> find_lib('IOKit') # '/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit' # # -bob from ctypes.macholib.dyld import dyld_find def find_lib(name): possible = ['lib'+name+'.dylib', name+'.dylib', name+'.framework/'+name] for dylib in possible: try: return os.path.realpath(dyld_find(dylib)) except ValueError: pass raise ValueError("%s not found" % (name,)) class MachOTest(unittest.TestCase): @unittest.skipUnless(sys.platform == "darwin", 'OSX-specific test') def test_find(self): self.assertEqual(find_lib('pthread'), '/usr/lib/libSystem.B.dylib') result = find_lib('z') # Issue #21093: dyld default search path includes $HOME/lib and # /usr/local/lib before /usr/lib, which caused test failures if # a local copy of libz exists in one of them. Now ignore the head # of the path. self.assertRegex(result, r".*/lib/libz\..*.*\.dylib") self.assertEqual(find_lib('IOKit'), '/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit') if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_loading.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_loading.py
from ctypes import * import os import sys import unittest import test.support from ctypes.util import find_library libc_name = None def setUpModule(): global libc_name if os.name == "nt": libc_name = find_library("c") elif sys.platform == "cygwin": libc_name = "cygwin1.dll" else: libc_name = find_library("c") if test.support.verbose: print("libc_name is", libc_name) class LoaderTest(unittest.TestCase): unknowndll = "xxrandomnamexx" def test_load(self): if libc_name is None: self.skipTest('could not find libc') CDLL(libc_name) CDLL(os.path.basename(libc_name)) self.assertRaises(OSError, CDLL, self.unknowndll) def test_load_version(self): if libc_name is None: self.skipTest('could not find libc') if os.path.basename(libc_name) != 'libc.so.6': self.skipTest('wrong libc path for test') cdll.LoadLibrary("libc.so.6") # linux uses version, libc 9 should not exist self.assertRaises(OSError, cdll.LoadLibrary, "libc.so.9") self.assertRaises(OSError, cdll.LoadLibrary, self.unknowndll) def test_find(self): for name in ("c", "m"): lib = find_library(name) if lib: cdll.LoadLibrary(lib) CDLL(lib) @unittest.skipUnless(os.name == "nt", 'test specific to Windows') def test_load_library(self): # CRT is no longer directly loadable. See issue23606 for the # discussion about alternative approaches. #self.assertIsNotNone(libc_name) if test.support.verbose: print(find_library("kernel32")) print(find_library("user32")) if os.name == "nt": windll.kernel32.GetModuleHandleW windll["kernel32"].GetModuleHandleW windll.LoadLibrary("kernel32").GetModuleHandleW WinDLL("kernel32").GetModuleHandleW # embedded null character self.assertRaises(ValueError, windll.LoadLibrary, "kernel32\0") @unittest.skipUnless(os.name == "nt", 'test specific to Windows') def test_load_ordinal_functions(self): import _ctypes_test dll = WinDLL(_ctypes_test.__file__) # We load the same function both via ordinal and name func_ord = dll[2] func_name = dll.GetString # addressof gets the address where the function pointer is stored a_ord = addressof(func_ord) a_name = addressof(func_name) f_ord_addr = c_void_p.from_address(a_ord).value f_name_addr = c_void_p.from_address(a_name).value self.assertEqual(hex(f_ord_addr), hex(f_name_addr)) self.assertRaises(AttributeError, dll.__getitem__, 1234) @unittest.skipUnless(os.name == "nt", 'Windows-specific test') def test_1703286_A(self): from _ctypes import LoadLibrary, FreeLibrary # On winXP 64-bit, advapi32 loads at an address that does # NOT fit into a 32-bit integer. FreeLibrary must be able # to accept this address. # These are tests for http://www.python.org/sf/1703286 handle = LoadLibrary("advapi32") FreeLibrary(handle) @unittest.skipUnless(os.name == "nt", 'Windows-specific test') def test_1703286_B(self): # Since on winXP 64-bit advapi32 loads like described # above, the (arbitrarily selected) CloseEventLog function # also has a high address. 'call_function' should accept # addresses so large. from _ctypes import call_function advapi32 = windll.advapi32 # Calling CloseEventLog with a NULL argument should fail, # but the call should not segfault or so. self.assertEqual(0, advapi32.CloseEventLog(None)) windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p windll.kernel32.GetProcAddress.restype = c_void_p proc = windll.kernel32.GetProcAddress(advapi32._handle, b"CloseEventLog") self.assertTrue(proc) # This is the real test: call the function via 'call_function' self.assertEqual(0, call_function(proc, (None,))) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_random_things.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_random_things.py
from ctypes import * import unittest, sys def callback_func(arg): 42 / arg raise ValueError(arg) @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') class call_function_TestCase(unittest.TestCase): # _ctypes.call_function is deprecated and private, but used by # Gary Bishp's readline module. If we have it, we must test it as well. def test(self): from _ctypes import call_function windll.kernel32.LoadLibraryA.restype = c_void_p windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p windll.kernel32.GetProcAddress.restype = c_void_p hdll = windll.kernel32.LoadLibraryA(b"kernel32") funcaddr = windll.kernel32.GetProcAddress(hdll, b"GetModuleHandleA") self.assertEqual(call_function(funcaddr, (None,)), windll.kernel32.GetModuleHandleA(None)) class CallbackTracbackTestCase(unittest.TestCase): # When an exception is raised in a ctypes callback function, the C # code prints a traceback. # # This test makes sure the exception types *and* the exception # value is printed correctly. # # Changed in 0.9.3: No longer is '(in callback)' prepended to the # error message - instead an additional frame for the C code is # created, then a full traceback printed. When SystemExit is # raised in a callback function, the interpreter exits. def capture_stderr(self, func, *args, **kw): # helper - call function 'func', and return the captured stderr import io old_stderr = sys.stderr logger = sys.stderr = io.StringIO() try: func(*args, **kw) finally: sys.stderr = old_stderr return logger.getvalue() def test_ValueError(self): cb = CFUNCTYPE(c_int, c_int)(callback_func) out = self.capture_stderr(cb, 42) self.assertEqual(out.splitlines()[-1], "ValueError: 42") def test_IntegerDivisionError(self): cb = CFUNCTYPE(c_int, c_int)(callback_func) out = self.capture_stderr(cb, 0) self.assertEqual(out.splitlines()[-1][:19], "ZeroDivisionError: ") def test_FloatDivisionError(self): cb = CFUNCTYPE(c_int, c_double)(callback_func) out = self.capture_stderr(cb, 0.0) self.assertEqual(out.splitlines()[-1][:19], "ZeroDivisionError: ") def test_TypeErrorDivisionError(self): cb = CFUNCTYPE(c_int, c_char_p)(callback_func) out = self.capture_stderr(cb, b"spam") self.assertEqual(out.splitlines()[-1], "TypeError: " "unsupported operand type(s) for /: 'int' and 'bytes'") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_sizes.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_sizes.py
# Test specifically-sized containers. from ctypes import * import unittest class SizesTestCase(unittest.TestCase): def test_8(self): self.assertEqual(1, sizeof(c_int8)) self.assertEqual(1, sizeof(c_uint8)) def test_16(self): self.assertEqual(2, sizeof(c_int16)) self.assertEqual(2, sizeof(c_uint16)) def test_32(self): self.assertEqual(4, sizeof(c_int32)) self.assertEqual(4, sizeof(c_uint32)) def test_64(self): self.assertEqual(8, sizeof(c_int64)) self.assertEqual(8, sizeof(c_uint64)) def test_size_t(self): self.assertEqual(sizeof(c_void_p), sizeof(c_size_t)) def test_ssize_t(self): self.assertEqual(sizeof(c_void_p), sizeof(c_ssize_t)) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_unaligned_structures.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_unaligned_structures.py
import sys, unittest from ctypes import * structures = [] byteswapped_structures = [] if sys.byteorder == "little": SwappedStructure = BigEndianStructure else: SwappedStructure = LittleEndianStructure for typ in [c_short, c_int, c_long, c_longlong, c_float, c_double, c_ushort, c_uint, c_ulong, c_ulonglong]: class X(Structure): _pack_ = 1 _fields_ = [("pad", c_byte), ("value", typ)] class Y(SwappedStructure): _pack_ = 1 _fields_ = [("pad", c_byte), ("value", typ)] structures.append(X) byteswapped_structures.append(Y) class TestStructures(unittest.TestCase): def test_native(self): for typ in structures: ## print typ.value self.assertEqual(typ.value.offset, 1) o = typ() o.value = 4 self.assertEqual(o.value, 4) def test_swapped(self): for typ in byteswapped_structures: ## print >> sys.stderr, typ.value self.assertEqual(typ.value.offset, 1) o = typ() o.value = 4 self.assertEqual(o.value, 4) if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_pickling.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_pickling.py
import unittest import pickle from ctypes import * import _ctypes_test dll = CDLL(_ctypes_test.__file__) class X(Structure): _fields_ = [("a", c_int), ("b", c_double)] init_called = 0 def __init__(self, *args, **kw): X.init_called += 1 self.x = 42 class Y(X): _fields_ = [("str", c_char_p)] class PickleTest: def dumps(self, item): return pickle.dumps(item, self.proto) def loads(self, item): return pickle.loads(item) def test_simple(self): for src in [ c_int(42), c_double(3.14), ]: dst = self.loads(self.dumps(src)) self.assertEqual(src.__dict__, dst.__dict__) self.assertEqual(memoryview(src).tobytes(), memoryview(dst).tobytes()) def test_struct(self): X.init_called = 0 x = X() x.a = 42 self.assertEqual(X.init_called, 1) y = self.loads(self.dumps(x)) # loads must NOT call __init__ self.assertEqual(X.init_called, 1) # ctypes instances are identical when the instance __dict__ # and the memory buffer are identical self.assertEqual(y.__dict__, x.__dict__) self.assertEqual(memoryview(y).tobytes(), memoryview(x).tobytes()) def test_unpickable(self): # ctypes objects that are pointers or contain pointers are # unpickable. self.assertRaises(ValueError, lambda: self.dumps(Y())) prototype = CFUNCTYPE(c_int) for item in [ c_char_p(), c_wchar_p(), c_void_p(), pointer(c_int(42)), dll._testfunc_p_p, prototype(lambda: 42), ]: self.assertRaises(ValueError, lambda: self.dumps(item)) def test_wchar(self): self.dumps(c_char(b"x")) # Issue 5049 self.dumps(c_wchar("x")) for proto in range(pickle.HIGHEST_PROTOCOL + 1): name = 'PickleTest_%s' % proto globals()[name] = type(name, (PickleTest, unittest.TestCase), {'proto': proto}) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_keeprefs.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_keeprefs.py
from ctypes import * import unittest class SimpleTestCase(unittest.TestCase): def test_cint(self): x = c_int() self.assertEqual(x._objects, None) x.value = 42 self.assertEqual(x._objects, None) x = c_int(99) self.assertEqual(x._objects, None) def test_ccharp(self): x = c_char_p() self.assertEqual(x._objects, None) x.value = b"abc" self.assertEqual(x._objects, b"abc") x = c_char_p(b"spam") self.assertEqual(x._objects, b"spam") class StructureTestCase(unittest.TestCase): def test_cint_struct(self): class X(Structure): _fields_ = [("a", c_int), ("b", c_int)] x = X() self.assertEqual(x._objects, None) x.a = 42 x.b = 99 self.assertEqual(x._objects, None) def test_ccharp_struct(self): class X(Structure): _fields_ = [("a", c_char_p), ("b", c_char_p)] x = X() self.assertEqual(x._objects, None) x.a = b"spam" x.b = b"foo" self.assertEqual(x._objects, {"0": b"spam", "1": b"foo"}) def test_struct_struct(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] class RECT(Structure): _fields_ = [("ul", POINT), ("lr", POINT)] r = RECT() r.ul.x = 0 r.ul.y = 1 r.lr.x = 2 r.lr.y = 3 self.assertEqual(r._objects, None) r = RECT() pt = POINT(1, 2) r.ul = pt self.assertEqual(r._objects, {'0': {}}) r.ul.x = 22 r.ul.y = 44 self.assertEqual(r._objects, {'0': {}}) r.lr = POINT() self.assertEqual(r._objects, {'0': {}, '1': {}}) class ArrayTestCase(unittest.TestCase): def test_cint_array(self): INTARR = c_int * 3 ia = INTARR() self.assertEqual(ia._objects, None) ia[0] = 1 ia[1] = 2 ia[2] = 3 self.assertEqual(ia._objects, None) class X(Structure): _fields_ = [("x", c_int), ("a", INTARR)] x = X() x.x = 1000 x.a[0] = 42 x.a[1] = 96 self.assertEqual(x._objects, None) x.a = ia self.assertEqual(x._objects, {'1': {}}) class PointerTestCase(unittest.TestCase): def test_p_cint(self): i = c_int(42) x = pointer(i) self.assertEqual(x._objects, {'1': i}) class DeletePointerTestCase(unittest.TestCase): @unittest.skip('test disabled') def test_X(self): class X(Structure): _fields_ = [("p", POINTER(c_char_p))] x = X() i = c_char_p("abc def") from sys import getrefcount as grc print("2?", grc(i)) x.p = pointer(i) print("3?", grc(i)) for i in range(320): c_int(99) x.p[0] print(x.p[0]) ## del x ## print "2?", grc(i) ## del i import gc gc.collect() for i in range(320): c_int(99) x.p[0] print(x.p[0]) print(x.p.contents) ## print x._objects x.p[0] = "spam spam" ## print x.p[0] print("+" * 42) print(x._objects) class PointerToStructure(unittest.TestCase): def test(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] class RECT(Structure): _fields_ = [("a", POINTER(POINT)), ("b", POINTER(POINT))] r = RECT() p1 = POINT(1, 2) r.a = pointer(p1) r.b = pointer(p1) ## from pprint import pprint as pp ## pp(p1._objects) ## pp(r._objects) r.a[0].x = 42 r.a[0].y = 99 # to avoid leaking when tests are run several times # clean up the types left in the cache. from ctypes import _pointer_type_cache del _pointer_type_cache[POINT] if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_funcptr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_funcptr.py
import unittest from ctypes import * try: WINFUNCTYPE except NameError: # fake to enable this test on Linux WINFUNCTYPE = CFUNCTYPE import _ctypes_test lib = CDLL(_ctypes_test.__file__) class CFuncPtrTestCase(unittest.TestCase): def test_basic(self): X = WINFUNCTYPE(c_int, c_int, c_int) def func(*args): return len(args) x = X(func) self.assertEqual(x.restype, c_int) self.assertEqual(x.argtypes, (c_int, c_int)) self.assertEqual(sizeof(x), sizeof(c_voidp)) self.assertEqual(sizeof(X), sizeof(c_voidp)) def test_first(self): StdCallback = WINFUNCTYPE(c_int, c_int, c_int) CdeclCallback = CFUNCTYPE(c_int, c_int, c_int) def func(a, b): return a + b s = StdCallback(func) c = CdeclCallback(func) self.assertEqual(s(1, 2), 3) self.assertEqual(c(1, 2), 3) # The following no longer raises a TypeError - it is now # possible, as in C, to call cdecl functions with more parameters. #self.assertRaises(TypeError, c, 1, 2, 3) self.assertEqual(c(1, 2, 3, 4, 5, 6), 3) if not WINFUNCTYPE is CFUNCTYPE: self.assertRaises(TypeError, s, 1, 2, 3) def test_structures(self): WNDPROC = WINFUNCTYPE(c_long, c_int, c_int, c_int, c_int) def wndproc(hwnd, msg, wParam, lParam): return hwnd + msg + wParam + lParam HINSTANCE = c_int HICON = c_int HCURSOR = c_int LPCTSTR = c_char_p class WNDCLASS(Structure): _fields_ = [("style", c_uint), ("lpfnWndProc", WNDPROC), ("cbClsExtra", c_int), ("cbWndExtra", c_int), ("hInstance", HINSTANCE), ("hIcon", HICON), ("hCursor", HCURSOR), ("lpszMenuName", LPCTSTR), ("lpszClassName", LPCTSTR)] wndclass = WNDCLASS() wndclass.lpfnWndProc = WNDPROC(wndproc) WNDPROC_2 = WINFUNCTYPE(c_long, c_int, c_int, c_int, c_int) # This is no longer true, now that WINFUNCTYPE caches created types internally. ## # CFuncPtr subclasses are compared by identity, so this raises a TypeError: ## self.assertRaises(TypeError, setattr, wndclass, ## "lpfnWndProc", WNDPROC_2(wndproc)) # instead: self.assertIs(WNDPROC, WNDPROC_2) # 'wndclass.lpfnWndProc' leaks 94 references. Why? self.assertEqual(wndclass.lpfnWndProc(1, 2, 3, 4), 10) f = wndclass.lpfnWndProc del wndclass del wndproc self.assertEqual(f(10, 11, 12, 13), 46) def test_dllfunctions(self): def NoNullHandle(value): if not value: raise WinError() return value strchr = lib.my_strchr strchr.restype = c_char_p strchr.argtypes = (c_char_p, c_char) self.assertEqual(strchr(b"abcdefghi", b"b"), b"bcdefghi") self.assertEqual(strchr(b"abcdefghi", b"x"), None) strtok = lib.my_strtok strtok.restype = c_char_p # Neither of this does work: strtok changes the buffer it is passed ## strtok.argtypes = (c_char_p, c_char_p) ## strtok.argtypes = (c_string, c_char_p) def c_string(init): size = len(init) + 1 return (c_char*size)(*init) s = b"a\nb\nc" b = c_string(s) ## b = (c_char * (len(s)+1))() ## b.value = s ## b = c_string(s) self.assertEqual(strtok(b, b"\n"), b"a") self.assertEqual(strtok(None, b"\n"), b"b") self.assertEqual(strtok(None, b"\n"), b"c") self.assertEqual(strtok(None, b"\n"), None) def test_abstract(self): from ctypes import _CFuncPtr self.assertRaises(TypeError, _CFuncPtr, 13, "name", 42, "iid") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/__main__.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/__main__.py
from ctypes.test import load_tests import unittest unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_refcounts.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_refcounts.py
import unittest from test import support import ctypes import gc MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong) import _ctypes_test dll = ctypes.CDLL(_ctypes_test.__file__) class RefcountTestCase(unittest.TestCase): @support.refcount_test def test_1(self): from sys import getrefcount as grc f = dll._testfunc_callback_i_if f.restype = ctypes.c_int f.argtypes = [ctypes.c_int, MyCallback] def callback(value): #print "called back with", value return value self.assertEqual(grc(callback), 2) cb = MyCallback(callback) self.assertGreater(grc(callback), 2) result = f(-10, cb) self.assertEqual(result, -18) cb = None gc.collect() self.assertEqual(grc(callback), 2) @support.refcount_test def test_refcount(self): from sys import getrefcount as grc def func(*args): pass # this is the standard refcount for func self.assertEqual(grc(func), 2) # the CFuncPtr instance holds at least one refcount on func: f = OtherCallback(func) self.assertGreater(grc(func), 2) # and may release it again del f self.assertGreaterEqual(grc(func), 2) # but now it must be gone gc.collect() self.assertEqual(grc(func), 2) class X(ctypes.Structure): _fields_ = [("a", OtherCallback)] x = X() x.a = OtherCallback(func) # the CFuncPtr instance holds at least one refcount on func: self.assertGreater(grc(func), 2) # and may release it again del x self.assertGreaterEqual(grc(func), 2) # and now it must be gone again gc.collect() self.assertEqual(grc(func), 2) f = OtherCallback(func) # the CFuncPtr instance holds at least one refcount on func: self.assertGreater(grc(func), 2) # create a cycle f.cycle = f del f gc.collect() self.assertEqual(grc(func), 2) class AnotherLeak(unittest.TestCase): def test_callback(self): import sys proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int) def func(a, b): return a * b * 2 f = proto(func) a = sys.getrefcount(ctypes.c_int) f(1, 2) self.assertEqual(sys.getrefcount(ctypes.c_int), a) if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_checkretval.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_checkretval.py
import unittest from ctypes import * from ctypes.test import need_symbol class CHECKED(c_int): def _check_retval_(value): # Receives a CHECKED instance. return str(value.value) _check_retval_ = staticmethod(_check_retval_) class Test(unittest.TestCase): def test_checkretval(self): import _ctypes_test dll = CDLL(_ctypes_test.__file__) self.assertEqual(42, dll._testfunc_p_p(42)) dll._testfunc_p_p.restype = CHECKED self.assertEqual("42", dll._testfunc_p_p(42)) dll._testfunc_p_p.restype = None self.assertEqual(None, dll._testfunc_p_p(42)) del dll._testfunc_p_p.restype self.assertEqual(42, dll._testfunc_p_p(42)) @need_symbol('oledll') def test_oledll(self): self.assertRaises(OSError, oledll.oleaut32.CreateTypeLib2, 0, None, None) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_strings.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_strings.py
import unittest from ctypes import * from ctypes.test import need_symbol class StringArrayTestCase(unittest.TestCase): def test(self): BUF = c_char * 4 buf = BUF(b"a", b"b", b"c") self.assertEqual(buf.value, b"abc") self.assertEqual(buf.raw, b"abc\000") buf.value = b"ABCD" self.assertEqual(buf.value, b"ABCD") self.assertEqual(buf.raw, b"ABCD") buf.value = b"x" self.assertEqual(buf.value, b"x") self.assertEqual(buf.raw, b"x\000CD") buf[1] = b"Z" self.assertEqual(buf.value, b"xZCD") self.assertEqual(buf.raw, b"xZCD") self.assertRaises(ValueError, setattr, buf, "value", b"aaaaaaaa") self.assertRaises(TypeError, setattr, buf, "value", 42) def test_c_buffer_value(self): buf = c_buffer(32) buf.value = b"Hello, World" self.assertEqual(buf.value, b"Hello, World") self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"Hello, World")) self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc")) self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100)) def test_c_buffer_raw(self): buf = c_buffer(32) buf.raw = memoryview(b"Hello, World") self.assertEqual(buf.value, b"Hello, World") self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc")) self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100)) def test_param_1(self): BUF = c_char * 4 buf = BUF() ## print c_char_p.from_param(buf) def test_param_2(self): BUF = c_char * 4 buf = BUF() ## print BUF.from_param(c_char_p("python")) ## print BUF.from_param(BUF(*"pyth")) def test_del_segfault(self): BUF = c_char * 4 buf = BUF() with self.assertRaises(AttributeError): del buf.raw @need_symbol('c_wchar') class WStringArrayTestCase(unittest.TestCase): def test(self): BUF = c_wchar * 4 buf = BUF("a", "b", "c") self.assertEqual(buf.value, "abc") buf.value = "ABCD" self.assertEqual(buf.value, "ABCD") buf.value = "x" self.assertEqual(buf.value, "x") buf[1] = "Z" self.assertEqual(buf.value, "xZCD") @unittest.skipIf(sizeof(c_wchar) < 4, "sizeof(wchar_t) is smaller than 4 bytes") def test_nonbmp(self): u = chr(0x10ffff) w = c_wchar(u) self.assertEqual(w.value, u) class StringTestCase(unittest.TestCase): @unittest.skip('test disabled') def test_basic_strings(self): cs = c_string("abcdef") # Cannot call len on a c_string any longer self.assertRaises(TypeError, len, cs) self.assertEqual(sizeof(cs), 7) # The value property is the string up to the first terminating NUL. self.assertEqual(cs.value, "abcdef") self.assertEqual(c_string("abc\000def").value, "abc") # The raw property is the total buffer contents: self.assertEqual(cs.raw, "abcdef\000") self.assertEqual(c_string("abc\000def").raw, "abc\000def\000") # We can change the value: cs.value = "ab" self.assertEqual(cs.value, "ab") self.assertEqual(cs.raw, "ab\000\000\000\000\000") cs.raw = "XY" self.assertEqual(cs.value, "XY") self.assertEqual(cs.raw, "XY\000\000\000\000\000") self.assertRaises(TypeError, c_string, "123") @unittest.skip('test disabled') def test_sized_strings(self): # New in releases later than 0.4.0: self.assertRaises(TypeError, c_string, None) # New in releases later than 0.4.0: # c_string(number) returns an empty string of size number self.assertEqual(len(c_string(32).raw), 32) self.assertRaises(ValueError, c_string, -1) self.assertRaises(ValueError, c_string, 0) # These tests fail, because it is no longer initialized ## self.assertEqual(c_string(2).value, "") ## self.assertEqual(c_string(2).raw, "\000\000") self.assertEqual(c_string(2).raw[-1], "\000") self.assertEqual(len(c_string(2).raw), 2) @unittest.skip('test disabled') def test_initialized_strings(self): self.assertEqual(c_string("ab", 4).raw[:2], "ab") self.assertEqual(c_string("ab", 4).raw[:2:], "ab") self.assertEqual(c_string("ab", 4).raw[:2:-1], "ba") self.assertEqual(c_string("ab", 4).raw[:2:2], "a") self.assertEqual(c_string("ab", 4).raw[-1], "\000") self.assertEqual(c_string("ab", 2).raw, "a\000") @unittest.skip('test disabled') def test_toolong(self): cs = c_string("abcdef") # Much too long string: self.assertRaises(ValueError, setattr, cs, "value", "123456789012345") # One char too long values: self.assertRaises(ValueError, setattr, cs, "value", "1234567") @unittest.skip('test disabled') def test_perf(self): check_perf() @need_symbol('c_wchar') class WStringTestCase(unittest.TestCase): def test_wchar(self): c_wchar("x") repr(byref(c_wchar("x"))) c_wchar("x") @unittest.skip('test disabled') def test_basic_wstrings(self): cs = c_wstring("abcdef") # XXX This behaviour is about to change: # len returns the size of the internal buffer in bytes. # This includes the terminating NUL character. self.assertEqual(sizeof(cs), 14) # The value property is the string up to the first terminating NUL. self.assertEqual(cs.value, "abcdef") self.assertEqual(c_wstring("abc\000def").value, "abc") self.assertEqual(c_wstring("abc\000def").value, "abc") # The raw property is the total buffer contents: self.assertEqual(cs.raw, "abcdef\000") self.assertEqual(c_wstring("abc\000def").raw, "abc\000def\000") # We can change the value: cs.value = "ab" self.assertEqual(cs.value, "ab") self.assertEqual(cs.raw, "ab\000\000\000\000\000") self.assertRaises(TypeError, c_wstring, "123") self.assertRaises(ValueError, c_wstring, 0) @unittest.skip('test disabled') def test_toolong(self): cs = c_wstring("abcdef") # Much too long string: self.assertRaises(ValueError, setattr, cs, "value", "123456789012345") # One char too long values: self.assertRaises(ValueError, setattr, cs, "value", "1234567") def run_test(rep, msg, func, arg): items = range(rep) from time import perf_counter as clock start = clock() for i in items: func(arg); func(arg); func(arg); func(arg); func(arg) stop = clock() print("%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))) def check_perf(): # Construct 5 objects REP = 200000 run_test(REP, "c_string(None)", c_string, None) run_test(REP, "c_string('abc')", c_string, 'abc') # Python 2.3 -OO, win2k, P4 700 MHz: # # c_string(None): 1.75 us # c_string('abc'): 2.74 us # Python 2.2 -OO, win2k, P4 700 MHz: # # c_string(None): 2.95 us # c_string('abc'): 3.67 us if __name__ == '__main__': ## check_perf() unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_internals.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_internals.py
# This tests the internal _objects attribute import unittest from ctypes import * from sys import getrefcount as grc # XXX This test must be reviewed for correctness!!! # ctypes' types are container types. # # They have an internal memory block, which only consists of some bytes, # but it has to keep references to other objects as well. This is not # really needed for trivial C types like int or char, but it is important # for aggregate types like strings or pointers in particular. # # What about pointers? class ObjectsTestCase(unittest.TestCase): def assertSame(self, a, b): self.assertEqual(id(a), id(b)) def test_ints(self): i = 42000123 refcnt = grc(i) ci = c_int(i) self.assertEqual(refcnt, grc(i)) self.assertEqual(ci._objects, None) def test_c_char_p(self): s = b"Hello, World" refcnt = grc(s) cs = c_char_p(s) self.assertEqual(refcnt + 1, grc(s)) self.assertSame(cs._objects, s) def test_simple_struct(self): class X(Structure): _fields_ = [("a", c_int), ("b", c_int)] a = 421234 b = 421235 x = X() self.assertEqual(x._objects, None) x.a = a x.b = b self.assertEqual(x._objects, None) def test_embedded_structs(self): class X(Structure): _fields_ = [("a", c_int), ("b", c_int)] class Y(Structure): _fields_ = [("x", X), ("y", X)] y = Y() self.assertEqual(y._objects, None) x1, x2 = X(), X() y.x, y.y = x1, x2 self.assertEqual(y._objects, {"0": {}, "1": {}}) x1.a, x2.b = 42, 93 self.assertEqual(y._objects, {"0": {}, "1": {}}) def test_xxx(self): class X(Structure): _fields_ = [("a", c_char_p), ("b", c_char_p)] class Y(Structure): _fields_ = [("x", X), ("y", X)] s1 = b"Hello, World" s2 = b"Hallo, Welt" x = X() x.a = s1 x.b = s2 self.assertEqual(x._objects, {"0": s1, "1": s2}) y = Y() y.x = x self.assertEqual(y._objects, {"0": {"0": s1, "1": s2}}) ## x = y.x ## del y ## print x._b_base_._objects def test_ptr_struct(self): class X(Structure): _fields_ = [("data", POINTER(c_int))] A = c_int*4 a = A(11, 22, 33, 44) self.assertEqual(a._objects, None) x = X() x.data = a ##XXX print x._objects ##XXX print x.data[0] ##XXX print x.data._objects if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_parameters.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_parameters.py
import unittest from ctypes.test import need_symbol import test.support class SimpleTypesTestCase(unittest.TestCase): def setUp(self): import ctypes try: from _ctypes import set_conversion_mode except ImportError: pass else: self.prev_conv_mode = set_conversion_mode("ascii", "strict") def tearDown(self): try: from _ctypes import set_conversion_mode except ImportError: pass else: set_conversion_mode(*self.prev_conv_mode) def test_subclasses(self): from ctypes import c_void_p, c_char_p # ctypes 0.9.5 and before did overwrite from_param in SimpleType_new class CVOIDP(c_void_p): def from_param(cls, value): return value * 2 from_param = classmethod(from_param) class CCHARP(c_char_p): def from_param(cls, value): return value * 4 from_param = classmethod(from_param) self.assertEqual(CVOIDP.from_param("abc"), "abcabc") self.assertEqual(CCHARP.from_param("abc"), "abcabcabcabc") @need_symbol('c_wchar_p') def test_subclasses_c_wchar_p(self): from ctypes import c_wchar_p class CWCHARP(c_wchar_p): def from_param(cls, value): return value * 3 from_param = classmethod(from_param) self.assertEqual(CWCHARP.from_param("abc"), "abcabcabc") # XXX Replace by c_char_p tests def test_cstrings(self): from ctypes import c_char_p # c_char_p.from_param on a Python String packs the string # into a cparam object s = b"123" self.assertIs(c_char_p.from_param(s)._obj, s) # new in 0.9.1: convert (encode) unicode to ascii self.assertEqual(c_char_p.from_param(b"123")._obj, b"123") self.assertRaises(TypeError, c_char_p.from_param, "123\377") self.assertRaises(TypeError, c_char_p.from_param, 42) # calling c_char_p.from_param with a c_char_p instance # returns the argument itself: a = c_char_p(b"123") self.assertIs(c_char_p.from_param(a), a) @need_symbol('c_wchar_p') def test_cw_strings(self): from ctypes import c_wchar_p c_wchar_p.from_param("123") self.assertRaises(TypeError, c_wchar_p.from_param, 42) self.assertRaises(TypeError, c_wchar_p.from_param, b"123\377") pa = c_wchar_p.from_param(c_wchar_p("123")) self.assertEqual(type(pa), c_wchar_p) def test_int_pointers(self): from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer LPINT = POINTER(c_int) ## p = pointer(c_int(42)) ## x = LPINT.from_param(p) x = LPINT.from_param(pointer(c_int(42))) self.assertEqual(x.contents.value, 42) self.assertEqual(LPINT(c_int(42)).contents.value, 42) self.assertEqual(LPINT.from_param(None), None) if c_int != c_long: self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42))) self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42))) self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42))) def test_byref_pointer(self): # The from_param class method of POINTER(typ) classes accepts what is # returned by byref(obj), it type(obj) == typ from ctypes import c_short, c_uint, c_int, c_long, POINTER, byref LPINT = POINTER(c_int) LPINT.from_param(byref(c_int(42))) self.assertRaises(TypeError, LPINT.from_param, byref(c_short(22))) if c_int != c_long: self.assertRaises(TypeError, LPINT.from_param, byref(c_long(22))) self.assertRaises(TypeError, LPINT.from_param, byref(c_uint(22))) def test_byref_pointerpointer(self): # See above from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref LPLPINT = POINTER(POINTER(c_int)) LPLPINT.from_param(byref(pointer(c_int(42)))) self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_short(22)))) if c_int != c_long: self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_long(22)))) self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_uint(22)))) def test_array_pointers(self): from ctypes import c_short, c_uint, c_int, c_long, POINTER INTARRAY = c_int * 3 ia = INTARRAY() self.assertEqual(len(ia), 3) self.assertEqual([ia[i] for i in range(3)], [0, 0, 0]) # Pointers are only compatible with arrays containing items of # the same type! LPINT = POINTER(c_int) LPINT.from_param((c_int*3)()) self.assertRaises(TypeError, LPINT.from_param, c_short*3) self.assertRaises(TypeError, LPINT.from_param, c_long*3) self.assertRaises(TypeError, LPINT.from_param, c_uint*3) def test_noctypes_argtype(self): import _ctypes_test from ctypes import CDLL, c_void_p, ArgumentError func = CDLL(_ctypes_test.__file__)._testfunc_p_p func.restype = c_void_p # TypeError: has no from_param method self.assertRaises(TypeError, setattr, func, "argtypes", (object,)) class Adapter(object): def from_param(cls, obj): return None func.argtypes = (Adapter(),) self.assertEqual(func(None), None) self.assertEqual(func(object()), None) class Adapter(object): def from_param(cls, obj): return obj func.argtypes = (Adapter(),) # don't know how to convert parameter 1 self.assertRaises(ArgumentError, func, object()) self.assertEqual(func(c_void_p(42)), 42) class Adapter(object): def from_param(cls, obj): raise ValueError(obj) func.argtypes = (Adapter(),) # ArgumentError: argument 1: ValueError: 99 self.assertRaises(ArgumentError, func, 99) def test_abstract(self): from ctypes import (Array, Structure, Union, _Pointer, _SimpleCData, _CFuncPtr) self.assertRaises(TypeError, Array.from_param, 42) self.assertRaises(TypeError, Structure.from_param, 42) self.assertRaises(TypeError, Union.from_param, 42) self.assertRaises(TypeError, _CFuncPtr.from_param, 42) self.assertRaises(TypeError, _Pointer.from_param, 42) self.assertRaises(TypeError, _SimpleCData.from_param, 42) @test.support.cpython_only def test_issue31311(self): # __setstate__ should neither raise a SystemError nor crash in case # of a bad __dict__. from ctypes import Structure class BadStruct(Structure): @property def __dict__(self): pass with self.assertRaises(TypeError): BadStruct().__setstate__({}, b'foo') class WorseStruct(Structure): @property def __dict__(self): 1/0 with self.assertRaises(ZeroDivisionError): WorseStruct().__setstate__({}, b'foo') ################################################################ if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_pointers.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_pointers.py
import unittest, sys from ctypes import * import _ctypes_test ctype_types = [c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_double, c_float] python_types = [int, int, int, int, int, int, int, int, int, int, float, float] class PointersTestCase(unittest.TestCase): def test_pointer_crash(self): class A(POINTER(c_ulong)): pass POINTER(c_ulong)(c_ulong(22)) # Pointer can't set contents: has no _type_ self.assertRaises(TypeError, A, c_ulong(33)) def test_pass_pointers(self): dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_p_p if sizeof(c_longlong) == sizeof(c_void_p): func.restype = c_longlong else: func.restype = c_long i = c_int(12345678) ## func.argtypes = (POINTER(c_int),) address = func(byref(i)) self.assertEqual(c_int.from_address(address).value, 12345678) func.restype = POINTER(c_int) res = func(pointer(i)) self.assertEqual(res.contents.value, 12345678) self.assertEqual(res[0], 12345678) def test_change_pointers(self): dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_p_p i = c_int(87654) func.restype = POINTER(c_int) func.argtypes = (POINTER(c_int),) res = func(pointer(i)) self.assertEqual(res[0], 87654) self.assertEqual(res.contents.value, 87654) # C code: *res = 54345 res[0] = 54345 self.assertEqual(i.value, 54345) # C code: # int x = 12321; # res = &x x = c_int(12321) res.contents = x self.assertEqual(i.value, 54345) x.value = -99 self.assertEqual(res.contents.value, -99) def test_callbacks_with_pointers(self): # a function type receiving a pointer PROTOTYPE = CFUNCTYPE(c_int, POINTER(c_int)) self.result = [] def func(arg): for i in range(10): ## print arg[i], self.result.append(arg[i]) ## print return 0 callback = PROTOTYPE(func) dll = CDLL(_ctypes_test.__file__) # This function expects a function pointer, # and calls this with an integer pointer as parameter. # The int pointer points to a table containing the numbers 1..10 doit = dll._testfunc_callback_with_pointer ## i = c_int(42) ## callback(byref(i)) ## self.assertEqual(i.value, 84) doit(callback) ## print self.result doit(callback) ## print self.result def test_basics(self): from operator import delitem for ct, pt in zip(ctype_types, python_types): i = ct(42) p = pointer(i) ## print type(p.contents), ct self.assertIs(type(p.contents), ct) # p.contents is the same as p[0] ## print p.contents ## self.assertEqual(p.contents, 42) ## self.assertEqual(p[0], 42) self.assertRaises(TypeError, delitem, p, 0) def test_from_address(self): from array import array a = array('i', [100, 200, 300, 400, 500]) addr = a.buffer_info()[0] p = POINTER(POINTER(c_int)) ## print dir(p) ## print p.from_address ## print p.from_address(addr)[0][0] def test_other(self): class Table(Structure): _fields_ = [("a", c_int), ("b", c_int), ("c", c_int)] pt = pointer(Table(1, 2, 3)) self.assertEqual(pt.contents.a, 1) self.assertEqual(pt.contents.b, 2) self.assertEqual(pt.contents.c, 3) pt.contents.c = 33 from ctypes import _pointer_type_cache del _pointer_type_cache[Table] def test_basic(self): p = pointer(c_int(42)) # Although a pointer can be indexed, it has no length self.assertRaises(TypeError, len, p) self.assertEqual(p[0], 42) self.assertEqual(p[0:1], [42]) self.assertEqual(p.contents.value, 42) def test_charpp(self): """Test that a character pointer-to-pointer is correctly passed""" dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_c_p_p func.restype = c_char_p argv = (c_char_p * 2)() argc = c_int( 2 ) argv[0] = b'hello' argv[1] = b'world' result = func( byref(argc), argv ) self.assertEqual(result, b'world') def test_bug_1467852(self): # http://sourceforge.net/tracker/?func=detail&atid=532154&aid=1467852&group_id=71702 x = c_int(5) dummy = [] for i in range(32000): dummy.append(c_int(i)) y = c_int(6) p = pointer(x) pp = pointer(p) q = pointer(y) pp[0] = q # <== self.assertEqual(p[0], 6) def test_c_void_p(self): # http://sourceforge.net/tracker/?func=detail&aid=1518190&group_id=5470&atid=105470 if sizeof(c_void_p) == 4: self.assertEqual(c_void_p(0xFFFFFFFF).value, c_void_p(-1).value) self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) elif sizeof(c_void_p) == 8: self.assertEqual(c_void_p(0xFFFFFFFF).value, 0xFFFFFFFF) self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) self.assertRaises(TypeError, c_void_p, 3.14) # make sure floats are NOT accepted self.assertRaises(TypeError, c_void_p, object()) # nor other objects def test_pointers_bool(self): # NULL pointers have a boolean False value, non-NULL pointers True. self.assertEqual(bool(POINTER(c_int)()), False) self.assertEqual(bool(pointer(c_int())), True) self.assertEqual(bool(CFUNCTYPE(None)(0)), False) self.assertEqual(bool(CFUNCTYPE(None)(42)), True) # COM methods are boolean True: if sys.platform == "win32": mth = WINFUNCTYPE(None)(42, "name", (), None) self.assertEqual(bool(mth), True) def test_pointer_type_name(self): LargeNamedType = type('T' * 2 ** 25, (Structure,), {}) self.assertTrue(POINTER(LargeNamedType)) # to not leak references, we must clean _pointer_type_cache from ctypes import _pointer_type_cache del _pointer_type_cache[LargeNamedType] def test_pointer_type_str_name(self): large_string = 'T' * 2 ** 25 P = POINTER(large_string) self.assertTrue(P) # to not leak references, we must clean _pointer_type_cache from ctypes import _pointer_type_cache del _pointer_type_cache[id(P)] def test_abstract(self): from ctypes import _Pointer self.assertRaises(TypeError, _Pointer.set_type, 42) if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_callbacks.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_callbacks.py
import functools import unittest from ctypes import * from ctypes.test import need_symbol import _ctypes_test class Callbacks(unittest.TestCase): functype = CFUNCTYPE ## def tearDown(self): ## import gc ## gc.collect() def callback(self, *args): self.got_args = args return args[-1] def check_type(self, typ, arg): PROTO = self.functype.__func__(typ, typ) result = PROTO(self.callback)(arg) if typ == c_float: self.assertAlmostEqual(result, arg, places=5) else: self.assertEqual(self.got_args, (arg,)) self.assertEqual(result, arg) PROTO = self.functype.__func__(typ, c_byte, typ) result = PROTO(self.callback)(-3, arg) if typ == c_float: self.assertAlmostEqual(result, arg, places=5) else: self.assertEqual(self.got_args, (-3, arg)) self.assertEqual(result, arg) ################ def test_byte(self): self.check_type(c_byte, 42) self.check_type(c_byte, -42) def test_ubyte(self): self.check_type(c_ubyte, 42) def test_short(self): self.check_type(c_short, 42) self.check_type(c_short, -42) def test_ushort(self): self.check_type(c_ushort, 42) def test_int(self): self.check_type(c_int, 42) self.check_type(c_int, -42) def test_uint(self): self.check_type(c_uint, 42) def test_long(self): self.check_type(c_long, 42) self.check_type(c_long, -42) def test_ulong(self): self.check_type(c_ulong, 42) def test_longlong(self): self.check_type(c_longlong, 42) self.check_type(c_longlong, -42) def test_ulonglong(self): self.check_type(c_ulonglong, 42) def test_float(self): # only almost equal: double -> float -> double import math self.check_type(c_float, math.e) self.check_type(c_float, -math.e) def test_double(self): self.check_type(c_double, 3.14) self.check_type(c_double, -3.14) def test_longdouble(self): self.check_type(c_longdouble, 3.14) self.check_type(c_longdouble, -3.14) def test_char(self): self.check_type(c_char, b"x") self.check_type(c_char, b"a") # disabled: would now (correctly) raise a RuntimeWarning about # a memory leak. A callback function cannot return a non-integral # C type without causing a memory leak. @unittest.skip('test disabled') def test_char_p(self): self.check_type(c_char_p, "abc") self.check_type(c_char_p, "def") def test_pyobject(self): o = () from sys import getrefcount as grc for o in (), [], object(): initial = grc(o) # This call leaks a reference to 'o'... self.check_type(py_object, o) before = grc(o) # ...but this call doesn't leak any more. Where is the refcount? self.check_type(py_object, o) after = grc(o) self.assertEqual((after, o), (before, o)) def test_unsupported_restype_1(self): # Only "fundamental" result types are supported for callback # functions, the type must have a non-NULL stgdict->setfunc. # POINTER(c_double), for example, is not supported. prototype = self.functype.__func__(POINTER(c_double)) # The type is checked when the prototype is called self.assertRaises(TypeError, prototype, lambda: None) def test_unsupported_restype_2(self): prototype = self.functype.__func__(object) self.assertRaises(TypeError, prototype, lambda: None) def test_issue_7959(self): proto = self.functype.__func__(None) class X(object): def func(self): pass def __init__(self): self.v = proto(self.func) import gc for i in range(32): X() gc.collect() live = [x for x in gc.get_objects() if isinstance(x, X)] self.assertEqual(len(live), 0) def test_issue12483(self): import gc class Nasty: def __del__(self): gc.collect() CFUNCTYPE(None)(lambda x=Nasty(): None) @need_symbol('WINFUNCTYPE') class StdcallCallbacks(Callbacks): try: functype = WINFUNCTYPE except NameError: pass ################################################################ class SampleCallbacksTestCase(unittest.TestCase): def test_integrate(self): # Derived from some then non-working code, posted by David Foster dll = CDLL(_ctypes_test.__file__) # The function prototype called by 'integrate': double func(double); CALLBACK = CFUNCTYPE(c_double, c_double) # The integrate function itself, exposed from the _ctypes_test dll integrate = dll.integrate integrate.argtypes = (c_double, c_double, CALLBACK, c_long) integrate.restype = c_double def func(x): return x**2 result = integrate(0.0, 1.0, CALLBACK(func), 10) diff = abs(result - 1./3.) self.assertLess(diff, 0.01, "%s not less than 0.01" % diff) def test_issue_8959_a(self): from ctypes.util import find_library libc_path = find_library("c") if not libc_path: self.skipTest('could not find libc') libc = CDLL(libc_path) @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) def cmp_func(a, b): return a[0] - b[0] array = (c_int * 5)(5, 1, 99, 7, 33) libc.qsort(array, len(array), sizeof(c_int), cmp_func) self.assertEqual(array[:], [1, 5, 7, 33, 99]) @need_symbol('WINFUNCTYPE') def test_issue_8959_b(self): from ctypes.wintypes import BOOL, HWND, LPARAM global windowCount windowCount = 0 @WINFUNCTYPE(BOOL, HWND, LPARAM) def EnumWindowsCallbackFunc(hwnd, lParam): global windowCount windowCount += 1 return True #Allow windows to keep enumerating windll.user32.EnumWindows(EnumWindowsCallbackFunc, 0) def test_callback_register_int(self): # Issue #8275: buggy handling of callback args under Win64 # NOTE: should be run on release builds as well dll = CDLL(_ctypes_test.__file__) CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int) # All this function does is call the callback with its args squared func = dll._testfunc_cbk_reg_int func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK) func.restype = c_int def callback(a, b, c, d, e): return a + b + c + d + e result = func(2, 3, 4, 5, 6, CALLBACK(callback)) self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6)) def test_callback_register_double(self): # Issue #8275: buggy handling of callback args under Win64 # NOTE: should be run on release builds as well dll = CDLL(_ctypes_test.__file__) CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double, c_double, c_double) # All this function does is call the callback with its args squared func = dll._testfunc_cbk_reg_double func.argtypes = (c_double, c_double, c_double, c_double, c_double, CALLBACK) func.restype = c_double def callback(a, b, c, d, e): return a + b + c + d + e result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback)) self.assertEqual(result, callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5)) def test_callback_large_struct(self): class Check: pass # This should mirror the structure in Modules/_ctypes/_ctypes_test.c class X(Structure): _fields_ = [ ('first', c_ulong), ('second', c_ulong), ('third', c_ulong), ] def callback(check, s): check.first = s.first check.second = s.second check.third = s.third # See issue #29565. # The structure should be passed by value, so # any changes to it should not be reflected in # the value passed s.first = s.second = s.third = 0x0badf00d check = Check() s = X() s.first = 0xdeadbeef s.second = 0xcafebabe s.third = 0x0bad1dea CALLBACK = CFUNCTYPE(None, X) dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_cbk_large_struct func.argtypes = (X, CALLBACK) func.restype = None # the function just calls the callback with the passed structure func(s, CALLBACK(functools.partial(callback, check))) self.assertEqual(check.first, s.first) self.assertEqual(check.second, s.second) self.assertEqual(check.third, s.third) self.assertEqual(check.first, 0xdeadbeef) self.assertEqual(check.second, 0xcafebabe) self.assertEqual(check.third, 0x0bad1dea) # See issue #29565. # Ensure that the original struct is unchanged. self.assertEqual(s.first, check.first) self.assertEqual(s.second, check.second) self.assertEqual(s.third, check.third) ################################################################ if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_prototypes.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_prototypes.py
from ctypes import * from ctypes.test import need_symbol import unittest # IMPORTANT INFO: # # Consider this call: # func.restype = c_char_p # func(c_char_p("123")) # It returns # "123" # # WHY IS THIS SO? # # argument tuple (c_char_p("123"), ) is destroyed after the function # func is called, but NOT before the result is actually built. # # If the arglist would be destroyed BEFORE the result has been built, # the c_char_p("123") object would already have a zero refcount, # and the pointer passed to (and returned by) the function would # probably point to deallocated space. # # In this case, there would have to be an additional reference to the argument... import _ctypes_test testdll = CDLL(_ctypes_test.__file__) # Return machine address `a` as a (possibly long) non-negative integer. # Starting with Python 2.5, id(anything) is always non-negative, and # the ctypes addressof() inherits that via PyLong_FromVoidPtr(). def positive_address(a): if a >= 0: return a # View the bits in `a` as unsigned instead. import struct num_bits = struct.calcsize("P") * 8 # num bits in native machine address a += 1 << num_bits assert a >= 0 return a def c_wbuffer(init): n = len(init) + 1 return (c_wchar * n)(*init) class CharPointersTestCase(unittest.TestCase): def setUp(self): func = testdll._testfunc_p_p func.restype = c_long func.argtypes = None def test_paramflags(self): # function returns c_void_p result, # and has a required parameter named 'input' prototype = CFUNCTYPE(c_void_p, c_void_p) func = prototype(("_testfunc_p_p", testdll), ((1, "input"),)) try: func() except TypeError as details: self.assertEqual(str(details), "required argument 'input' missing") else: self.fail("TypeError not raised") self.assertEqual(func(None), None) self.assertEqual(func(input=None), None) def test_int_pointer_arg(self): func = testdll._testfunc_p_p if sizeof(c_longlong) == sizeof(c_void_p): func.restype = c_longlong else: func.restype = c_long self.assertEqual(0, func(0)) ci = c_int(0) func.argtypes = POINTER(c_int), self.assertEqual(positive_address(addressof(ci)), positive_address(func(byref(ci)))) func.argtypes = c_char_p, self.assertRaises(ArgumentError, func, byref(ci)) func.argtypes = POINTER(c_short), self.assertRaises(ArgumentError, func, byref(ci)) func.argtypes = POINTER(c_double), self.assertRaises(ArgumentError, func, byref(ci)) def test_POINTER_c_char_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = POINTER(c_char), self.assertEqual(None, func(None)) self.assertEqual(b"123", func(b"123")) self.assertEqual(None, func(c_char_p(None))) self.assertEqual(b"123", func(c_char_p(b"123"))) self.assertEqual(b"123", func(c_buffer(b"123"))) ca = c_char(b"a") self.assertEqual(ord(b"a"), func(pointer(ca))[0]) self.assertEqual(ord(b"a"), func(byref(ca))[0]) def test_c_char_p_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = c_char_p, self.assertEqual(None, func(None)) self.assertEqual(b"123", func(b"123")) self.assertEqual(None, func(c_char_p(None))) self.assertEqual(b"123", func(c_char_p(b"123"))) self.assertEqual(b"123", func(c_buffer(b"123"))) ca = c_char(b"a") self.assertEqual(ord(b"a"), func(pointer(ca))[0]) self.assertEqual(ord(b"a"), func(byref(ca))[0]) def test_c_void_p_arg(self): func = testdll._testfunc_p_p func.restype = c_char_p func.argtypes = c_void_p, self.assertEqual(None, func(None)) self.assertEqual(b"123", func(b"123")) self.assertEqual(b"123", func(c_char_p(b"123"))) self.assertEqual(None, func(c_char_p(None))) self.assertEqual(b"123", func(c_buffer(b"123"))) ca = c_char(b"a") self.assertEqual(ord(b"a"), func(pointer(ca))[0]) self.assertEqual(ord(b"a"), func(byref(ca))[0]) func(byref(c_int())) func(pointer(c_int())) func((c_int * 3)()) @need_symbol('c_wchar_p') def test_c_void_p_arg_with_c_wchar_p(self): func = testdll._testfunc_p_p func.restype = c_wchar_p func.argtypes = c_void_p, self.assertEqual(None, func(c_wchar_p(None))) self.assertEqual("123", func(c_wchar_p("123"))) def test_instance(self): func = testdll._testfunc_p_p func.restype = c_void_p class X: _as_parameter_ = None func.argtypes = c_void_p, self.assertEqual(None, func(X())) func.argtypes = None self.assertEqual(None, func(X())) @need_symbol('c_wchar') class WCharPointersTestCase(unittest.TestCase): def setUp(self): func = testdll._testfunc_p_p func.restype = c_int func.argtypes = None def test_POINTER_c_wchar_arg(self): func = testdll._testfunc_p_p func.restype = c_wchar_p func.argtypes = POINTER(c_wchar), self.assertEqual(None, func(None)) self.assertEqual("123", func("123")) self.assertEqual(None, func(c_wchar_p(None))) self.assertEqual("123", func(c_wchar_p("123"))) self.assertEqual("123", func(c_wbuffer("123"))) ca = c_wchar("a") self.assertEqual("a", func(pointer(ca))[0]) self.assertEqual("a", func(byref(ca))[0]) def test_c_wchar_p_arg(self): func = testdll._testfunc_p_p func.restype = c_wchar_p func.argtypes = c_wchar_p, c_wchar_p.from_param("123") self.assertEqual(None, func(None)) self.assertEqual("123", func("123")) self.assertEqual(None, func(c_wchar_p(None))) self.assertEqual("123", func(c_wchar_p("123"))) # XXX Currently, these raise TypeErrors, although they shouldn't: self.assertEqual("123", func(c_wbuffer("123"))) ca = c_wchar("a") self.assertEqual("a", func(pointer(ca))[0]) self.assertEqual("a", func(byref(ca))[0]) class ArrayTest(unittest.TestCase): def test(self): func = testdll._testfunc_ai8 func.restype = POINTER(c_int) func.argtypes = c_int * 8, func((c_int * 8)(1, 2, 3, 4, 5, 6, 7, 8)) # This did crash before: def func(): pass CFUNCTYPE(None, c_int * 3)(func) ################################################################ if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/__init__.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/__init__.py
import os import unittest from test import support # skip tests if _ctypes was not built ctypes = support.import_module('ctypes') ctypes_symbols = dir(ctypes) def need_symbol(name): return unittest.skipUnless(name in ctypes_symbols, '{!r} is required'.format(name)) def load_tests(*args): return support.load_package_tests(os.path.dirname(__file__), *args)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_repr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_repr.py
from ctypes import * import unittest subclasses = [] for base in [c_byte, c_short, c_int, c_long, c_longlong, c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong, c_float, c_double, c_longdouble, c_bool]: class X(base): pass subclasses.append(X) class X(c_char): pass # This test checks if the __repr__ is correct for subclasses of simple types class ReprTest(unittest.TestCase): def test_numbers(self): for typ in subclasses: base = typ.__bases__[0] self.assertTrue(repr(base(42)).startswith(base.__name__)) self.assertEqual("<X object at", repr(typ(42))[:12]) def test_char(self): self.assertEqual("c_char(b'x')", repr(c_char(b'x'))) self.assertEqual("<X object at", repr(X(b'x'))[:12]) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_bitfields.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_bitfields.py
from ctypes import * from ctypes.test import need_symbol import unittest import os import _ctypes_test class BITS(Structure): _fields_ = [("A", c_int, 1), ("B", c_int, 2), ("C", c_int, 3), ("D", c_int, 4), ("E", c_int, 5), ("F", c_int, 6), ("G", c_int, 7), ("H", c_int, 8), ("I", c_int, 9), ("M", c_short, 1), ("N", c_short, 2), ("O", c_short, 3), ("P", c_short, 4), ("Q", c_short, 5), ("R", c_short, 6), ("S", c_short, 7)] func = CDLL(_ctypes_test.__file__).unpack_bitfields func.argtypes = POINTER(BITS), c_char ##for n in "ABCDEFGHIMNOPQRS": ## print n, hex(getattr(BITS, n).size), getattr(BITS, n).offset class C_Test(unittest.TestCase): def test_ints(self): for i in range(512): for name in "ABCDEFGHI": b = BITS() setattr(b, name, i) self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii'))) def test_shorts(self): for i in range(256): for name in "MNOPQRS": b = BITS() setattr(b, name, i) self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii'))) signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong) unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong) int_types = unsigned_int_types + signed_int_types class BitFieldTest(unittest.TestCase): def test_longlong(self): class X(Structure): _fields_ = [("a", c_longlong, 1), ("b", c_longlong, 62), ("c", c_longlong, 1)] self.assertEqual(sizeof(X), sizeof(c_longlong)) x = X() x.a, x.b, x.c = -1, 7, -1 self.assertEqual((x.a, x.b, x.c), (-1, 7, -1)) def test_ulonglong(self): class X(Structure): _fields_ = [("a", c_ulonglong, 1), ("b", c_ulonglong, 62), ("c", c_ulonglong, 1)] self.assertEqual(sizeof(X), sizeof(c_longlong)) x = X() self.assertEqual((x.a, x.b, x.c), (0, 0, 0)) x.a, x.b, x.c = 7, 7, 7 self.assertEqual((x.a, x.b, x.c), (1, 7, 1)) def test_signed(self): for c_typ in signed_int_types: class X(Structure): _fields_ = [("dummy", c_typ), ("a", c_typ, 3), ("b", c_typ, 3), ("c", c_typ, 1)] self.assertEqual(sizeof(X), sizeof(c_typ)*2) x = X() self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) x.a = -1 self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, -1, 0, 0)) x.a, x.b = 0, -1 self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, -1, 0)) def test_unsigned(self): for c_typ in unsigned_int_types: class X(Structure): _fields_ = [("a", c_typ, 3), ("b", c_typ, 3), ("c", c_typ, 1)] self.assertEqual(sizeof(X), sizeof(c_typ)) x = X() self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) x.a = -1 self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 7, 0, 0)) x.a, x.b = 0, -1 self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 7, 0)) def fail_fields(self, *fields): return self.get_except(type(Structure), "X", (), {"_fields_": fields}) def test_nonint_types(self): # bit fields are not allowed on non-integer types. result = self.fail_fields(("a", c_char_p, 1)) self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char_p')) result = self.fail_fields(("a", c_void_p, 1)) self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_void_p')) if c_int != c_long: result = self.fail_fields(("a", POINTER(c_int), 1)) self.assertEqual(result, (TypeError, 'bit fields not allowed for type LP_c_int')) result = self.fail_fields(("a", c_char, 1)) self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char')) class Dummy(Structure): _fields_ = [] result = self.fail_fields(("a", Dummy, 1)) self.assertEqual(result, (TypeError, 'bit fields not allowed for type Dummy')) @need_symbol('c_wchar') def test_c_wchar(self): result = self.fail_fields(("a", c_wchar, 1)) self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_wchar')) def test_single_bitfield_size(self): for c_typ in int_types: result = self.fail_fields(("a", c_typ, -1)) self.assertEqual(result, (ValueError, 'number of bits invalid for bit field')) result = self.fail_fields(("a", c_typ, 0)) self.assertEqual(result, (ValueError, 'number of bits invalid for bit field')) class X(Structure): _fields_ = [("a", c_typ, 1)] self.assertEqual(sizeof(X), sizeof(c_typ)) class X(Structure): _fields_ = [("a", c_typ, sizeof(c_typ)*8)] self.assertEqual(sizeof(X), sizeof(c_typ)) result = self.fail_fields(("a", c_typ, sizeof(c_typ)*8 + 1)) self.assertEqual(result, (ValueError, 'number of bits invalid for bit field')) def test_multi_bitfields_size(self): class X(Structure): _fields_ = [("a", c_short, 1), ("b", c_short, 14), ("c", c_short, 1)] self.assertEqual(sizeof(X), sizeof(c_short)) class X(Structure): _fields_ = [("a", c_short, 1), ("a1", c_short), ("b", c_short, 14), ("c", c_short, 1)] self.assertEqual(sizeof(X), sizeof(c_short)*3) self.assertEqual(X.a.offset, 0) self.assertEqual(X.a1.offset, sizeof(c_short)) self.assertEqual(X.b.offset, sizeof(c_short)*2) self.assertEqual(X.c.offset, sizeof(c_short)*2) class X(Structure): _fields_ = [("a", c_short, 3), ("b", c_short, 14), ("c", c_short, 14)] self.assertEqual(sizeof(X), sizeof(c_short)*3) self.assertEqual(X.a.offset, sizeof(c_short)*0) self.assertEqual(X.b.offset, sizeof(c_short)*1) self.assertEqual(X.c.offset, sizeof(c_short)*2) def get_except(self, func, *args, **kw): try: func(*args, **kw) except Exception as detail: return detail.__class__, str(detail) def test_mixed_1(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_int, 4)] if os.name == "nt": self.assertEqual(sizeof(X), sizeof(c_int)*2) else: self.assertEqual(sizeof(X), sizeof(c_int)) def test_mixed_2(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_int, 32)] self.assertEqual(sizeof(X), alignment(c_int)+sizeof(c_int)) def test_mixed_3(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_ubyte, 4)] self.assertEqual(sizeof(X), sizeof(c_byte)) def test_mixed_4(self): class X(Structure): _fields_ = [("a", c_short, 4), ("b", c_short, 4), ("c", c_int, 24), ("d", c_short, 4), ("e", c_short, 4), ("f", c_int, 24)] # MSVC does NOT combine c_short and c_int into one field, GCC # does (unless GCC is run with '-mms-bitfields' which # produces code compatible with MSVC). if os.name == "nt": self.assertEqual(sizeof(X), sizeof(c_int) * 4) else: self.assertEqual(sizeof(X), sizeof(c_int) * 2) def test_anon_bitfields(self): # anonymous bit-fields gave a strange error message class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_ubyte, 4)] class Y(Structure): _anonymous_ = ["_"] _fields_ = [("_", X)] @need_symbol('c_uint32') def test_uint32(self): class X(Structure): _fields_ = [("a", c_uint32, 32)] x = X() x.a = 10 self.assertEqual(x.a, 10) x.a = 0xFDCBA987 self.assertEqual(x.a, 0xFDCBA987) @need_symbol('c_uint64') def test_uint64(self): class X(Structure): _fields_ = [("a", c_uint64, 64)] x = X() x.a = 10 self.assertEqual(x.a, 10) x.a = 0xFEDCBA9876543211 self.assertEqual(x.a, 0xFEDCBA9876543211) @need_symbol('c_uint32') def test_uint32_swap_little_endian(self): # Issue #23319 class Little(LittleEndianStructure): _fields_ = [("a", c_uint32, 24), ("b", c_uint32, 4), ("c", c_uint32, 4)] b = bytearray(4) x = Little.from_buffer(b) x.a = 0xabcdef x.b = 1 x.c = 2 self.assertEqual(b, b'\xef\xcd\xab\x21') @need_symbol('c_uint32') def test_uint32_swap_big_endian(self): # Issue #23319 class Big(BigEndianStructure): _fields_ = [("a", c_uint32, 24), ("b", c_uint32, 4), ("c", c_uint32, 4)] b = bytearray(4) x = Big.from_buffer(b) x.a = 0xabcdef x.b = 1 x.c = 2 self.assertEqual(b, b'\xab\xcd\xef\x12') if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_struct_fields.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_struct_fields.py
import unittest from ctypes import * class StructFieldsTestCase(unittest.TestCase): # Structure/Union classes must get 'finalized' sooner or # later, when one of these things happen: # # 1. _fields_ is set. # 2. An instance is created. # 3. The type is used as field of another Structure/Union. # 4. The type is subclassed # # When they are finalized, assigning _fields_ is no longer allowed. def test_1_A(self): class X(Structure): pass self.assertEqual(sizeof(X), 0) # not finalized X._fields_ = [] # finalized self.assertRaises(AttributeError, setattr, X, "_fields_", []) def test_1_B(self): class X(Structure): _fields_ = [] # finalized self.assertRaises(AttributeError, setattr, X, "_fields_", []) def test_2(self): class X(Structure): pass X() self.assertRaises(AttributeError, setattr, X, "_fields_", []) def test_3(self): class X(Structure): pass class Y(Structure): _fields_ = [("x", X)] # finalizes X self.assertRaises(AttributeError, setattr, X, "_fields_", []) def test_4(self): class X(Structure): pass class Y(X): pass self.assertRaises(AttributeError, setattr, X, "_fields_", []) Y._fields_ = [] self.assertRaises(AttributeError, setattr, X, "_fields_", []) # __set__ and __get__ should raise a TypeError in case their self # argument is not a ctype instance. def test___set__(self): class MyCStruct(Structure): _fields_ = (("field", c_int),) self.assertRaises(TypeError, MyCStruct.field.__set__, 'wrong type self', 42) class MyCUnion(Union): _fields_ = (("field", c_int),) self.assertRaises(TypeError, MyCUnion.field.__set__, 'wrong type self', 42) def test___get__(self): class MyCStruct(Structure): _fields_ = (("field", c_int),) self.assertRaises(TypeError, MyCStruct.field.__get__, 'wrong type self', 42) class MyCUnion(Union): _fields_ = (("field", c_int),) self.assertRaises(TypeError, MyCUnion.field.__get__, 'wrong type self', 42) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_delattr.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_delattr.py
import unittest from ctypes import * class X(Structure): _fields_ = [("foo", c_int)] class TestCase(unittest.TestCase): def test_simple(self): self.assertRaises(TypeError, delattr, c_int(42), "value") def test_chararray(self): self.assertRaises(TypeError, delattr, (c_char * 5)(), "value") def test_struct(self): self.assertRaises(TypeError, delattr, X(), "foo") if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_values.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_values.py
""" A testcase which accesses *values* in a dll. """ import unittest import sys from ctypes import * import _ctypes_test class ValuesTestCase(unittest.TestCase): def test_an_integer(self): # This test checks and changes an integer stored inside the # _ctypes_test dll/shared lib. ctdll = CDLL(_ctypes_test.__file__) an_integer = c_int.in_dll(ctdll, "an_integer") x = an_integer.value self.assertEqual(x, ctdll.get_an_integer()) an_integer.value *= 2 self.assertEqual(x*2, ctdll.get_an_integer()) # To avoid test failures when this test is repeated several # times the original value must be restored an_integer.value = x self.assertEqual(x, ctdll.get_an_integer()) def test_undefined(self): ctdll = CDLL(_ctypes_test.__file__) self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol") class PythonValuesTestCase(unittest.TestCase): """This test only works when python itself is a dll/shared library""" def test_optimizeflag(self): # This test accesses the Py_OptimizeFlag integer, which is # exported by the Python dll and should match the sys.flags value opt = c_int.in_dll(pythonapi, "Py_OptimizeFlag").value self.assertEqual(opt, sys.flags.optimize) def test_frozentable(self): # Python exports a PyImport_FrozenModules symbol. This is a # pointer to an array of struct _frozen entries. The end of the # array is marked by an entry containing a NULL name and zero # size. # In standard Python, this table contains a __hello__ # module, and a __phello__ package containing a spam # module. class struct_frozen(Structure): _fields_ = [("name", c_char_p), ("code", POINTER(c_ubyte)), ("size", c_int)] FrozenTable = POINTER(struct_frozen) ft = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules") # ft is a pointer to the struct_frozen entries: items = [] # _frozen_importlib changes size whenever importlib._bootstrap # changes, so it gets a special case. We should make sure it's # found, but don't worry about its size too much. The same # applies to _frozen_importlib_external. bootstrap_seen = [] bootstrap_expected = [ b'_frozen_importlib', b'_frozen_importlib_external', ] for entry in ft: # This is dangerous. We *can* iterate over a pointer, but # the loop will not terminate (maybe with an access # violation;-) because the pointer instance has no size. if entry.name is None: break if entry.name in bootstrap_expected: bootstrap_seen.append(entry.name) self.assertTrue(entry.size, "{!r} was reported as having no size".format(entry.name)) continue items.append((entry.name.decode("ascii"), entry.size)) expected = [("__hello__", 139), ("__phello__", -139), ("__phello__.spam", 139), ] self.assertEqual(items, expected, "PyImport_FrozenModules example " "in Doc/library/ctypes.rst may be out of date") self.assertEqual(sorted(bootstrap_seen), bootstrap_expected, "frozen bootstrap modules did not match PyImport_FrozenModules") from ctypes import _pointer_type_cache del _pointer_type_cache[struct_frozen] def test_undefined(self): self.assertRaises(ValueError, c_int.in_dll, pythonapi, "Undefined_Symbol") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_simplesubclasses.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_simplesubclasses.py
import unittest from ctypes import * class MyInt(c_int): def __eq__(self, other): if type(other) != MyInt: return NotImplementedError return self.value == other.value class Test(unittest.TestCase): def test_compare(self): self.assertEqual(MyInt(3), MyInt(3)) self.assertNotEqual(MyInt(42), MyInt(43)) def test_ignore_retval(self): # Test if the return value of a callback is ignored # if restype is None proto = CFUNCTYPE(None) def func(): return (1, "abc", None) cb = proto(func) self.assertEqual(None, cb()) def test_int_callback(self): args = [] def func(arg): args.append(arg) return arg cb = CFUNCTYPE(None, MyInt)(func) self.assertEqual(None, cb(42)) self.assertEqual(type(args[-1]), MyInt) cb = CFUNCTYPE(c_int, c_int)(func) self.assertEqual(42, cb(42)) self.assertEqual(type(args[-1]), int) def test_int_struct(self): class X(Structure): _fields_ = [("x", MyInt)] self.assertEqual(X().x, MyInt()) s = X() s.x = MyInt(42) self.assertEqual(s.x, MyInt(42)) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_varsize_struct.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_varsize_struct.py
from ctypes import * import unittest class VarSizeTest(unittest.TestCase): def test_resize(self): class X(Structure): _fields_ = [("item", c_int), ("array", c_int * 1)] self.assertEqual(sizeof(X), sizeof(c_int) * 2) x = X() x.item = 42 x.array[0] = 100 self.assertEqual(sizeof(x), sizeof(c_int) * 2) # make room for one additional item new_size = sizeof(X) + sizeof(c_int) * 1 resize(x, new_size) self.assertEqual(sizeof(x), new_size) self.assertEqual((x.item, x.array[0]), (42, 100)) # make room for 10 additional items new_size = sizeof(X) + sizeof(c_int) * 9 resize(x, new_size) self.assertEqual(sizeof(x), new_size) self.assertEqual((x.item, x.array[0]), (42, 100)) # make room for one additional item new_size = sizeof(X) + sizeof(c_int) * 1 resize(x, new_size) self.assertEqual(sizeof(x), new_size) self.assertEqual((x.item, x.array[0]), (42, 100)) def test_array_invalid_length(self): # cannot create arrays with non-positive size self.assertRaises(ValueError, lambda: c_int * -1) self.assertRaises(ValueError, lambda: c_int * -3) def test_zerosized_array(self): array = (c_int * 0)() # accessing elements of zero-sized arrays raise IndexError self.assertRaises(IndexError, array.__setitem__, 0, None) self.assertRaises(IndexError, array.__getitem__, 0) self.assertRaises(IndexError, array.__setitem__, 1, None) self.assertRaises(IndexError, array.__getitem__, 1) self.assertRaises(IndexError, array.__setitem__, -1, None) self.assertRaises(IndexError, array.__getitem__, -1) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_structures.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_structures.py
import platform import sys import unittest from ctypes import * from ctypes.test import need_symbol from struct import calcsize import _ctypes_test import test.support class SubclassesTest(unittest.TestCase): def test_subclass(self): class X(Structure): _fields_ = [("a", c_int)] class Y(X): _fields_ = [("b", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [("a", c_int)]) self.assertEqual(Y._fields_, [("b", c_int)]) self.assertEqual(Z._fields_, [("a", c_int)]) def test_subclass_delayed(self): class X(Structure): pass self.assertEqual(sizeof(X), 0) X._fields_ = [("a", c_int)] class Y(X): pass self.assertEqual(sizeof(Y), sizeof(X)) Y._fields_ = [("b", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [("a", c_int)]) self.assertEqual(Y._fields_, [("b", c_int)]) self.assertEqual(Z._fields_, [("a", c_int)]) class StructureTestCase(unittest.TestCase): formats = {"c": c_char, "b": c_byte, "B": c_ubyte, "h": c_short, "H": c_ushort, "i": c_int, "I": c_uint, "l": c_long, "L": c_ulong, "q": c_longlong, "Q": c_ulonglong, "f": c_float, "d": c_double, } def test_simple_structs(self): for code, tp in self.formats.items(): class X(Structure): _fields_ = [("x", c_char), ("y", tp)] self.assertEqual((sizeof(X), code), (calcsize("c%c0%c" % (code, code)), code)) def test_unions(self): for code, tp in self.formats.items(): class X(Union): _fields_ = [("x", c_char), ("y", tp)] self.assertEqual((sizeof(X), code), (calcsize("%c" % (code)), code)) def test_struct_alignment(self): class X(Structure): _fields_ = [("x", c_char * 3)] self.assertEqual(alignment(X), calcsize("s")) self.assertEqual(sizeof(X), calcsize("3s")) class Y(Structure): _fields_ = [("x", c_char * 3), ("y", c_int)] self.assertEqual(alignment(Y), alignment(c_int)) self.assertEqual(sizeof(Y), calcsize("3si")) class SI(Structure): _fields_ = [("a", X), ("b", Y)] self.assertEqual(alignment(SI), max(alignment(Y), alignment(X))) self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i")) class IS(Structure): _fields_ = [("b", Y), ("a", X)] self.assertEqual(alignment(SI), max(alignment(X), alignment(Y))) self.assertEqual(sizeof(IS), calcsize("3si 3s 0i")) class XX(Structure): _fields_ = [("a", X), ("b", X)] self.assertEqual(alignment(XX), alignment(X)) self.assertEqual(sizeof(XX), calcsize("3s 3s 0s")) def test_empty(self): # I had problems with these # # Although these are pathological cases: Empty Structures! class X(Structure): _fields_ = [] class Y(Union): _fields_ = [] # Is this really the correct alignment, or should it be 0? self.assertTrue(alignment(X) == alignment(Y) == 1) self.assertTrue(sizeof(X) == sizeof(Y) == 0) class XX(Structure): _fields_ = [("a", X), ("b", X)] self.assertEqual(alignment(XX), 1) self.assertEqual(sizeof(XX), 0) def test_fields(self): # test the offset and size attributes of Structure/Union fields. class X(Structure): _fields_ = [("x", c_int), ("y", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, sizeof(c_int)) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92) class X(Union): _fields_ = [("x", c_int), ("y", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, 0) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92) # XXX Should we check nested data types also? # offset is always relative to the class... def test_packed(self): class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 1 self.assertEqual(sizeof(X), 9) self.assertEqual(X.b.offset, 1) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 2 self.assertEqual(sizeof(X), 10) self.assertEqual(X.b.offset, 2) import struct longlong_size = struct.calcsize("q") longlong_align = struct.calcsize("bq") - longlong_size class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 4 self.assertEqual(sizeof(X), min(4, longlong_align) + longlong_size) self.assertEqual(X.b.offset, min(4, longlong_align)) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 8 self.assertEqual(sizeof(X), min(8, longlong_align) + longlong_size) self.assertEqual(X.b.offset, min(8, longlong_align)) d = {"_fields_": [("a", "b"), ("b", "q")], "_pack_": -1} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) @test.support.cpython_only def test_packed_c_limits(self): # Issue 15989 import _testcapi d = {"_fields_": [("a", c_byte)], "_pack_": _testcapi.INT_MAX + 1} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) d = {"_fields_": [("a", c_byte)], "_pack_": _testcapi.UINT_MAX + 2} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) def test_initializers(self): class Person(Structure): _fields_ = [("name", c_char*6), ("age", c_int)] self.assertRaises(TypeError, Person, 42) self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj") self.assertRaises(TypeError, Person, "Name", "HI") # short enough self.assertEqual(Person(b"12345", 5).name, b"12345") # exact fit self.assertEqual(Person(b"123456", 5).name, b"123456") # too long self.assertRaises(ValueError, Person, b"1234567", 5) def test_conflicting_initializers(self): class POINT(Structure): _fields_ = [("phi", c_float), ("rho", c_float)] # conflicting positional and keyword args self.assertRaisesRegex(TypeError, "phi", POINT, 2, 3, phi=4) self.assertRaisesRegex(TypeError, "rho", POINT, 2, 3, rho=4) # too many initializers self.assertRaises(TypeError, POINT, 2, 3, 4) def test_keyword_initializers(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] pt = POINT(1, 2) self.assertEqual((pt.x, pt.y), (1, 2)) pt = POINT(y=2, x=1) self.assertEqual((pt.x, pt.y), (1, 2)) def test_invalid_field_types(self): class POINT(Structure): pass self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)]) def test_invalid_name(self): # field name must be string def declare_with_name(name): class S(Structure): _fields_ = [(name, c_int)] self.assertRaises(TypeError, declare_with_name, b"x") def test_intarray_fields(self): class SomeInts(Structure): _fields_ = [("a", c_int * 4)] # can use tuple to initialize array (but not list!) self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1]) self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0]) self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2]) self.assertEqual(SomeInts((1, 2)).a[6:4:-1], []) self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4]) self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4]) # too long # XXX Should raise ValueError?, not RuntimeError self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5)) def test_nested_initializers(self): # test initializing nested structures class Phone(Structure): _fields_ = [("areacode", c_char*6), ("number", c_char*12)] class Person(Structure): _fields_ = [("name", c_char * 12), ("phone", Phone), ("age", c_int)] p = Person(b"Someone", (b"1234", b"5678"), 5) self.assertEqual(p.name, b"Someone") self.assertEqual(p.phone.areacode, b"1234") self.assertEqual(p.phone.number, b"5678") self.assertEqual(p.age, 5) @need_symbol('c_wchar') def test_structures_with_wchar(self): class PersonW(Structure): _fields_ = [("name", c_wchar * 12), ("age", c_int)] p = PersonW("Someone \xe9") self.assertEqual(p.name, "Someone \xe9") self.assertEqual(PersonW("1234567890").name, "1234567890") self.assertEqual(PersonW("12345678901").name, "12345678901") # exact fit self.assertEqual(PersonW("123456789012").name, "123456789012") #too long self.assertRaises(ValueError, PersonW, "1234567890123") def test_init_errors(self): class Phone(Structure): _fields_ = [("areacode", c_char*6), ("number", c_char*12)] class Person(Structure): _fields_ = [("name", c_char * 12), ("phone", Phone), ("age", c_int)] cls, msg = self.get_except(Person, b"Someone", (1, 2)) self.assertEqual(cls, RuntimeError) self.assertEqual(msg, "(Phone) <class 'TypeError'>: " "expected bytes, int found") cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c")) self.assertEqual(cls, RuntimeError) self.assertEqual(msg, "(Phone) <class 'TypeError'>: too many initializers") def test_huge_field_name(self): # issue12881: segfault with large structure field names def create_class(length): class S(Structure): _fields_ = [('x' * length, c_int)] for length in [10 ** i for i in range(0, 8)]: try: create_class(length) except MemoryError: # MemoryErrors are OK, we just don't want to segfault pass def get_except(self, func, *args): try: func(*args) except Exception as detail: return detail.__class__, str(detail) @unittest.skip('test disabled') def test_subclass_creation(self): meta = type(Structure) # same as 'class X(Structure): pass' # fails, since we need either a _fields_ or a _abstract_ attribute cls, msg = self.get_except(meta, "X", (Structure,), {}) self.assertEqual((cls, msg), (AttributeError, "class must define a '_fields_' attribute")) def test_abstract_class(self): class X(Structure): _abstract_ = "something" # try 'X()' cls, msg = self.get_except(eval, "X()", locals()) self.assertEqual((cls, msg), (TypeError, "abstract class")) def test_methods(self): ## class X(Structure): ## _fields_ = [] self.assertIn("in_dll", dir(type(Structure))) self.assertIn("from_address", dir(type(Structure))) self.assertIn("in_dll", dir(type(Structure))) def test_positional_args(self): # see also http://bugs.python.org/issue5042 class W(Structure): _fields_ = [("a", c_int), ("b", c_int)] class X(W): _fields_ = [("c", c_int)] class Y(X): pass class Z(Y): _fields_ = [("d", c_int), ("e", c_int), ("f", c_int)] z = Z(1, 2, 3, 4, 5, 6) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 2, 3, 4, 5, 6)) z = Z(1) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 0, 0, 0, 0, 0)) self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7)) def test_pass_by_value(self): # This should mirror the structure in Modules/_ctypes/_ctypes_test.c class X(Structure): _fields_ = [ ('first', c_ulong), ('second', c_ulong), ('third', c_ulong), ] s = X() s.first = 0xdeadbeef s.second = 0xcafebabe s.third = 0x0bad1dea dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_large_struct_update_value func.argtypes = (X,) func.restype = None func(s) self.assertEqual(s.first, 0xdeadbeef) self.assertEqual(s.second, 0xcafebabe) self.assertEqual(s.third, 0x0bad1dea) def test_pass_by_value_in_register(self): class X(Structure): _fields_ = [ ('first', c_uint), ('second', c_uint) ] s = X() s.first = 0xdeadbeef s.second = 0xcafebabe dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_reg_struct_update_value func.argtypes = (X,) func.restype = None func(s) self.assertEqual(s.first, 0xdeadbeef) self.assertEqual(s.second, 0xcafebabe) got = X.in_dll(dll, "last_tfrsuv_arg") self.assertEqual(s.first, got.first) self.assertEqual(s.second, got.second) def test_array_in_struct(self): # See bpo-22273 # These should mirror the structures in Modules/_ctypes/_ctypes_test.c class Test2(Structure): _fields_ = [ ('data', c_ubyte * 16), ] class Test3(Structure): _fields_ = [ ('data', c_double * 2), ] class Test3A(Structure): _fields_ = [ ('data', c_float * 2), ] class Test3B(Test3A): _fields_ = [ ('more_data', c_float * 2), ] s = Test2() expected = 0 for i in range(16): s.data[i] = i expected += i dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_array_in_struct1 func.restype = c_int func.argtypes = (Test2,) result = func(s) self.assertEqual(result, expected) # check the passed-in struct hasn't changed for i in range(16): self.assertEqual(s.data[i], i) s = Test3() s.data[0] = 3.14159 s.data[1] = 2.71828 expected = 3.14159 + 2.71828 func = dll._testfunc_array_in_struct2 func.restype = c_double func.argtypes = (Test3,) result = func(s) self.assertEqual(result, expected) # check the passed-in struct hasn't changed self.assertEqual(s.data[0], 3.14159) self.assertEqual(s.data[1], 2.71828) s = Test3B() s.data[0] = 3.14159 s.data[1] = 2.71828 s.more_data[0] = -3.0 s.more_data[1] = -2.0 expected = 3.14159 + 2.71828 - 5.0 func = dll._testfunc_array_in_struct2a func.restype = c_double func.argtypes = (Test3B,) result = func(s) self.assertAlmostEqual(result, expected, places=6) # check the passed-in struct hasn't changed self.assertAlmostEqual(s.data[0], 3.14159, places=6) self.assertAlmostEqual(s.data[1], 2.71828, places=6) self.assertAlmostEqual(s.more_data[0], -3.0, places=6) self.assertAlmostEqual(s.more_data[1], -2.0, places=6) def test_38368(self): class U(Union): _fields_ = [ ('f1', c_uint8 * 16), ('f2', c_uint16 * 8), ('f3', c_uint32 * 4), ] u = U() u.f3[0] = 0x01234567 u.f3[1] = 0x89ABCDEF u.f3[2] = 0x76543210 u.f3[3] = 0xFEDCBA98 f1 = [u.f1[i] for i in range(16)] f2 = [u.f2[i] for i in range(8)] if sys.byteorder == 'little': self.assertEqual(f1, [0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, 0x89, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe]) self.assertEqual(f2, [0x4567, 0x0123, 0xcdef, 0x89ab, 0x3210, 0x7654, 0xba98, 0xfedc]) @unittest.skipIf(True, 'Test disabled for now - see bpo-16575/bpo-16576') def test_union_by_value(self): # See bpo-16575 # These should mirror the structures in Modules/_ctypes/_ctypes_test.c class Nested1(Structure): _fields_ = [ ('an_int', c_int), ('another_int', c_int), ] class Test4(Union): _fields_ = [ ('a_long', c_long), ('a_struct', Nested1), ] class Nested2(Structure): _fields_ = [ ('an_int', c_int), ('a_union', Test4), ] class Test5(Structure): _fields_ = [ ('an_int', c_int), ('nested', Nested2), ('another_int', c_int), ] test4 = Test4() dll = CDLL(_ctypes_test.__file__) with self.assertRaises(TypeError) as ctx: func = dll._testfunc_union_by_value1 func.restype = c_long func.argtypes = (Test4,) result = func(test4) self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes ' 'a union by value, which is unsupported.') test5 = Test5() with self.assertRaises(TypeError) as ctx: func = dll._testfunc_union_by_value2 func.restype = c_long func.argtypes = (Test5,) result = func(test5) self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes ' 'a union by value, which is unsupported.') # passing by reference should be OK test4.a_long = 12345; func = dll._testfunc_union_by_reference1 func.restype = c_long func.argtypes = (POINTER(Test4),) result = func(byref(test4)) self.assertEqual(result, 12345) self.assertEqual(test4.a_long, 0) self.assertEqual(test4.a_struct.an_int, 0) self.assertEqual(test4.a_struct.another_int, 0) test4.a_struct.an_int = 0x12340000 test4.a_struct.another_int = 0x5678 func = dll._testfunc_union_by_reference2 func.restype = c_long func.argtypes = (POINTER(Test4),) result = func(byref(test4)) self.assertEqual(result, 0x12345678) self.assertEqual(test4.a_long, 0) self.assertEqual(test4.a_struct.an_int, 0) self.assertEqual(test4.a_struct.another_int, 0) test5.an_int = 0x12000000 test5.nested.an_int = 0x345600 test5.another_int = 0x78 func = dll._testfunc_union_by_reference3 func.restype = c_long func.argtypes = (POINTER(Test5),) result = func(byref(test5)) self.assertEqual(result, 0x12345678) self.assertEqual(test5.an_int, 0) self.assertEqual(test5.nested.an_int, 0) self.assertEqual(test5.another_int, 0) @unittest.skipIf(True, 'Test disabled for now - see bpo-16575/bpo-16576') def test_bitfield_by_value(self): # See bpo-16576 # These should mirror the structures in Modules/_ctypes/_ctypes_test.c class Test6(Structure): _fields_ = [ ('A', c_int, 1), ('B', c_int, 2), ('C', c_int, 3), ('D', c_int, 2), ] test6 = Test6() # As these are signed int fields, all are logically -1 due to sign # extension. test6.A = 1 test6.B = 3 test6.C = 7 test6.D = 3 dll = CDLL(_ctypes_test.__file__) with self.assertRaises(TypeError) as ctx: func = dll._testfunc_bitfield_by_value1 func.restype = c_long func.argtypes = (Test6,) result = func(test6) self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes ' 'a struct/union with a bitfield by value, which is ' 'unsupported.') # passing by reference should be OK func = dll._testfunc_bitfield_by_reference1 func.restype = c_long func.argtypes = (POINTER(Test6),) result = func(byref(test6)) self.assertEqual(result, -4) self.assertEqual(test6.A, 0) self.assertEqual(test6.B, 0) self.assertEqual(test6.C, 0) self.assertEqual(test6.D, 0) class Test7(Structure): _fields_ = [ ('A', c_uint, 1), ('B', c_uint, 2), ('C', c_uint, 3), ('D', c_uint, 2), ] test7 = Test7() test7.A = 1 test7.B = 3 test7.C = 7 test7.D = 3 func = dll._testfunc_bitfield_by_reference2 func.restype = c_long func.argtypes = (POINTER(Test7),) result = func(byref(test7)) self.assertEqual(result, 14) self.assertEqual(test7.A, 0) self.assertEqual(test7.B, 0) self.assertEqual(test7.C, 0) self.assertEqual(test7.D, 0) # for a union with bitfields, the union check happens first class Test8(Union): _fields_ = [ ('A', c_int, 1), ('B', c_int, 2), ('C', c_int, 3), ('D', c_int, 2), ] test8 = Test8() with self.assertRaises(TypeError) as ctx: func = dll._testfunc_bitfield_by_value2 func.restype = c_long func.argtypes = (Test8,) result = func(test8) self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes ' 'a union by value, which is unsupported.') class PointerMemberTestCase(unittest.TestCase): def test(self): # a Structure with a POINTER field class S(Structure): _fields_ = [("array", POINTER(c_int))] s = S() # We can assign arrays of the correct type s.array = (c_int * 3)(1, 2, 3) items = [s.array[i] for i in range(3)] self.assertEqual(items, [1, 2, 3]) # The following are bugs, but are included here because the unittests # also describe the current behaviour. # # This fails with SystemError: bad arg to internal function # or with IndexError (with a patch I have) s.array[0] = 42 items = [s.array[i] for i in range(3)] self.assertEqual(items, [42, 2, 3]) s.array[0] = 1 ## s.array[1] = 42 items = [s.array[i] for i in range(3)] self.assertEqual(items, [1, 2, 3]) def test_none_to_pointer_fields(self): class S(Structure): _fields_ = [("x", c_int), ("p", POINTER(c_int))] s = S() s.x = 12345678 s.p = None self.assertEqual(s.x, 12345678) class TestRecursiveStructure(unittest.TestCase): def test_contains_itself(self): class Recursive(Structure): pass try: Recursive._fields_ = [("next", Recursive)] except AttributeError as details: self.assertIn("Structure or union cannot contain itself", str(details)) else: self.fail("Structure or union cannot contain itself") def test_vice_versa(self): class First(Structure): pass class Second(Structure): pass First._fields_ = [("second", Second)] try: Second._fields_ = [("first", First)] except AttributeError as details: self.assertIn("_fields_ is final", str(details)) else: self.fail("AttributeError not raised") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_libc.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_libc.py
import unittest from ctypes import * import _ctypes_test lib = CDLL(_ctypes_test.__file__) def three_way_cmp(x, y): """Return -1 if x < y, 0 if x == y and 1 if x > y""" return (x > y) - (x < y) class LibTest(unittest.TestCase): def test_sqrt(self): lib.my_sqrt.argtypes = c_double, lib.my_sqrt.restype = c_double self.assertEqual(lib.my_sqrt(4.0), 2.0) import math self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0)) def test_qsort(self): comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char)) lib.my_qsort.argtypes = c_void_p, c_size_t, c_size_t, comparefunc lib.my_qsort.restype = None def sort(a, b): return three_way_cmp(a[0], b[0]) chars = create_string_buffer(b"spam, spam, and spam") lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort)) self.assertEqual(chars.raw, b" ,,aaaadmmmnpppsss\x00") if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_array_in_pointer.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_array_in_pointer.py
import unittest from ctypes import * from binascii import hexlify import re def dump(obj): # helper function to dump memory contents in hex, with a hyphen # between the bytes. h = hexlify(memoryview(obj)).decode() return re.sub(r"(..)", r"\1-", h)[:-1] class Value(Structure): _fields_ = [("val", c_byte)] class Container(Structure): _fields_ = [("pvalues", POINTER(Value))] class Test(unittest.TestCase): def test(self): # create an array of 4 values val_array = (Value * 4)() # create a container, which holds a pointer to the pvalues array. c = Container() c.pvalues = val_array # memory contains 4 NUL bytes now, that's correct self.assertEqual("00-00-00-00", dump(val_array)) # set the values of the array through the pointer: for i in range(4): c.pvalues[i].val = i + 1 values = [c.pvalues[i].val for i in range(4)] # These are the expected results: here s the bug! self.assertEqual( (values, dump(val_array)), ([1, 2, 3, 4], "01-02-03-04") ) def test_2(self): val_array = (Value * 4)() # memory contains 4 NUL bytes now, that's correct self.assertEqual("00-00-00-00", dump(val_array)) ptr = cast(val_array, POINTER(Value)) # set the values of the array through the pointer: for i in range(4): ptr[i].val = i + 1 values = [ptr[i].val for i in range(4)] # These are the expected results: here s the bug! self.assertEqual( (values, dump(val_array)), ([1, 2, 3, 4], "01-02-03-04") ) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_incomplete.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_incomplete.py
import unittest from ctypes import * ################################################################ # # The incomplete pointer example from the tutorial # class MyTestCase(unittest.TestCase): def test_incomplete_example(self): lpcell = POINTER("cell") class cell(Structure): _fields_ = [("name", c_char_p), ("next", lpcell)] SetPointerType(lpcell, cell) c1 = cell() c1.name = b"foo" c2 = cell() c2.name = b"bar" c1.next = pointer(c2) c2.next = pointer(c1) p = c1 result = [] for i in range(8): result.append(p.name) p = p.next[0] self.assertEqual(result, [b"foo", b"bar"] * 4) # to not leak references, we must clean _pointer_type_cache from ctypes import _pointer_type_cache del _pointer_type_cache[cell] ################################################################ if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_byteswap.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_byteswap.py
import sys, unittest, struct, math, ctypes from binascii import hexlify from ctypes import * def bin(s): return hexlify(memoryview(s)).decode().upper() # Each *simple* type that supports different byte orders has an # __ctype_be__ attribute that specifies the same type in BIG ENDIAN # byte order, and a __ctype_le__ attribute that is the same type in # LITTLE ENDIAN byte order. # # For Structures and Unions, these types are created on demand. class Test(unittest.TestCase): @unittest.skip('test disabled') def test_X(self): print(sys.byteorder, file=sys.stderr) for i in range(32): bits = BITS() setattr(bits, "i%s" % i, 1) dump(bits) def test_slots(self): class BigPoint(BigEndianStructure): __slots__ = () _fields_ = [("x", c_int), ("y", c_int)] class LowPoint(LittleEndianStructure): __slots__ = () _fields_ = [("x", c_int), ("y", c_int)] big = BigPoint() little = LowPoint() big.x = 4 big.y = 2 little.x = 2 little.y = 4 with self.assertRaises(AttributeError): big.z = 42 with self.assertRaises(AttributeError): little.z = 24 def test_endian_short(self): if sys.byteorder == "little": self.assertIs(c_short.__ctype_le__, c_short) self.assertIs(c_short.__ctype_be__.__ctype_le__, c_short) else: self.assertIs(c_short.__ctype_be__, c_short) self.assertIs(c_short.__ctype_le__.__ctype_be__, c_short) s = c_short.__ctype_be__(0x1234) self.assertEqual(bin(struct.pack(">h", 0x1234)), "1234") self.assertEqual(bin(s), "1234") self.assertEqual(s.value, 0x1234) s = c_short.__ctype_le__(0x1234) self.assertEqual(bin(struct.pack("<h", 0x1234)), "3412") self.assertEqual(bin(s), "3412") self.assertEqual(s.value, 0x1234) s = c_ushort.__ctype_be__(0x1234) self.assertEqual(bin(struct.pack(">h", 0x1234)), "1234") self.assertEqual(bin(s), "1234") self.assertEqual(s.value, 0x1234) s = c_ushort.__ctype_le__(0x1234) self.assertEqual(bin(struct.pack("<h", 0x1234)), "3412") self.assertEqual(bin(s), "3412") self.assertEqual(s.value, 0x1234) def test_endian_int(self): if sys.byteorder == "little": self.assertIs(c_int.__ctype_le__, c_int) self.assertIs(c_int.__ctype_be__.__ctype_le__, c_int) else: self.assertIs(c_int.__ctype_be__, c_int) self.assertIs(c_int.__ctype_le__.__ctype_be__, c_int) s = c_int.__ctype_be__(0x12345678) self.assertEqual(bin(struct.pack(">i", 0x12345678)), "12345678") self.assertEqual(bin(s), "12345678") self.assertEqual(s.value, 0x12345678) s = c_int.__ctype_le__(0x12345678) self.assertEqual(bin(struct.pack("<i", 0x12345678)), "78563412") self.assertEqual(bin(s), "78563412") self.assertEqual(s.value, 0x12345678) s = c_uint.__ctype_be__(0x12345678) self.assertEqual(bin(struct.pack(">I", 0x12345678)), "12345678") self.assertEqual(bin(s), "12345678") self.assertEqual(s.value, 0x12345678) s = c_uint.__ctype_le__(0x12345678) self.assertEqual(bin(struct.pack("<I", 0x12345678)), "78563412") self.assertEqual(bin(s), "78563412") self.assertEqual(s.value, 0x12345678) def test_endian_longlong(self): if sys.byteorder == "little": self.assertIs(c_longlong.__ctype_le__, c_longlong) self.assertIs(c_longlong.__ctype_be__.__ctype_le__, c_longlong) else: self.assertIs(c_longlong.__ctype_be__, c_longlong) self.assertIs(c_longlong.__ctype_le__.__ctype_be__, c_longlong) s = c_longlong.__ctype_be__(0x1234567890ABCDEF) self.assertEqual(bin(struct.pack(">q", 0x1234567890ABCDEF)), "1234567890ABCDEF") self.assertEqual(bin(s), "1234567890ABCDEF") self.assertEqual(s.value, 0x1234567890ABCDEF) s = c_longlong.__ctype_le__(0x1234567890ABCDEF) self.assertEqual(bin(struct.pack("<q", 0x1234567890ABCDEF)), "EFCDAB9078563412") self.assertEqual(bin(s), "EFCDAB9078563412") self.assertEqual(s.value, 0x1234567890ABCDEF) s = c_ulonglong.__ctype_be__(0x1234567890ABCDEF) self.assertEqual(bin(struct.pack(">Q", 0x1234567890ABCDEF)), "1234567890ABCDEF") self.assertEqual(bin(s), "1234567890ABCDEF") self.assertEqual(s.value, 0x1234567890ABCDEF) s = c_ulonglong.__ctype_le__(0x1234567890ABCDEF) self.assertEqual(bin(struct.pack("<Q", 0x1234567890ABCDEF)), "EFCDAB9078563412") self.assertEqual(bin(s), "EFCDAB9078563412") self.assertEqual(s.value, 0x1234567890ABCDEF) def test_endian_float(self): if sys.byteorder == "little": self.assertIs(c_float.__ctype_le__, c_float) self.assertIs(c_float.__ctype_be__.__ctype_le__, c_float) else: self.assertIs(c_float.__ctype_be__, c_float) self.assertIs(c_float.__ctype_le__.__ctype_be__, c_float) s = c_float(math.pi) self.assertEqual(bin(struct.pack("f", math.pi)), bin(s)) # Hm, what's the precision of a float compared to a double? self.assertAlmostEqual(s.value, math.pi, places=6) s = c_float.__ctype_le__(math.pi) self.assertAlmostEqual(s.value, math.pi, places=6) self.assertEqual(bin(struct.pack("<f", math.pi)), bin(s)) s = c_float.__ctype_be__(math.pi) self.assertAlmostEqual(s.value, math.pi, places=6) self.assertEqual(bin(struct.pack(">f", math.pi)), bin(s)) def test_endian_double(self): if sys.byteorder == "little": self.assertIs(c_double.__ctype_le__, c_double) self.assertIs(c_double.__ctype_be__.__ctype_le__, c_double) else: self.assertIs(c_double.__ctype_be__, c_double) self.assertIs(c_double.__ctype_le__.__ctype_be__, c_double) s = c_double(math.pi) self.assertEqual(s.value, math.pi) self.assertEqual(bin(struct.pack("d", math.pi)), bin(s)) s = c_double.__ctype_le__(math.pi) self.assertEqual(s.value, math.pi) self.assertEqual(bin(struct.pack("<d", math.pi)), bin(s)) s = c_double.__ctype_be__(math.pi) self.assertEqual(s.value, math.pi) self.assertEqual(bin(struct.pack(">d", math.pi)), bin(s)) def test_endian_other(self): self.assertIs(c_byte.__ctype_le__, c_byte) self.assertIs(c_byte.__ctype_be__, c_byte) self.assertIs(c_ubyte.__ctype_le__, c_ubyte) self.assertIs(c_ubyte.__ctype_be__, c_ubyte) self.assertIs(c_char.__ctype_le__, c_char) self.assertIs(c_char.__ctype_be__, c_char) def test_struct_fields_1(self): if sys.byteorder == "little": base = BigEndianStructure else: base = LittleEndianStructure class T(base): pass _fields_ = [("a", c_ubyte), ("b", c_byte), ("c", c_short), ("d", c_ushort), ("e", c_int), ("f", c_uint), ("g", c_long), ("h", c_ulong), ("i", c_longlong), ("k", c_ulonglong), ("l", c_float), ("m", c_double), ("n", c_char), ("b1", c_byte, 3), ("b2", c_byte, 3), ("b3", c_byte, 2), ("a", c_int * 3 * 3 * 3)] T._fields_ = _fields_ # these fields do not support different byte order: for typ in c_wchar, c_void_p, POINTER(c_int): _fields_.append(("x", typ)) class T(base): pass self.assertRaises(TypeError, setattr, T, "_fields_", [("x", typ)]) def test_struct_struct(self): # nested structures with different byteorders # create nested structures with given byteorders and set memory to data for nested, data in ( (BigEndianStructure, b'\0\0\0\1\0\0\0\2'), (LittleEndianStructure, b'\1\0\0\0\2\0\0\0'), ): for parent in ( BigEndianStructure, LittleEndianStructure, Structure, ): class NestedStructure(nested): _fields_ = [("x", c_uint32), ("y", c_uint32)] class TestStructure(parent): _fields_ = [("point", NestedStructure)] self.assertEqual(len(data), sizeof(TestStructure)) ptr = POINTER(TestStructure) s = cast(data, ptr)[0] del ctypes._pointer_type_cache[TestStructure] self.assertEqual(s.point.x, 1) self.assertEqual(s.point.y, 2) def test_struct_fields_2(self): # standard packing in struct uses no alignment. # So, we have to align using pad bytes. # # Unaligned accesses will crash Python (on those platforms that # don't allow it, like sparc solaris). if sys.byteorder == "little": base = BigEndianStructure fmt = ">bxhid" else: base = LittleEndianStructure fmt = "<bxhid" class S(base): _fields_ = [("b", c_byte), ("h", c_short), ("i", c_int), ("d", c_double)] s1 = S(0x12, 0x1234, 0x12345678, 3.14) s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14) self.assertEqual(bin(s1), bin(s2)) def test_unaligned_nonnative_struct_fields(self): if sys.byteorder == "little": base = BigEndianStructure fmt = ">b h xi xd" else: base = LittleEndianStructure fmt = "<b h xi xd" class S(base): _pack_ = 1 _fields_ = [("b", c_byte), ("h", c_short), ("_1", c_byte), ("i", c_int), ("_2", c_byte), ("d", c_double)] s1 = S() s1.b = 0x12 s1.h = 0x1234 s1.i = 0x12345678 s1.d = 3.14 s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14) self.assertEqual(bin(s1), bin(s2)) def test_unaligned_native_struct_fields(self): if sys.byteorder == "little": fmt = "<b h xi xd" else: base = LittleEndianStructure fmt = ">b h xi xd" class S(Structure): _pack_ = 1 _fields_ = [("b", c_byte), ("h", c_short), ("_1", c_byte), ("i", c_int), ("_2", c_byte), ("d", c_double)] s1 = S() s1.b = 0x12 s1.h = 0x1234 s1.i = 0x12345678 s1.d = 3.14 s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14) self.assertEqual(bin(s1), bin(s2)) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_frombuffer.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_frombuffer.py
from ctypes import * import array import gc import unittest class X(Structure): _fields_ = [("c_int", c_int)] init_called = False def __init__(self): self._init_called = True class Test(unittest.TestCase): def test_from_buffer(self): a = array.array("i", range(16)) x = (c_int * 16).from_buffer(a) y = X.from_buffer(a) self.assertEqual(y.c_int, a[0]) self.assertFalse(y.init_called) self.assertEqual(x[:], a.tolist()) a[0], a[-1] = 200, -200 self.assertEqual(x[:], a.tolist()) self.assertRaises(BufferError, a.append, 100) self.assertRaises(BufferError, a.pop) del x; del y; gc.collect(); gc.collect(); gc.collect() a.append(100) a.pop() x = (c_int * 16).from_buffer(a) self.assertIn(a, [obj.obj if isinstance(obj, memoryview) else obj for obj in x._objects.values()]) expected = x[:] del a; gc.collect(); gc.collect(); gc.collect() self.assertEqual(x[:], expected) with self.assertRaisesRegex(TypeError, "not writable"): (c_char * 16).from_buffer(b"a" * 16) with self.assertRaisesRegex(TypeError, "not writable"): (c_char * 16).from_buffer(memoryview(b"a" * 16)) with self.assertRaisesRegex(TypeError, "not C contiguous"): (c_char * 16).from_buffer(memoryview(bytearray(b"a" * 16))[::-1]) msg = "bytes-like object is required" with self.assertRaisesRegex(TypeError, msg): (c_char * 16).from_buffer("a" * 16) def test_fortran_contiguous(self): try: import _testbuffer except ImportError as err: self.skipTest(str(err)) flags = _testbuffer.ND_WRITABLE | _testbuffer.ND_FORTRAN array = _testbuffer.ndarray( [97] * 16, format="B", shape=[4, 4], flags=flags) with self.assertRaisesRegex(TypeError, "not C contiguous"): (c_char * 16).from_buffer(array) array = memoryview(array) self.assertTrue(array.f_contiguous) self.assertFalse(array.c_contiguous) with self.assertRaisesRegex(TypeError, "not C contiguous"): (c_char * 16).from_buffer(array) def test_from_buffer_with_offset(self): a = array.array("i", range(16)) x = (c_int * 15).from_buffer(a, sizeof(c_int)) self.assertEqual(x[:], a.tolist()[1:]) with self.assertRaises(ValueError): c_int.from_buffer(a, -1) with self.assertRaises(ValueError): (c_int * 16).from_buffer(a, sizeof(c_int)) with self.assertRaises(ValueError): (c_int * 1).from_buffer(a, 16 * sizeof(c_int)) def test_from_buffer_memoryview(self): a = [c_char.from_buffer(memoryview(bytearray(b'a')))] a.append(a) del a gc.collect() # Should not crash def test_from_buffer_copy(self): a = array.array("i", range(16)) x = (c_int * 16).from_buffer_copy(a) y = X.from_buffer_copy(a) self.assertEqual(y.c_int, a[0]) self.assertFalse(y.init_called) self.assertEqual(x[:], list(range(16))) a[0], a[-1] = 200, -200 self.assertEqual(x[:], list(range(16))) a.append(100) self.assertEqual(x[:], list(range(16))) self.assertEqual(x._objects, None) del a; gc.collect(); gc.collect(); gc.collect() self.assertEqual(x[:], list(range(16))) x = (c_char * 16).from_buffer_copy(b"a" * 16) self.assertEqual(x[:], b"a" * 16) with self.assertRaises(TypeError): (c_char * 16).from_buffer_copy("a" * 16) def test_from_buffer_copy_with_offset(self): a = array.array("i", range(16)) x = (c_int * 15).from_buffer_copy(a, sizeof(c_int)) self.assertEqual(x[:], a.tolist()[1:]) with self.assertRaises(ValueError): c_int.from_buffer_copy(a, -1) with self.assertRaises(ValueError): (c_int * 16).from_buffer_copy(a, sizeof(c_int)) with self.assertRaises(ValueError): (c_int * 1).from_buffer_copy(a, 16 * sizeof(c_int)) def test_abstract(self): from ctypes import _Pointer, _SimpleCData, _CFuncPtr self.assertRaises(TypeError, Array.from_buffer, bytearray(10)) self.assertRaises(TypeError, Structure.from_buffer, bytearray(10)) self.assertRaises(TypeError, Union.from_buffer, bytearray(10)) self.assertRaises(TypeError, _CFuncPtr.from_buffer, bytearray(10)) self.assertRaises(TypeError, _Pointer.from_buffer, bytearray(10)) self.assertRaises(TypeError, _SimpleCData.from_buffer, bytearray(10)) self.assertRaises(TypeError, Array.from_buffer_copy, b"123") self.assertRaises(TypeError, Structure.from_buffer_copy, b"123") self.assertRaises(TypeError, Union.from_buffer_copy, b"123") self.assertRaises(TypeError, _CFuncPtr.from_buffer_copy, b"123") self.assertRaises(TypeError, _Pointer.from_buffer_copy, b"123") self.assertRaises(TypeError, _SimpleCData.from_buffer_copy, b"123") if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_win32.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_win32.py
# Windows specific tests from ctypes import * import unittest, sys from test import support import _ctypes_test # Only windows 32-bit has different calling conventions. @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') @unittest.skipUnless(sizeof(c_void_p) == sizeof(c_int), "sizeof c_void_p and c_int differ") class WindowsTestCase(unittest.TestCase): def test_callconv_1(self): # Testing stdcall function IsWindow = windll.user32.IsWindow # ValueError: Procedure probably called with not enough arguments # (4 bytes missing) self.assertRaises(ValueError, IsWindow) # This one should succeed... self.assertEqual(0, IsWindow(0)) # ValueError: Procedure probably called with too many arguments # (8 bytes in excess) self.assertRaises(ValueError, IsWindow, 0, 0, 0) def test_callconv_2(self): # Calling stdcall function as cdecl IsWindow = cdll.user32.IsWindow # ValueError: Procedure called with not enough arguments # (4 bytes missing) or wrong calling convention self.assertRaises(ValueError, IsWindow, None) @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') class FunctionCallTestCase(unittest.TestCase): @unittest.skipUnless('MSC' in sys.version, "SEH only supported by MSC") @unittest.skipIf(sys.executable.lower().endswith('_d.exe'), "SEH not enabled in debug builds") def test_SEH(self): # Disable faulthandler to prevent logging the warning: # "Windows fatal exception: access violation" with support.disable_faulthandler(): # Call functions with invalid arguments, and make sure # that access violations are trapped and raise an # exception. self.assertRaises(OSError, windll.kernel32.GetModuleHandleA, 32) def test_noargs(self): # This is a special case on win32 x64 windll.user32.GetDesktopWindow() @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') class ReturnStructSizesTestCase(unittest.TestCase): def test_sizes(self): dll = CDLL(_ctypes_test.__file__) for i in range(1, 11): fields = [ (f"f{f}", c_char) for f in range(1, i + 1)] class S(Structure): _fields_ = fields f = getattr(dll, f"TestSize{i}") f.restype = S res = f() for i, f in enumerate(fields): value = getattr(res, f[0]) expected = bytes([ord('a') + i]) self.assertEqual(value, expected) @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') class TestWintypes(unittest.TestCase): def test_HWND(self): from ctypes import wintypes self.assertEqual(sizeof(wintypes.HWND), sizeof(c_void_p)) def test_PARAM(self): from ctypes import wintypes self.assertEqual(sizeof(wintypes.WPARAM), sizeof(c_void_p)) self.assertEqual(sizeof(wintypes.LPARAM), sizeof(c_void_p)) def test_COMError(self): from _ctypes import COMError if support.HAVE_DOCSTRINGS: self.assertEqual(COMError.__doc__, "Raised when a COM method call failed.") ex = COMError(-1, "text", ("details",)) self.assertEqual(ex.hresult, -1) self.assertEqual(ex.text, "text") self.assertEqual(ex.details, ("details",)) @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') class TestWinError(unittest.TestCase): def test_winerror(self): # see Issue 16169 import errno ERROR_INVALID_PARAMETER = 87 msg = FormatError(ERROR_INVALID_PARAMETER).strip() args = (errno.EINVAL, msg, None, ERROR_INVALID_PARAMETER) e = WinError(ERROR_INVALID_PARAMETER) self.assertEqual(e.args, args) self.assertEqual(e.errno, errno.EINVAL) self.assertEqual(e.winerror, ERROR_INVALID_PARAMETER) windll.kernel32.SetLastError(ERROR_INVALID_PARAMETER) try: raise WinError() except OSError as exc: e = exc self.assertEqual(e.args, args) self.assertEqual(e.errno, errno.EINVAL) self.assertEqual(e.winerror, ERROR_INVALID_PARAMETER) class Structures(unittest.TestCase): def test_struct_by_value(self): class POINT(Structure): _fields_ = [("x", c_long), ("y", c_long)] class RECT(Structure): _fields_ = [("left", c_long), ("top", c_long), ("right", c_long), ("bottom", c_long)] dll = CDLL(_ctypes_test.__file__) pt = POINT(15, 25) left = c_long.in_dll(dll, 'left') top = c_long.in_dll(dll, 'top') right = c_long.in_dll(dll, 'right') bottom = c_long.in_dll(dll, 'bottom') rect = RECT(left, top, right, bottom) PointInRect = dll.PointInRect PointInRect.argtypes = [POINTER(RECT), POINT] self.assertEqual(1, PointInRect(byref(rect), pt)) ReturnRect = dll.ReturnRect ReturnRect.argtypes = [c_int, RECT, POINTER(RECT), POINT, RECT, POINTER(RECT), POINT, RECT] ReturnRect.restype = RECT for i in range(4): ret = ReturnRect(i, rect, pointer(rect), pt, rect, byref(rect), pt, rect) # the c function will check and modify ret if something is # passed in improperly self.assertEqual(ret.left, left.value) self.assertEqual(ret.right, right.value) self.assertEqual(ret.top, top.value) self.assertEqual(ret.bottom, bottom.value) # to not leak references, we must clean _pointer_type_cache from ctypes import _pointer_type_cache del _pointer_type_cache[RECT] if __name__ == '__main__': unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_find.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_find.py
import unittest import os.path import sys import test.support from ctypes import * from ctypes.util import find_library # On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode. class Test_OpenGL_libs(unittest.TestCase): @classmethod def setUpClass(cls): lib_gl = lib_glu = lib_gle = None if sys.platform == "win32": lib_gl = find_library("OpenGL32") lib_glu = find_library("Glu32") elif sys.platform == "darwin": lib_gl = lib_glu = find_library("OpenGL") else: lib_gl = find_library("GL") lib_glu = find_library("GLU") lib_gle = find_library("gle") ## print, for debugging if test.support.verbose: print("OpenGL libraries:") for item in (("GL", lib_gl), ("GLU", lib_glu), ("gle", lib_gle)): print("\t", item) cls.gl = cls.glu = cls.gle = None if lib_gl: try: cls.gl = CDLL(lib_gl, mode=RTLD_GLOBAL) except OSError: pass if lib_glu: try: cls.glu = CDLL(lib_glu, RTLD_GLOBAL) except OSError: pass if lib_gle: try: cls.gle = CDLL(lib_gle) except OSError: pass @classmethod def tearDownClass(cls): cls.gl = cls.glu = cls.gle = None def test_gl(self): if self.gl is None: self.skipTest('lib_gl not available') self.gl.glClearIndex def test_glu(self): if self.glu is None: self.skipTest('lib_glu not available') self.glu.gluBeginCurve def test_gle(self): if self.gle is None: self.skipTest('lib_gle not available') self.gle.gleGetJoinStyle def test_shell_injection(self): result = find_library('; echo Hello shell > ' + test.support.TESTFN) self.assertFalse(os.path.lexists(test.support.TESTFN)) self.assertIsNone(result) @unittest.skipUnless(sys.platform.startswith('linux'), 'Test only valid for Linux') class LibPathFindTest(unittest.TestCase): def test_find_on_libpath(self): import subprocess import tempfile try: p = subprocess.Popen(['gcc', '--version'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) out, _ = p.communicate() except OSError: raise unittest.SkipTest('gcc, needed for test, not available') with tempfile.TemporaryDirectory() as d: # create an empty temporary file srcname = os.path.join(d, 'dummy.c') libname = 'py_ctypes_test_dummy' dstname = os.path.join(d, 'lib%s.so' % libname) with open(srcname, 'w') as f: pass self.assertTrue(os.path.exists(srcname)) # compile the file to a shared library cmd = ['gcc', '-o', dstname, '--shared', '-Wl,-soname,lib%s.so' % libname, srcname] out = subprocess.check_output(cmd) self.assertTrue(os.path.exists(dstname)) # now check that the .so can't be found (since not in # LD_LIBRARY_PATH) self.assertIsNone(find_library(libname)) # now add the location to LD_LIBRARY_PATH with test.support.EnvironmentVarGuard() as env: KEY = 'LD_LIBRARY_PATH' if KEY not in env: v = d else: v = '%s:%s' % (env[KEY], d) env.set(KEY, v) # now check that the .so can be found (since in # LD_LIBRARY_PATH) self.assertEqual(find_library(libname), 'lib%s.so' % libname) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_init.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_init.py
from ctypes import * import unittest class X(Structure): _fields_ = [("a", c_int), ("b", c_int)] new_was_called = False def __new__(cls): result = super().__new__(cls) result.new_was_called = True return result def __init__(self): self.a = 9 self.b = 12 class Y(Structure): _fields_ = [("x", X)] class InitTest(unittest.TestCase): def test_get(self): # make sure the only accessing a nested structure # doesn't call the structure's __new__ and __init__ y = Y() self.assertEqual((y.x.a, y.x.b), (0, 0)) self.assertEqual(y.x.new_was_called, False) # But explicitly creating an X structure calls __new__ and __init__, of course. x = X() self.assertEqual((x.a, x.b), (9, 12)) self.assertEqual(x.new_was_called, True) y.x = x self.assertEqual((y.x.a, y.x.b), (9, 12)) self.assertEqual(y.x.new_was_called, False) if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_pep3118.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/test/test_pep3118.py
import unittest from ctypes import * import re, sys if sys.byteorder == "little": THIS_ENDIAN = "<" OTHER_ENDIAN = ">" else: THIS_ENDIAN = ">" OTHER_ENDIAN = "<" def normalize(format): # Remove current endian specifier and white space from a format # string if format is None: return "" format = format.replace(OTHER_ENDIAN, THIS_ENDIAN) return re.sub(r"\s", "", format) class Test(unittest.TestCase): def test_native_types(self): for tp, fmt, shape, itemtp in native_types: ob = tp() v = memoryview(ob) try: self.assertEqual(normalize(v.format), normalize(fmt)) if shape: self.assertEqual(len(v), shape[0]) else: self.assertEqual(len(v) * sizeof(itemtp), sizeof(ob)) self.assertEqual(v.itemsize, sizeof(itemtp)) self.assertEqual(v.shape, shape) # XXX Issue #12851: PyCData_NewGetBuffer() must provide strides # if requested. memoryview currently reconstructs missing # stride information, so this assert will fail. # self.assertEqual(v.strides, ()) # they are always read/write self.assertFalse(v.readonly) if v.shape: n = 1 for dim in v.shape: n = n * dim self.assertEqual(n * v.itemsize, len(v.tobytes())) except: # so that we can see the failing type print(tp) raise def test_endian_types(self): for tp, fmt, shape, itemtp in endian_types: ob = tp() v = memoryview(ob) try: self.assertEqual(v.format, fmt) if shape: self.assertEqual(len(v), shape[0]) else: self.assertEqual(len(v) * sizeof(itemtp), sizeof(ob)) self.assertEqual(v.itemsize, sizeof(itemtp)) self.assertEqual(v.shape, shape) # XXX Issue #12851 # self.assertEqual(v.strides, ()) # they are always read/write self.assertFalse(v.readonly) if v.shape: n = 1 for dim in v.shape: n = n * dim self.assertEqual(n, len(v)) except: # so that we can see the failing type print(tp) raise # define some structure classes class Point(Structure): _fields_ = [("x", c_long), ("y", c_long)] class PackedPoint(Structure): _pack_ = 2 _fields_ = [("x", c_long), ("y", c_long)] class Point2(Structure): pass Point2._fields_ = [("x", c_long), ("y", c_long)] class EmptyStruct(Structure): _fields_ = [] class aUnion(Union): _fields_ = [("a", c_int)] class StructWithArrays(Structure): _fields_ = [("x", c_long * 3 * 2), ("y", Point * 4)] class Incomplete(Structure): pass class Complete(Structure): pass PComplete = POINTER(Complete) Complete._fields_ = [("a", c_long)] ################################################################ # # This table contains format strings as they look on little endian # machines. The test replaces '<' with '>' on big endian machines. # # Platform-specific type codes s_bool = {1: '?', 2: 'H', 4: 'L', 8: 'Q'}[sizeof(c_bool)] s_short = {2: 'h', 4: 'l', 8: 'q'}[sizeof(c_short)] s_ushort = {2: 'H', 4: 'L', 8: 'Q'}[sizeof(c_ushort)] s_int = {2: 'h', 4: 'i', 8: 'q'}[sizeof(c_int)] s_uint = {2: 'H', 4: 'I', 8: 'Q'}[sizeof(c_uint)] s_long = {4: 'l', 8: 'q'}[sizeof(c_long)] s_ulong = {4: 'L', 8: 'Q'}[sizeof(c_ulong)] s_longlong = "q" s_ulonglong = "Q" s_float = "f" s_double = "d" s_longdouble = "g" # Alias definitions in ctypes/__init__.py if c_int is c_long: s_int = s_long if c_uint is c_ulong: s_uint = s_ulong if c_longlong is c_long: s_longlong = s_long if c_ulonglong is c_ulong: s_ulonglong = s_ulong if c_longdouble is c_double: s_longdouble = s_double native_types = [ # type format shape calc itemsize ## simple types (c_char, "<c", (), c_char), (c_byte, "<b", (), c_byte), (c_ubyte, "<B", (), c_ubyte), (c_short, "<" + s_short, (), c_short), (c_ushort, "<" + s_ushort, (), c_ushort), (c_int, "<" + s_int, (), c_int), (c_uint, "<" + s_uint, (), c_uint), (c_long, "<" + s_long, (), c_long), (c_ulong, "<" + s_ulong, (), c_ulong), (c_longlong, "<" + s_longlong, (), c_longlong), (c_ulonglong, "<" + s_ulonglong, (), c_ulonglong), (c_float, "<f", (), c_float), (c_double, "<d", (), c_double), (c_longdouble, "<" + s_longdouble, (), c_longdouble), (c_bool, "<" + s_bool, (), c_bool), (py_object, "<O", (), py_object), ## pointers (POINTER(c_byte), "&<b", (), POINTER(c_byte)), (POINTER(POINTER(c_long)), "&&<" + s_long, (), POINTER(POINTER(c_long))), ## arrays and pointers (c_double * 4, "<d", (4,), c_double), (c_float * 4 * 3 * 2, "<f", (2,3,4), c_float), (POINTER(c_short) * 2, "&<" + s_short, (2,), POINTER(c_short)), (POINTER(c_short) * 2 * 3, "&<" + s_short, (3,2,), POINTER(c_short)), (POINTER(c_short * 2), "&(2)<" + s_short, (), POINTER(c_short)), ## structures and unions (Point, "T{<l:x:<l:y:}".replace('l', s_long), (), Point), # packed structures do not implement the pep (PackedPoint, "B", (), PackedPoint), (Point2, "T{<l:x:<l:y:}".replace('l', s_long), (), Point2), (EmptyStruct, "T{}", (), EmptyStruct), # the pep doesn't support unions (aUnion, "B", (), aUnion), # structure with sub-arrays (StructWithArrays, "T{(2,3)<l:x:(4)T{<l:x:<l:y:}:y:}".replace('l', s_long), (), StructWithArrays), (StructWithArrays * 3, "T{(2,3)<l:x:(4)T{<l:x:<l:y:}:y:}".replace('l', s_long), (3,), StructWithArrays), ## pointer to incomplete structure (Incomplete, "B", (), Incomplete), (POINTER(Incomplete), "&B", (), POINTER(Incomplete)), # 'Complete' is a structure that starts incomplete, but is completed after the # pointer type to it has been created. (Complete, "T{<l:a:}".replace('l', s_long), (), Complete), # Unfortunately the pointer format string is not fixed... (POINTER(Complete), "&B", (), POINTER(Complete)), ## other # function signatures are not implemented (CFUNCTYPE(None), "X{}", (), CFUNCTYPE(None)), ] class BEPoint(BigEndianStructure): _fields_ = [("x", c_long), ("y", c_long)] class LEPoint(LittleEndianStructure): _fields_ = [("x", c_long), ("y", c_long)] ################################################################ # # This table contains format strings as they really look, on both big # and little endian machines. # endian_types = [ (BEPoint, "T{>l:x:>l:y:}".replace('l', s_long), (), BEPoint), (LEPoint, "T{<l:x:<l:y:}".replace('l', s_long), (), LEPoint), (POINTER(BEPoint), "&T{>l:x:>l:y:}".replace('l', s_long), (), POINTER(BEPoint)), (POINTER(LEPoint), "&T{<l:x:<l:y:}".replace('l', s_long), (), POINTER(LEPoint)), ] if __name__ == "__main__": unittest.main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/dylib.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/dylib.py
""" Generic dylib path manipulation """ import re __all__ = ['dylib_info'] DYLIB_RE = re.compile(r"""(?x) (?P<location>^.*)(?:^|/) (?P<name> (?P<shortname>\w+?) (?:\.(?P<version>[^._]+))? (?:_(?P<suffix>[^._]+))? \.dylib$ ) """) def dylib_info(filename): """ A dylib name can take one of the following four forms: Location/Name.SomeVersion_Suffix.dylib Location/Name.SomeVersion.dylib Location/Name_Suffix.dylib Location/Name.dylib returns None if not found or a mapping equivalent to: dict( location='Location', name='Name.SomeVersion_Suffix.dylib', shortname='Name', version='SomeVersion', suffix='Suffix', ) Note that SomeVersion and Suffix are optional and may be None if not present. """ is_dylib = DYLIB_RE.match(filename) if not is_dylib: return None return is_dylib.groupdict() def test_dylib_info(): def d(location=None, name=None, shortname=None, version=None, suffix=None): return dict( location=location, name=name, shortname=shortname, version=version, suffix=suffix ) assert dylib_info('completely/invalid') is None assert dylib_info('completely/invalide_debug') is None assert dylib_info('P/Foo.dylib') == d('P', 'Foo.dylib', 'Foo') assert dylib_info('P/Foo_debug.dylib') == d('P', 'Foo_debug.dylib', 'Foo', suffix='debug') assert dylib_info('P/Foo.A.dylib') == d('P', 'Foo.A.dylib', 'Foo', 'A') assert dylib_info('P/Foo_debug.A.dylib') == d('P', 'Foo_debug.A.dylib', 'Foo_debug', 'A') assert dylib_info('P/Foo.A_debug.dylib') == d('P', 'Foo.A_debug.dylib', 'Foo', 'A', 'debug') if __name__ == '__main__': test_dylib_info()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/__init__.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/__init__.py
""" Enough Mach-O to make your head spin. See the relevant header files in /usr/include/mach-o And also Apple's documentation. """ __version__ = '1.0'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/dyld.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/dyld.py
""" dyld emulation """ import os from ctypes.macholib.framework import framework_info from ctypes.macholib.dylib import dylib_info from itertools import * __all__ = [ 'dyld_find', 'framework_find', 'framework_info', 'dylib_info', ] # These are the defaults as per man dyld(1) # DEFAULT_FRAMEWORK_FALLBACK = [ os.path.expanduser("~/Library/Frameworks"), "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", ] DEFAULT_LIBRARY_FALLBACK = [ os.path.expanduser("~/lib"), "/usr/local/lib", "/lib", "/usr/lib", ] def dyld_env(env, var): if env is None: env = os.environ rval = env.get(var) if rval is None: return [] return rval.split(':') def dyld_image_suffix(env=None): if env is None: env = os.environ return env.get('DYLD_IMAGE_SUFFIX') def dyld_framework_path(env=None): return dyld_env(env, 'DYLD_FRAMEWORK_PATH') def dyld_library_path(env=None): return dyld_env(env, 'DYLD_LIBRARY_PATH') def dyld_fallback_framework_path(env=None): return dyld_env(env, 'DYLD_FALLBACK_FRAMEWORK_PATH') def dyld_fallback_library_path(env=None): return dyld_env(env, 'DYLD_FALLBACK_LIBRARY_PATH') def dyld_image_suffix_search(iterator, env=None): """For a potential path iterator, add DYLD_IMAGE_SUFFIX semantics""" suffix = dyld_image_suffix(env) if suffix is None: return iterator def _inject(iterator=iterator, suffix=suffix): for path in iterator: if path.endswith('.dylib'): yield path[:-len('.dylib')] + suffix + '.dylib' else: yield path + suffix yield path return _inject() def dyld_override_search(name, env=None): # If DYLD_FRAMEWORK_PATH is set and this dylib_name is a # framework name, use the first file that exists in the framework # path if any. If there is none go on to search the DYLD_LIBRARY_PATH # if any. framework = framework_info(name) if framework is not None: for path in dyld_framework_path(env): yield os.path.join(path, framework['name']) # If DYLD_LIBRARY_PATH is set then use the first file that exists # in the path. If none use the original name. for path in dyld_library_path(env): yield os.path.join(path, os.path.basename(name)) def dyld_executable_path_search(name, executable_path=None): # If we haven't done any searching and found a library and the # dylib_name starts with "@executable_path/" then construct the # library name. if name.startswith('@executable_path/') and executable_path is not None: yield os.path.join(executable_path, name[len('@executable_path/'):]) def dyld_default_search(name, env=None): yield name framework = framework_info(name) if framework is not None: fallback_framework_path = dyld_fallback_framework_path(env) for path in fallback_framework_path: yield os.path.join(path, framework['name']) fallback_library_path = dyld_fallback_library_path(env) for path in fallback_library_path: yield os.path.join(path, os.path.basename(name)) if framework is not None and not fallback_framework_path: for path in DEFAULT_FRAMEWORK_FALLBACK: yield os.path.join(path, framework['name']) if not fallback_library_path: for path in DEFAULT_LIBRARY_FALLBACK: yield os.path.join(path, os.path.basename(name)) def dyld_find(name, executable_path=None, env=None): """ Find a library or framework using dyld semantics """ for path in dyld_image_suffix_search(chain( dyld_override_search(name, env), dyld_executable_path_search(name, executable_path), dyld_default_search(name, env), ), env): if os.path.isfile(path): return path raise ValueError("dylib %s could not be found" % (name,)) def framework_find(fn, executable_path=None, env=None): """ Find a framework using dyld semantics in a very loose manner. Will take input such as: Python Python.framework Python.framework/Versions/Current """ error = None try: return dyld_find(fn, executable_path=executable_path, env=env) except ValueError as e: error = e fmwk_index = fn.rfind('.framework') if fmwk_index == -1: fmwk_index = len(fn) fn += '.framework' fn = os.path.join(fn, os.path.basename(fn[:fmwk_index])) try: return dyld_find(fn, executable_path=executable_path, env=env) except ValueError: raise error finally: error = None def test_dyld_find(): env = {} assert dyld_find('libSystem.dylib') == '/usr/lib/libSystem.dylib' assert dyld_find('System.framework/System') == '/System/Library/Frameworks/System.framework/System' if __name__ == '__main__': test_dyld_find()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/framework.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/ctypes/macholib/framework.py
""" Generic framework path manipulation """ import re __all__ = ['framework_info'] STRICT_FRAMEWORK_RE = re.compile(r"""(?x) (?P<location>^.*)(?:^|/) (?P<name> (?P<shortname>\w+).framework/ (?:Versions/(?P<version>[^/]+)/)? (?P=shortname) (?:_(?P<suffix>[^_]+))? )$ """) def framework_info(filename): """ A framework name can take one of the following four forms: Location/Name.framework/Versions/SomeVersion/Name_Suffix Location/Name.framework/Versions/SomeVersion/Name Location/Name.framework/Name_Suffix Location/Name.framework/Name returns None if not found, or a mapping equivalent to: dict( location='Location', name='Name.framework/Versions/SomeVersion/Name_Suffix', shortname='Name', version='SomeVersion', suffix='Suffix', ) Note that SomeVersion and Suffix are optional and may be None if not present """ is_framework = STRICT_FRAMEWORK_RE.match(filename) if not is_framework: return None return is_framework.groupdict() def test_framework_info(): def d(location=None, name=None, shortname=None, version=None, suffix=None): return dict( location=location, name=name, shortname=shortname, version=version, suffix=suffix ) assert framework_info('completely/invalid') is None assert framework_info('completely/invalid/_debug') is None assert framework_info('P/F.framework') is None assert framework_info('P/F.framework/_debug') is None assert framework_info('P/F.framework/F') == d('P', 'F.framework/F', 'F') assert framework_info('P/F.framework/F_debug') == d('P', 'F.framework/F_debug', 'F', suffix='debug') assert framework_info('P/F.framework/Versions') is None assert framework_info('P/F.framework/Versions/A') is None assert framework_info('P/F.framework/Versions/A/F') == d('P', 'F.framework/Versions/A/F', 'F', 'A') assert framework_info('P/F.framework/Versions/A/F_debug') == d('P', 'F.framework/Versions/A/F_debug', 'F', 'A', 'debug') if __name__ == '__main__': test_framework_info()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/client.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/client.py
r"""HTTP/1.1 client library <intro stuff goes here> <other stuff, too> HTTPConnection goes through a number of "states", which define when a client may legally make another request or fetch the response for a particular request. This diagram details these state transitions: (null) | | HTTPConnection() v Idle | | putrequest() v Request-started | | ( putheader() )* endheaders() v Request-sent |\_____________________________ | | getresponse() raises | response = getresponse() | ConnectionError v v Unread-response Idle [Response-headers-read] |\____________________ | | | response.read() | putrequest() v v Idle Req-started-unread-response ______/| / | response.read() | | ( putheader() )* endheaders() v v Request-started Req-sent-unread-response | | response.read() v Request-sent This diagram presents the following rules: -- a second request may not be started until {response-headers-read} -- a response [object] cannot be retrieved until {request-sent} -- there is no differentiation between an unread response body and a partially read response body Note: this enforcement is applied by the HTTPConnection class. The HTTPResponse class does not enforce this state machine, which implies sophisticated clients may accelerate the request/response pipeline. Caution should be taken, though: accelerating the states beyond the above pattern may imply knowledge of the server's connection-close behavior for certain requests. For example, it is impossible to tell whether the server will close the connection UNTIL the response headers have been read; this means that further requests cannot be placed into the pipeline until it is known that the server will NOT be closing the connection. Logical State __state __response ------------- ------- ---------- Idle _CS_IDLE None Request-started _CS_REQ_STARTED None Request-sent _CS_REQ_SENT None Unread-response _CS_IDLE <response_class> Req-started-unread-response _CS_REQ_STARTED <response_class> Req-sent-unread-response _CS_REQ_SENT <response_class> """ import email.parser import email.message import http import io import re import socket import collections.abc from urllib.parse import urlsplit # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for simplicity __all__ = ["HTTPResponse", "HTTPConnection", "HTTPException", "NotConnected", "UnknownProtocol", "UnknownTransferEncoding", "UnimplementedFileMode", "IncompleteRead", "InvalidURL", "ImproperConnectionState", "CannotSendRequest", "CannotSendHeader", "ResponseNotReady", "BadStatusLine", "LineTooLong", "RemoteDisconnected", "error", "responses"] HTTP_PORT = 80 HTTPS_PORT = 443 _UNKNOWN = 'UNKNOWN' # connection states _CS_IDLE = 'Idle' _CS_REQ_STARTED = 'Request-started' _CS_REQ_SENT = 'Request-sent' # hack to maintain backwards compatibility globals().update(http.HTTPStatus.__members__) # another hack to maintain backwards compatibility # Mapping status codes to official W3C names responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()} # maximal amount of data to read at one time in _safe_read MAXAMOUNT = 1048576 # maximal line length when calling readline(). _MAXLINE = 65536 _MAXHEADERS = 100 # Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2) # # VCHAR = %x21-7E # obs-text = %x80-FF # header-field = field-name ":" OWS field-value OWS # field-name = token # field-value = *( field-content / obs-fold ) # field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] # field-vchar = VCHAR / obs-text # # obs-fold = CRLF 1*( SP / HTAB ) # ; obsolete line folding # ; see Section 3.2.4 # token = 1*tchar # # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" # / DIGIT / ALPHA # ; any VCHAR, except delimiters # # VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1 # the patterns for both name and value are more lenient than RFC # definitions to allow for backwards compatibility _is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch _is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search # These characters are not allowed within HTTP URL paths. # See https://tools.ietf.org/html/rfc3986#section-3.3 and the # https://tools.ietf.org/html/rfc3986#appendix-A pchar definition. # Prevents CVE-2019-9740. Includes control characters such as \r\n. # We don't restrict chars above \x7f as putrequest() limits us to ASCII. _contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]') # Arguably only these _should_ allowed: # _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$") # We are more lenient for assumed real world compatibility purposes. # We always set the Content-Length header for these methods because some # servers will otherwise respond with a 411 _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'} def _encode(data, name='data'): """Call data.encode("latin-1") but show a better error message.""" try: return data.encode("latin-1") except UnicodeEncodeError as err: raise UnicodeEncodeError( err.encoding, err.object, err.start, err.end, "%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') " "if you want to send it encoded in UTF-8." % (name.title(), data[err.start:err.end], name)) from None class HTTPMessage(email.message.Message): # XXX The only usage of this method is in # http.server.CGIHTTPRequestHandler. Maybe move the code there so # that it doesn't need to be part of the public API. The API has # never been defined so this could cause backwards compatibility # issues. def getallmatchingheaders(self, name): """Find all header lines matching a given header name. Look through the list of headers and find all lines matching a given header name (and their continuation lines). A list of the lines is returned, without interpretation. If the header does not occur, an empty list is returned. If the header occurs multiple times, all occurrences are returned. Case is not important in the header name. """ name = name.lower() + ':' n = len(name) lst = [] hit = 0 for line in self.keys(): if line[:n].lower() == name: hit = 1 elif not line[:1].isspace(): hit = 0 if hit: lst.append(line) return lst def parse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes from the stream, bytes which we later need to read as bytes. So we read the correct bytes here, as bytes, for email Parser to parse. """ headers = [] while True: line = fp.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise LineTooLong("header line") headers.append(line) if len(headers) > _MAXHEADERS: raise HTTPException("got more than %d headers" % _MAXHEADERS) if line in (b'\r\n', b'\n', b''): break hstring = b''.join(headers).decode('iso-8859-1') return email.parser.Parser(_class=_class).parsestr(hstring) class HTTPResponse(io.BufferedIOBase): # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details. # The bytes from the socket object are iso-8859-1 strings. # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded # text following RFC 2047. The basic status line parsing only # accepts iso-8859-1. def __init__(self, sock, debuglevel=0, method=None, url=None): # If the response includes a content-length header, we need to # make sure that the client doesn't read more than the # specified number of bytes. If it does, it will block until # the server times out and closes the connection. This will # happen if a self.fp.read() is done (without a size) whether # self.fp is buffered or not. So, no self.fp.read() by # clients unless they know what they are doing. self.fp = sock.makefile("rb") self.debuglevel = debuglevel self._method = method # The HTTPResponse object is returned via urllib. The clients # of http and urllib expect different attributes for the # headers. headers is used here and supports urllib. msg is # provided as a backwards compatibility layer for http # clients. self.headers = self.msg = None # from the Status-Line of the response self.version = _UNKNOWN # HTTP-Version self.status = _UNKNOWN # Status-Code self.reason = _UNKNOWN # Reason-Phrase self.chunked = _UNKNOWN # is "chunked" being used? self.chunk_left = _UNKNOWN # bytes left to read in current chunk self.length = _UNKNOWN # number of bytes left in response self.will_close = _UNKNOWN # conn will close at end of response def _read_status(self): line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") if len(line) > _MAXLINE: raise LineTooLong("status line") if self.debuglevel > 0: print("reply:", repr(line)) if not line: # Presumably, the server closed the connection before # sending a valid response. raise RemoteDisconnected("Remote end closed connection without" " response") try: version, status, reason = line.split(None, 2) except ValueError: try: version, status = line.split(None, 1) reason = "" except ValueError: # empty version will cause next test to fail. version = "" if not version.startswith("HTTP/"): self._close_conn() raise BadStatusLine(line) # The status code is a three-digit number try: status = int(status) if status < 100 or status > 999: raise BadStatusLine(line) except ValueError: raise BadStatusLine(line) return version, status, reason def begin(self): if self.headers is not None: # we've already started reading the response return # read until we get a non-100 response while True: version, status, reason = self._read_status() if status != CONTINUE: break # skip the header from the 100 response while True: skip = self.fp.readline(_MAXLINE + 1) if len(skip) > _MAXLINE: raise LineTooLong("header line") skip = skip.strip() if not skip: break if self.debuglevel > 0: print("header:", skip) self.code = self.status = status self.reason = reason.strip() if version in ("HTTP/1.0", "HTTP/0.9"): # Some servers might still return "0.9", treat it as 1.0 anyway self.version = 10 elif version.startswith("HTTP/1."): self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1 else: raise UnknownProtocol(version) self.headers = self.msg = parse_headers(self.fp) if self.debuglevel > 0: for hdr, val in self.headers.items(): print("header:", hdr + ":", val) # are we using the chunked-style of transfer encoding? tr_enc = self.headers.get("transfer-encoding") if tr_enc and tr_enc.lower() == "chunked": self.chunked = True self.chunk_left = None else: self.chunked = False # will the connection close at the end of the response? self.will_close = self._check_close() # do we have a Content-Length? # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked" self.length = None length = self.headers.get("content-length") # are we using the chunked-style of transfer encoding? tr_enc = self.headers.get("transfer-encoding") if length and not self.chunked: try: self.length = int(length) except ValueError: self.length = None else: if self.length < 0: # ignore nonsensical negative lengths self.length = None else: self.length = None # does the body have a fixed length? (of zero) if (status == NO_CONTENT or status == NOT_MODIFIED or 100 <= status < 200 or # 1xx codes self._method == "HEAD"): self.length = 0 # if the connection remains open, and we aren't using chunked, and # a content-length was not provided, then assume that the connection # WILL close. if (not self.will_close and not self.chunked and self.length is None): self.will_close = True def _check_close(self): conn = self.headers.get("connection") if self.version == 11: # An HTTP/1.1 proxy is assumed to stay open unless # explicitly closed. if conn and "close" in conn.lower(): return True return False # Some HTTP/1.0 implementations have support for persistent # connections, using rules different than HTTP/1.1. # For older HTTP, Keep-Alive indicates persistent connection. if self.headers.get("keep-alive"): return False # At least Akamai returns a "Connection: Keep-Alive" header, # which was supposed to be sent by the client. if conn and "keep-alive" in conn.lower(): return False # Proxy-Connection is a netscape hack. pconn = self.headers.get("proxy-connection") if pconn and "keep-alive" in pconn.lower(): return False # otherwise, assume it will close return True def _close_conn(self): fp = self.fp self.fp = None fp.close() def close(self): try: super().close() # set "closed" flag finally: if self.fp: self._close_conn() # These implementations are for the benefit of io.BufferedReader. # XXX This class should probably be revised to act more like # the "raw stream" that BufferedReader expects. def flush(self): super().flush() if self.fp: self.fp.flush() def readable(self): """Always returns True""" return True # End of "raw stream" methods def isclosed(self): """True if the connection is closed.""" # NOTE: it is possible that we will not ever call self.close(). This # case occurs when will_close is TRUE, length is None, and we # read up to the last byte, but NOT past it. # # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be # called, meaning self.isclosed() is meaningful. return self.fp is None def read(self, amt=None): if self.fp is None: return b"" if self._method == "HEAD": self._close_conn() return b"" if amt is not None: # Amount is given, implement using readinto b = bytearray(amt) n = self.readinto(b) return memoryview(b)[:n].tobytes() else: # Amount is not given (unbounded read) so we must check self.length # and self.chunked if self.chunked: return self._readall_chunked() if self.length is None: s = self.fp.read() else: try: s = self._safe_read(self.length) except IncompleteRead: self._close_conn() raise self.length = 0 self._close_conn() # we read everything return s def readinto(self, b): """Read up to len(b) bytes into bytearray b and return the number of bytes read. """ if self.fp is None: return 0 if self._method == "HEAD": self._close_conn() return 0 if self.chunked: return self._readinto_chunked(b) if self.length is not None: if len(b) > self.length: # clip the read to the "end of response" b = memoryview(b)[0:self.length] # we do not use _safe_read() here because this may be a .will_close # connection, and the user is reading more bytes than will be provided # (for example, reading in 1k chunks) n = self.fp.readinto(b) if not n and b: # Ideally, we would raise IncompleteRead if the content-length # wasn't satisfied, but it might break compatibility. self._close_conn() elif self.length is not None: self.length -= n if not self.length: self._close_conn() return n def _read_next_chunk_size(self): # Read the next chunk size from the file line = self.fp.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise LineTooLong("chunk size") i = line.find(b";") if i >= 0: line = line[:i] # strip chunk-extensions try: return int(line, 16) except ValueError: # close the connection as protocol synchronisation is # probably lost self._close_conn() raise def _read_and_discard_trailer(self): # read and discard trailer up to the CRLF terminator ### note: we shouldn't have any trailers! while True: line = self.fp.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise LineTooLong("trailer line") if not line: # a vanishingly small number of sites EOF without # sending the trailer break if line in (b'\r\n', b'\n', b''): break def _get_chunk_left(self): # return self.chunk_left, reading a new chunk if necessary. # chunk_left == 0: at the end of the current chunk, need to close it # chunk_left == None: No current chunk, should read next. # This function returns non-zero or None if the last chunk has # been read. chunk_left = self.chunk_left if not chunk_left: # Can be 0 or None if chunk_left is not None: # We are at the end of chunk, discard chunk end self._safe_read(2) # toss the CRLF at the end of the chunk try: chunk_left = self._read_next_chunk_size() except ValueError: raise IncompleteRead(b'') if chunk_left == 0: # last chunk: 1*("0") [ chunk-extension ] CRLF self._read_and_discard_trailer() # we read everything; close the "file" self._close_conn() chunk_left = None self.chunk_left = chunk_left return chunk_left def _readall_chunked(self): assert self.chunked != _UNKNOWN value = [] try: while True: chunk_left = self._get_chunk_left() if chunk_left is None: break value.append(self._safe_read(chunk_left)) self.chunk_left = 0 return b''.join(value) except IncompleteRead: raise IncompleteRead(b''.join(value)) def _readinto_chunked(self, b): assert self.chunked != _UNKNOWN total_bytes = 0 mvb = memoryview(b) try: while True: chunk_left = self._get_chunk_left() if chunk_left is None: return total_bytes if len(mvb) <= chunk_left: n = self._safe_readinto(mvb) self.chunk_left = chunk_left - n return total_bytes + n temp_mvb = mvb[:chunk_left] n = self._safe_readinto(temp_mvb) mvb = mvb[n:] total_bytes += n self.chunk_left = 0 except IncompleteRead: raise IncompleteRead(bytes(b[0:total_bytes])) def _safe_read(self, amt): """Read the number of bytes requested, compensating for partial reads. Normally, we have a blocking socket, but a read() can be interrupted by a signal (resulting in a partial read). Note that we cannot distinguish between EOF and an interrupt when zero bytes have been read. IncompleteRead() will be raised in this situation. This function should be used when <amt> bytes "should" be present for reading. If the bytes are truly not available (due to EOF), then the IncompleteRead exception can be used to detect the problem. """ s = [] while amt > 0: chunk = self.fp.read(min(amt, MAXAMOUNT)) if not chunk: raise IncompleteRead(b''.join(s), amt) s.append(chunk) amt -= len(chunk) return b"".join(s) def _safe_readinto(self, b): """Same as _safe_read, but for reading into a buffer.""" total_bytes = 0 mvb = memoryview(b) while total_bytes < len(b): if MAXAMOUNT < len(mvb): temp_mvb = mvb[0:MAXAMOUNT] n = self.fp.readinto(temp_mvb) else: n = self.fp.readinto(mvb) if not n: raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b)) mvb = mvb[n:] total_bytes += n return total_bytes def read1(self, n=-1): """Read with at most one underlying system call. If at least one byte is buffered, return that instead. """ if self.fp is None or self._method == "HEAD": return b"" if self.chunked: return self._read1_chunked(n) if self.length is not None and (n < 0 or n > self.length): n = self.length result = self.fp.read1(n) if not result and n: self._close_conn() elif self.length is not None: self.length -= len(result) return result def peek(self, n=-1): # Having this enables IOBase.readline() to read more than one # byte at a time if self.fp is None or self._method == "HEAD": return b"" if self.chunked: return self._peek_chunked(n) return self.fp.peek(n) def readline(self, limit=-1): if self.fp is None or self._method == "HEAD": return b"" if self.chunked: # Fallback to IOBase readline which uses peek() and read() return super().readline(limit) if self.length is not None and (limit < 0 or limit > self.length): limit = self.length result = self.fp.readline(limit) if not result and limit: self._close_conn() elif self.length is not None: self.length -= len(result) return result def _read1_chunked(self, n): # Strictly speaking, _get_chunk_left() may cause more than one read, # but that is ok, since that is to satisfy the chunked protocol. chunk_left = self._get_chunk_left() if chunk_left is None or n == 0: return b'' if not (0 <= n <= chunk_left): n = chunk_left # if n is negative or larger than chunk_left read = self.fp.read1(n) self.chunk_left -= len(read) if not read: raise IncompleteRead(b"") return read def _peek_chunked(self, n): # Strictly speaking, _get_chunk_left() may cause more than one read, # but that is ok, since that is to satisfy the chunked protocol. try: chunk_left = self._get_chunk_left() except IncompleteRead: return b'' # peek doesn't worry about protocol if chunk_left is None: return b'' # eof # peek is allowed to return more than requested. Just request the # entire chunk, and truncate what we get. return self.fp.peek(chunk_left)[:chunk_left] def fileno(self): return self.fp.fileno() def getheader(self, name, default=None): '''Returns the value of the header matching *name*. If there are multiple matching headers, the values are combined into a single string separated by commas and spaces. If no matching header is found, returns *default* or None if the *default* is not specified. If the headers are unknown, raises http.client.ResponseNotReady. ''' if self.headers is None: raise ResponseNotReady() headers = self.headers.get_all(name) or default if isinstance(headers, str) or not hasattr(headers, '__iter__'): return headers else: return ', '.join(headers) def getheaders(self): """Return list of (header, value) tuples.""" if self.headers is None: raise ResponseNotReady() return list(self.headers.items()) # We override IOBase.__iter__ so that it doesn't check for closed-ness def __iter__(self): return self # For compatibility with old-style urllib responses. def info(self): '''Returns an instance of the class mimetools.Message containing meta-information associated with the URL. When the method is HTTP, these headers are those returned by the server at the head of the retrieved HTML page (including Content-Length and Content-Type). When the method is FTP, a Content-Length header will be present if (as is now usual) the server passed back a file length in response to the FTP retrieval request. A Content-Type header will be present if the MIME type can be guessed. When the method is local-file, returned headers will include a Date representing the file's last-modified time, a Content-Length giving file size, and a Content-Type containing a guess at the file's type. See also the description of the mimetools module. ''' return self.headers def geturl(self): '''Return the real URL of the page. In some cases, the HTTP server redirects a client to another URL. The urlopen() function handles this transparently, but in some cases the caller needs to know which URL the client was redirected to. The geturl() method can be used to get at this redirected URL. ''' return self.url def getcode(self): '''Return the HTTP status code that was sent with the response, or None if the URL is not an HTTP URL. ''' return self.status class HTTPConnection: _http_vsn = 11 _http_vsn_str = 'HTTP/1.1' response_class = HTTPResponse default_port = HTTP_PORT auto_open = 1 debuglevel = 0 @staticmethod def _is_textIO(stream): """Test whether a file-like object is a text or a binary stream. """ return isinstance(stream, io.TextIOBase) @staticmethod def _get_content_length(body, method): """Get the content-length based on the body. If the body is None, we set Content-Length: 0 for methods that expect a body (RFC 7230, Section 3.3.2). We also set the Content-Length for any method if the body is a str or bytes-like object and not a file. """ if body is None: # do an explicit check for not None here to distinguish # between unset and set but empty if method.upper() in _METHODS_EXPECTING_BODY: return 0 else: return None if hasattr(body, 'read'): # file-like object. return None try: # does it implement the buffer protocol (bytes, bytearray, array)? mv = memoryview(body) return mv.nbytes except TypeError: pass if isinstance(body, str): return len(body) return None def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, blocksize=8192): self.timeout = timeout self.source_address = source_address self.blocksize = blocksize self.sock = None self._buffer = [] self.__response = None self.__state = _CS_IDLE self._method = None self._tunnel_host = None self._tunnel_port = None self._tunnel_headers = {} (self.host, self.port) = self._get_hostport(host, port) # This is stored as an instance variable to allow unit # tests to replace it with a suitable mockup self._create_connection = socket.create_connection def set_tunnel(self, host, port=None, headers=None): """Set up host and port for HTTP CONNECT tunnelling. In a connection that uses HTTP CONNECT tunneling, the host passed to the constructor is used as a proxy server that relays all communication to the endpoint passed to `set_tunnel`. This done by sending an HTTP CONNECT request to the proxy server when the connection is established. This method must be called before the HTML connection has been established. The headers argument should be a mapping of extra HTTP headers to send with the CONNECT request. """ if self.sock: raise RuntimeError("Can't set up tunnel for established connection") self._tunnel_host, self._tunnel_port = self._get_hostport(host, port) if headers: self._tunnel_headers = headers else: self._tunnel_headers.clear() def _get_hostport(self, host, port): if port is None: i = host.rfind(':') j = host.rfind(']') # ipv6 addresses have [...] if i > j: try: port = int(host[i+1:]) except ValueError: if host[i+1:] == "": # http://foo.com:/ == http://foo.com/ port = self.default_port else: raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) host = host[:i] else: port = self.default_port if host and host[0] == '[' and host[-1] == ']': host = host[1:-1] return (host, port) def set_debuglevel(self, level): self.debuglevel = level def _tunnel(self): connect_str = "CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host, self._tunnel_port) connect_bytes = connect_str.encode("ascii") self.send(connect_bytes) for header, value in self._tunnel_headers.items(): header_str = "%s: %s\r\n" % (header, value) header_bytes = header_str.encode("latin-1") self.send(header_bytes) self.send(b'\r\n')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/cookiejar.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/cookiejar.py
r"""HTTP cookie handling for web clients. This module has (now fairly distant) origins in Gisle Aas' Perl module HTTP::Cookies, from the libwww-perl library. Docstrings, comments and debug strings in this code refer to the attributes of the HTTP cookie system as cookie-attributes, to distinguish them clearly from Python attributes. Class diagram (note that BSDDBCookieJar and the MSIE* classes are not distributed with the Python standard library, but are available from http://wwwsearch.sf.net/): CookieJar____ / \ \ FileCookieJar \ \ / | \ \ \ MozillaCookieJar | LWPCookieJar \ \ | | \ | ---MSIEBase | \ | / | | \ | / MSIEDBCookieJar BSDDBCookieJar |/ MSIECookieJar """ __all__ = ['Cookie', 'CookieJar', 'CookiePolicy', 'DefaultCookiePolicy', 'FileCookieJar', 'LWPCookieJar', 'LoadError', 'MozillaCookieJar'] import copy import datetime import re import time import urllib.parse, urllib.request import threading as _threading import http.client # only for the default HTTP port from calendar import timegm debug = False # set to True to enable debugging via the logging module logger = None def _debug(*args): if not debug: return global logger if not logger: import logging logger = logging.getLogger("http.cookiejar") return logger.debug(*args) DEFAULT_HTTP_PORT = str(http.client.HTTP_PORT) MISSING_FILENAME_TEXT = ("a filename was not supplied (nor was the CookieJar " "instance initialised with one)") def _warn_unhandled_exception(): # There are a few catch-all except: statements in this module, for # catching input that's bad in unexpected ways. Warn if any # exceptions are caught there. import io, warnings, traceback f = io.StringIO() traceback.print_exc(None, f) msg = f.getvalue() warnings.warn("http.cookiejar bug!\n%s" % msg, stacklevel=2) # Date/time conversion # ----------------------------------------------------------------------------- EPOCH_YEAR = 1970 def _timegm(tt): year, month, mday, hour, min, sec = tt[:6] if ((year >= EPOCH_YEAR) and (1 <= month <= 12) and (1 <= mday <= 31) and (0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)): return timegm(tt) else: return None DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] MONTHS_LOWER = [] for month in MONTHS: MONTHS_LOWER.append(month.lower()) def time2isoz(t=None): """Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ", representing Universal Time (UTC, aka GMT). An example of this format is: 1994-11-24 08:49:37Z """ if t is None: dt = datetime.datetime.utcnow() else: dt = datetime.datetime.utcfromtimestamp(t) return "%04d-%02d-%02d %02d:%02d:%02dZ" % ( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) def time2netscape(t=None): """Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like this: Wed, DD-Mon-YYYY HH:MM:SS GMT """ if t is None: dt = datetime.datetime.utcnow() else: dt = datetime.datetime.utcfromtimestamp(t) return "%s, %02d-%s-%04d %02d:%02d:%02d GMT" % ( DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1], dt.year, dt.hour, dt.minute, dt.second) UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None} TIMEZONE_RE = re.compile(r"^([-+])?(\d\d?):?(\d\d)?$", re.ASCII) def offset_from_tz_string(tz): offset = None if tz in UTC_ZONES: offset = 0 else: m = TIMEZONE_RE.search(tz) if m: offset = 3600 * int(m.group(2)) if m.group(3): offset = offset + 60 * int(m.group(3)) if m.group(1) == '-': offset = -offset return offset def _str2time(day, mon, yr, hr, min, sec, tz): yr = int(yr) if yr > datetime.MAXYEAR: return None # translate month name to number # month numbers start with 1 (January) try: mon = MONTHS_LOWER.index(mon.lower())+1 except ValueError: # maybe it's already a number try: imon = int(mon) except ValueError: return None if 1 <= imon <= 12: mon = imon else: return None # make sure clock elements are defined if hr is None: hr = 0 if min is None: min = 0 if sec is None: sec = 0 day = int(day) hr = int(hr) min = int(min) sec = int(sec) if yr < 1000: # find "obvious" year cur_yr = time.localtime(time.time())[0] m = cur_yr % 100 tmp = yr yr = yr + cur_yr - m m = m - tmp if abs(m) > 50: if m > 0: yr = yr + 100 else: yr = yr - 100 # convert UTC time tuple to seconds since epoch (not timezone-adjusted) t = _timegm((yr, mon, day, hr, min, sec, tz)) if t is not None: # adjust time using timezone string, to get absolute time since epoch if tz is None: tz = "UTC" tz = tz.upper() offset = offset_from_tz_string(tz) if offset is None: return None t = t - offset return t STRICT_DATE_RE = re.compile( r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) " r"(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$", re.ASCII) WEEKDAY_RE = re.compile( r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I | re.ASCII) LOOSE_HTTP_DATE_RE = re.compile( r"""^ (\d\d?) # day (?:\s+|[-\/]) (\w+) # month (?:\s+|[-\/]) (\d+) # year (?: (?:\s+|:) # separator before clock (\d\d?):(\d\d) # hour:min (?::(\d\d))? # optional seconds )? # optional clock \s* (?: ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+) # timezone \s* )? (?: \(\w+\) # ASCII representation of timezone in parens. \s* )?$""", re.X | re.ASCII) def http2time(text): """Returns time in seconds since epoch of time represented by a string. Return value is an integer. None is returned if the format of str is unrecognized, the time is outside the representable range, or the timezone string is not recognized. If the string contains no timezone, UTC is assumed. The timezone in the string may be numerical (like "-0800" or "+0100") or a string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the timezone strings equivalent to UTC (zero offset) are known to the function. The function loosely parses the following formats: Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday) 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday) 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday) The parser ignores leading and trailing whitespace. The time may be absent. If the year is given with only 2 digits, the function will select the century that makes the year closest to the current date. """ # fast exit for strictly conforming string m = STRICT_DATE_RE.search(text) if m: g = m.groups() mon = MONTHS_LOWER.index(g[1].lower()) + 1 tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5])) return _timegm(tt) # No, we need some messy parsing... # clean up text = text.lstrip() text = WEEKDAY_RE.sub("", text, 1) # Useless weekday # tz is time zone specifier string day, mon, yr, hr, min, sec, tz = [None]*7 # loose regexp parse m = LOOSE_HTTP_DATE_RE.search(text) if m is not None: day, mon, yr, hr, min, sec, tz = m.groups() else: return None # bad format return _str2time(day, mon, yr, hr, min, sec, tz) ISO_DATE_RE = re.compile( r"""^ (\d{4}) # year [-\/]? (\d\d?) # numerical month [-\/]? (\d\d?) # day (?: (?:\s+|[-:Tt]) # separator before clock (\d\d?):?(\d\d) # hour:min (?::?(\d\d(?:\.\d*)?))? # optional seconds (and fractional) )? # optional clock \s* (?: ([-+]?\d\d?:?(:?\d\d)? |Z|z) # timezone (Z is "zero meridian", i.e. GMT) \s* )?$""", re.X | re. ASCII) def iso2time(text): """ As for http2time, but parses the ISO 8601 formats: 1994-02-03 14:15:29 -0100 -- ISO 8601 format 1994-02-03 14:15:29 -- zone is optional 1994-02-03 -- only date 1994-02-03T14:15:29 -- Use T as separator 19940203T141529Z -- ISO 8601 compact format 19940203 -- only date """ # clean up text = text.lstrip() # tz is time zone specifier string day, mon, yr, hr, min, sec, tz = [None]*7 # loose regexp parse m = ISO_DATE_RE.search(text) if m is not None: # XXX there's an extra bit of the timezone I'm ignoring here: is # this the right thing to do? yr, mon, day, hr, min, sec, tz, _ = m.groups() else: return None # bad format return _str2time(day, mon, yr, hr, min, sec, tz) # Header parsing # ----------------------------------------------------------------------------- def unmatched(match): """Return unmatched part of re.Match object.""" start, end = match.span(0) return match.string[:start]+match.string[end:] HEADER_TOKEN_RE = re.compile(r"^\s*([^=\s;,]+)") HEADER_QUOTED_VALUE_RE = re.compile(r"^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"") HEADER_VALUE_RE = re.compile(r"^\s*=\s*([^\s;,]*)") HEADER_ESCAPE_RE = re.compile(r"\\(.)") def split_header_words(header_values): r"""Parse header values into a list of lists containing key,value pairs. The function knows how to deal with ",", ";" and "=" as well as quoted values after "=". A list of space separated tokens are parsed as if they were separated by ";". If the header_values passed as argument contains multiple values, then they are treated as if they were a single value separated by comma ",". This means that this function is useful for parsing header fields that follow this syntax (BNF as from the HTTP/1.1 specification, but we relax the requirement for tokens). headers = #header header = (token | parameter) *( [";"] (token | parameter)) token = 1*<any CHAR except CTLs or separators> separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) qdtext = <any TEXT except <">> quoted-pair = "\" CHAR parameter = attribute "=" value attribute = token value = token | quoted-string Each header is represented by a list of key/value pairs. The value for a simple token (not part of a parameter) is None. Syntactically incorrect headers will not necessarily be parsed as you would want. This is easier to describe with some examples: >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz']) [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]] >>> split_header_words(['text/html; charset="iso-8859-1"']) [[('text/html', None), ('charset', 'iso-8859-1')]] >>> split_header_words([r'Basic realm="\"foo\bar\""']) [[('Basic', None), ('realm', '"foobar"')]] """ assert not isinstance(header_values, str) result = [] for text in header_values: orig_text = text pairs = [] while text: m = HEADER_TOKEN_RE.search(text) if m: text = unmatched(m) name = m.group(1) m = HEADER_QUOTED_VALUE_RE.search(text) if m: # quoted value text = unmatched(m) value = m.group(1) value = HEADER_ESCAPE_RE.sub(r"\1", value) else: m = HEADER_VALUE_RE.search(text) if m: # unquoted value text = unmatched(m) value = m.group(1) value = value.rstrip() else: # no value, a lone token value = None pairs.append((name, value)) elif text.lstrip().startswith(","): # concatenated headers, as per RFC 2616 section 4.2 text = text.lstrip()[1:] if pairs: result.append(pairs) pairs = [] else: # skip junk non_junk, nr_junk_chars = re.subn(r"^[=\s;]*", "", text) assert nr_junk_chars > 0, ( "split_header_words bug: '%s', '%s', %s" % (orig_text, text, pairs)) text = non_junk if pairs: result.append(pairs) return result HEADER_JOIN_ESCAPE_RE = re.compile(r"([\"\\])") def join_header_words(lists): """Do the inverse (almost) of the conversion done by split_header_words. Takes a list of lists of (key, value) pairs and produces a single header value. Attribute values are quoted if needed. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859-1")]]) 'text/plain; charset="iso-8859-1"' >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859-1")]]) 'text/plain, charset="iso-8859-1"' """ headers = [] for pairs in lists: attr = [] for k, v in pairs: if v is not None: if not re.search(r"^\w+$", v): v = HEADER_JOIN_ESCAPE_RE.sub(r"\\\1", v) # escape " and \ v = '"%s"' % v k = "%s=%s" % (k, v) attr.append(k) if attr: headers.append("; ".join(attr)) return ", ".join(headers) def strip_quotes(text): if text.startswith('"'): text = text[1:] if text.endswith('"'): text = text[:-1] return text def parse_ns_headers(ns_headers): """Ad-hoc parser for Netscape protocol cookie-attributes. The old Netscape cookie format for Set-Cookie can for instance contain an unquoted "," in the expires field, so we have to use this ad-hoc parser instead of split_header_words. XXX This may not make the best possible effort to parse all the crap that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient parser is probably better, so could do worse than following that if this ever gives any trouble. Currently, this is also used for parsing RFC 2109 cookies. """ known_attrs = ("expires", "domain", "path", "secure", # RFC 2109 attrs (may turn up in Netscape cookies, too) "version", "port", "max-age") result = [] for ns_header in ns_headers: pairs = [] version_set = False # XXX: The following does not strictly adhere to RFCs in that empty # names and values are legal (the former will only appear once and will # be overwritten if multiple occurrences are present). This is # mostly to deal with backwards compatibility. for ii, param in enumerate(ns_header.split(';')): param = param.strip() key, sep, val = param.partition('=') key = key.strip() if not key: if ii == 0: break else: continue # allow for a distinction between present and empty and missing # altogether val = val.strip() if sep else None if ii != 0: lc = key.lower() if lc in known_attrs: key = lc if key == "version": # This is an RFC 2109 cookie. if val is not None: val = strip_quotes(val) version_set = True elif key == "expires": # convert expires date to seconds since epoch if val is not None: val = http2time(strip_quotes(val)) # None if invalid pairs.append((key, val)) if pairs: if not version_set: pairs.append(("version", "0")) result.append(pairs) return result IPV4_RE = re.compile(r"\.\d+$", re.ASCII) def is_HDN(text): """Return True if text is a host domain name.""" # XXX # This may well be wrong. Which RFC is HDN defined in, if any (for # the purposes of RFC 2965)? # For the current implementation, what about IPv6? Remember to look # at other uses of IPV4_RE also, if change this. if IPV4_RE.search(text): return False if text == "": return False if text[0] == "." or text[-1] == ".": return False return True def domain_match(A, B): """Return True if domain A domain-matches domain B, according to RFC 2965. A and B may be host domain names or IP addresses. RFC 2965, section 1: Host names can be specified either as an IP address or a HDN string. Sometimes we compare one host name with another. (Such comparisons SHALL be case-insensitive.) Host A's name domain-matches host B's if * their host name strings string-compare equal; or * A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.) Note that domain-match is not a commutative operation: a.b.c.com domain-matches .c.com, but not the reverse. """ # Note that, if A or B are IP addresses, the only relevant part of the # definition of the domain-match algorithm is the direct string-compare. A = A.lower() B = B.lower() if A == B: return True if not is_HDN(A): return False i = A.rfind(B) if i == -1 or i == 0: # A does not have form NB, or N is the empty string return False if not B.startswith("."): return False if not is_HDN(B[1:]): return False return True def liberal_is_HDN(text): """Return True if text is a sort-of-like a host domain name. For accepting/blocking domains. """ if IPV4_RE.search(text): return False return True def user_domain_match(A, B): """For blocking/accepting domains. A and B may be host domain names or IP addresses. """ A = A.lower() B = B.lower() if not (liberal_is_HDN(A) and liberal_is_HDN(B)): if A == B: # equal IP addresses return True return False initial_dot = B.startswith(".") if initial_dot and A.endswith(B): return True if not initial_dot and A == B: return True return False cut_port_re = re.compile(r":\d+$", re.ASCII) def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() host = urllib.parse.urlparse(url)[1] if host == "": host = request.get_header("Host", "") # remove port, if present host = cut_port_re.sub("", host, 1) return host.lower() def eff_request_host(request): """Return a tuple (request-host, effective request-host name). As defined by RFC 2965, except both are lowercased. """ erhn = req_host = request_host(request) if req_host.find(".") == -1 and not IPV4_RE.search(req_host): erhn = req_host + ".local" return req_host, erhn def request_path(request): """Path component of request-URI, as defined by RFC 2965.""" url = request.get_full_url() parts = urllib.parse.urlsplit(url) path = escape_path(parts.path) if not path.startswith("/"): # fix bad RFC 2396 absoluteURI path = "/" + path return path def request_port(request): host = request.host i = host.find(':') if i >= 0: port = host[i+1:] try: int(port) except ValueError: _debug("nonnumeric port: '%s'", port) return None else: port = DEFAULT_HTTP_PORT return port # Characters in addition to A-Z, a-z, 0-9, '_', '.', and '-' that don't # need to be escaped to form a valid HTTP URL (RFCs 2396 and 1738). HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()" ESCAPED_CHAR_RE = re.compile(r"%([0-9a-fA-F][0-9a-fA-F])") def uppercase_escaped_char(match): return "%%%s" % match.group(1).upper() def escape_path(path): """Escape any invalid characters in HTTP URL, and uppercase all escapes.""" # There's no knowing what character encoding was used to create URLs # containing %-escapes, but since we have to pick one to escape invalid # path characters, we pick UTF-8, as recommended in the HTML 4.0 # specification: # http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1 # And here, kind of: draft-fielding-uri-rfc2396bis-03 # (And in draft IRI specification: draft-duerst-iri-05) # (And here, for new URI schemes: RFC 2718) path = urllib.parse.quote(path, HTTP_PATH_SAFE) path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path) return path def reach(h): """Return reach of host h, as defined by RFC 2965, section 1. The reach R of a host name H is defined as follows: * If - H is the host domain name of a host; and, - H has the form A.B; and - A has no embedded (that is, interior) dots; and - B has at least one embedded dot, or B is the string "local". then the reach of H is .B. * Otherwise, the reach of H is H. >>> reach("www.acme.com") '.acme.com' >>> reach("acme.com") 'acme.com' >>> reach("acme.local") '.local' """ i = h.find(".") if i >= 0: #a = h[:i] # this line is only here to show what a is b = h[i+1:] i = b.find(".") if is_HDN(h) and (i >= 0 or b == "local"): return "."+b return h def is_third_party(request): """ RFC 2965, section 3.3.6: An unverifiable transaction is to a third-party host if its request- host U does not domain-match the reach R of the request-host O in the origin transaction. """ req_host = request_host(request) if not domain_match(req_host, reach(request.origin_req_host)): return True else: return False class Cookie: """HTTP Cookie. This class represents both Netscape and RFC 2965 cookies. This is deliberately a very simple class. It just holds attributes. It's possible to construct Cookie instances that don't comply with the cookie standards. CookieJar.make_cookies is the factory function for Cookie objects -- it deals with cookie parsing, supplying defaults, and normalising to the representation used in this class. CookiePolicy is responsible for checking them to see whether they should be accepted from and returned to the server. Note that the port may be present in the headers, but unspecified ("Port" rather than"Port=80", for example); if this is the case, port is None. """ def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109=False, ): if version is not None: version = int(version) if expires is not None: expires = int(float(expires)) if port is None and port_specified is True: raise ValueError("if port is None, port_specified must be false") self.version = version self.name = name self.value = value self.port = port self.port_specified = port_specified # normalise case, as per RFC 2965 section 3.3.3 self.domain = domain.lower() self.domain_specified = domain_specified # Sigh. We need to know whether the domain given in the # cookie-attribute had an initial dot, in order to follow RFC 2965 # (as clarified in draft errata). Needed for the returned $Domain # value. self.domain_initial_dot = domain_initial_dot self.path = path self.path_specified = path_specified self.secure = secure self.expires = expires self.discard = discard self.comment = comment self.comment_url = comment_url self.rfc2109 = rfc2109 self._rest = copy.copy(rest) def has_nonstandard_attr(self, name): return name in self._rest def get_nonstandard_attr(self, name, default=None): return self._rest.get(name, default) def set_nonstandard_attr(self, name, value): self._rest[name] = value def is_expired(self, now=None): if now is None: now = time.time() if (self.expires is not None) and (self.expires <= now): return True return False def __str__(self): if self.port is None: p = "" else: p = ":"+self.port limit = self.domain + p + self.path if self.value is not None: namevalue = "%s=%s" % (self.name, self.value) else: namevalue = self.name return "<Cookie %s for %s>" % (namevalue, limit) def __repr__(self): args = [] for name in ("version", "name", "value", "port", "port_specified", "domain", "domain_specified", "domain_initial_dot", "path", "path_specified", "secure", "expires", "discard", "comment", "comment_url", ): attr = getattr(self, name) args.append("%s=%s" % (name, repr(attr))) args.append("rest=%s" % repr(self._rest)) args.append("rfc2109=%s" % repr(self.rfc2109)) return "%s(%s)" % (self.__class__.__name__, ", ".join(args)) class CookiePolicy: """Defines which cookies get accepted from and returned to server. May also modify cookies, though this is probably a bad idea. The subclass DefaultCookiePolicy defines the standard rules for Netscape and RFC 2965 cookies -- override that if you want a customized policy. """ def set_ok(self, cookie, request): """Return true if (and only if) cookie should be accepted from server. Currently, pre-expired cookies never get this far -- the CookieJar class deletes such cookies itself. """ raise NotImplementedError() def return_ok(self, cookie, request): """Return true if (and only if) cookie should be returned to server.""" raise NotImplementedError() def domain_return_ok(self, domain, request): """Return false if cookies should not be returned, given cookie domain. """ return True def path_return_ok(self, path, request): """Return false if cookies should not be returned, given cookie path. """ return True class DefaultCookiePolicy(CookiePolicy): """Implements the standard rules for accepting and returning cookies.""" DomainStrictNoDots = 1 DomainStrictNonDomain = 2 DomainRFC2965Match = 4 DomainLiberal = 0 DomainStrict = DomainStrictNoDots|DomainStrictNonDomain def __init__(self, blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False, ): """Constructor arguments should be passed as keyword arguments only.""" self.netscape = netscape self.rfc2965 = rfc2965 self.rfc2109_as_netscape = rfc2109_as_netscape self.hide_cookie2 = hide_cookie2 self.strict_domain = strict_domain self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable self.strict_ns_unverifiable = strict_ns_unverifiable self.strict_ns_domain = strict_ns_domain self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar self.strict_ns_set_path = strict_ns_set_path if blocked_domains is not None: self._blocked_domains = tuple(blocked_domains) else: self._blocked_domains = () if allowed_domains is not None: allowed_domains = tuple(allowed_domains) self._allowed_domains = allowed_domains def blocked_domains(self): """Return the sequence of blocked domains (as a tuple).""" return self._blocked_domains def set_blocked_domains(self, blocked_domains): """Set the sequence of blocked domains.""" self._blocked_domains = tuple(blocked_domains) def is_blocked(self, domain): for blocked_domain in self._blocked_domains: if user_domain_match(domain, blocked_domain): return True return False def allowed_domains(self): """Return None, or the sequence of allowed domains (as a tuple).""" return self._allowed_domains def set_allowed_domains(self, allowed_domains): """Set the sequence of allowed domains, or None.""" if allowed_domains is not None: allowed_domains = tuple(allowed_domains) self._allowed_domains = allowed_domains def is_not_allowed(self, domain): if self._allowed_domains is None: return False for allowed_domain in self._allowed_domains: if user_domain_match(domain, allowed_domain): return False return True def set_ok(self, cookie, request): """ If you override .set_ok(), be sure to call this method. If it returns false, so should your subclass (assuming your subclass wants to be more strict about which cookies to accept). """ _debug(" - checking cookie %s=%s", cookie.name, cookie.value) assert cookie.name is not None for n in "version", "verifiability", "name", "path", "domain", "port": fn_name = "set_ok_"+n fn = getattr(self, fn_name) if not fn(cookie, request): return False return True def set_ok_version(self, cookie, request): if cookie.version is None: # Version is always set to 0 by parse_ns_headers if it's a Netscape # cookie, so this must be an invalid RFC 2965 cookie. _debug(" Set-Cookie2 without version attribute (%s=%s)", cookie.name, cookie.value) return False if cookie.version > 0 and not self.rfc2965: _debug(" RFC 2965 cookies are switched off") return False elif cookie.version == 0 and not self.netscape: _debug(" Netscape cookies are switched off") return False return True def set_ok_verifiability(self, cookie, request): if request.unverifiable and is_third_party(request):
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/cookies.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/cookies.py
#### # Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu> # # All Rights Reserved # # Permission to use, copy, modify, and distribute this software # and its documentation for any purpose and without fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Timothy O'Malley not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR # ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # #### # # Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp # by Timothy O'Malley <timo@alum.mit.edu> # # Cookie.py is a Python module for the handling of HTTP # cookies as a Python dictionary. See RFC 2109 for more # information on cookies. # # The original idea to treat Cookies as a dictionary came from # Dave Mitchell (davem@magnet.com) in 1995, when he released the # first version of nscookie.py. # #### r""" Here's a sample session to show how to use this module. At the moment, this is the only documentation. The Basics ---------- Importing is easy... >>> from http import cookies Most of the time you start by creating a cookie. >>> C = cookies.SimpleCookie() Once you've created your Cookie, you can add values just as if it were a dictionary. >>> C = cookies.SimpleCookie() >>> C["fig"] = "newton" >>> C["sugar"] = "wafer" >>> C.output() 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer' Notice that the printable representation of a Cookie is the appropriate format for a Set-Cookie: header. This is the default behavior. You can change the header and printed attributes by using the .output() function >>> C = cookies.SimpleCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" >>> print(C.output(header="Cookie:")) Cookie: rocky=road; Path=/cookie >>> print(C.output(attrs=[], header="Cookie:")) Cookie: rocky=road The load() method of a Cookie extracts cookies from a string. In a CGI script, you would use this method to extract the cookies from the HTTP_COOKIE environment variable. >>> C = cookies.SimpleCookie() >>> C.load("chips=ahoy; vienna=finger") >>> C.output() 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger' The load() method is darn-tootin smart about identifying cookies within a string. Escaped quotation marks, nested semicolons, and other such trickeries do not confuse it. >>> C = cookies.SimpleCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') >>> print(C) Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" Each element of the Cookie also supports all of the RFC 2109 Cookie attributes. Here's an example which sets the Path attribute. >>> C = cookies.SimpleCookie() >>> C["oreo"] = "doublestuff" >>> C["oreo"]["path"] = "/" >>> print(C) Set-Cookie: oreo=doublestuff; Path=/ Each dictionary element has a 'value' attribute, which gives you back the value associated with the key. >>> C = cookies.SimpleCookie() >>> C["twix"] = "none for you" >>> C["twix"].value 'none for you' The SimpleCookie expects that all values should be standard strings. Just to be sure, SimpleCookie invokes the str() builtin to convert the value to a string, when the values are set dictionary-style. >>> C = cookies.SimpleCookie() >>> C["number"] = 7 >>> C["string"] = "seven" >>> C["number"].value '7' >>> C["string"].value 'seven' >>> C.output() 'Set-Cookie: number=7\r\nSet-Cookie: string=seven' Finis. """ # # Import our required modules # import re import string __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] _nulljoin = ''.join _semispacejoin = '; '.join _spacejoin = ' '.join # # Define an exception visible to External modules # class CookieError(Exception): pass # These quoting routines conform to the RFC2109 specification, which in # turn references the character definitions from RFC2068. They provide # a two-way quoting algorithm. Any non-text character is translated # into a 4 character sequence: a forward-slash followed by the # three-digit octal equivalent of the character. Any '\' or '"' is # quoted with a preceding '\' slash. # Because of the way browsers really handle cookies (as opposed to what # the RFC says) we also encode "," and ";". # # These are taken from RFC2068 and RFC2109. # _LegalChars is the list of chars which don't require "'s # _Translator hash-table for fast quoting # _LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:" _UnescapedChars = _LegalChars + ' ()/<=>?@[]{}' _Translator = {n: '\\%03o' % n for n in set(range(256)) - set(map(ord, _UnescapedChars))} _Translator.update({ ord('"'): '\\"', ord('\\'): '\\\\', }) _is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch def _quote(str): r"""Quote a string for use in a cookie header. If the string does not need to be double-quoted, then just return the string. Otherwise, surround the string in doublequotes and quote (with a \) special characters. """ if str is None or _is_legal_key(str): return str else: return '"' + str.translate(_Translator) + '"' _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]") _QuotePatt = re.compile(r"[\\].") def _unquote(str): # If there aren't any doublequotes, # then there can't be any special characters. See RFC 2109. if str is None or len(str) < 2: return str if str[0] != '"' or str[-1] != '"': return str # We have to assume that we must decode this string. # Down to work. # Remove the "s str = str[1:-1] # Check for special sequences. Examples: # \012 --> \n # \" --> " # i = 0 n = len(str) res = [] while 0 <= i < n: o_match = _OctalPatt.search(str, i) q_match = _QuotePatt.search(str, i) if not o_match and not q_match: # Neither matched res.append(str[i:]) break # else: j = k = -1 if o_match: j = o_match.start(0) if q_match: k = q_match.start(0) if q_match and (not o_match or k < j): # QuotePatt matched res.append(str[i:k]) res.append(str[k+1]) i = k + 2 else: # OctalPatt matched res.append(str[i:j]) res.append(chr(int(str[j+1:j+4], 8))) i = j + 4 return _nulljoin(res) # The _getdate() routine is used to set the expiration time in the cookie's HTTP # header. By default, _getdate() returns the current time in the appropriate # "expires" format for a Set-Cookie header. The one optional argument is an # offset from now, in seconds. For example, an offset of -3600 means "one hour # ago". The offset may be a floating point number. # _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] _monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname): from time import gmtime, time now = time() year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \ (weekdayname[wd], day, monthname[month], year, hh, mm, ss) class Morsel(dict): """A class to hold ONE (key, value) pair. In a cookie, each such pair may have several attributes, so this class is used to keep the attributes associated with the appropriate key,value pair. This class also includes a coded_value attribute, which is used to hold the network representation of the value. This is most useful when Python objects are pickled for network transit. """ # RFC 2109 lists these attributes as reserved: # path comment domain # max-age secure version # # For historical reasons, these attributes are also reserved: # expires # # This is an extension from Microsoft: # httponly # # This dictionary provides a mapping from the lowercase # variant on the left to the appropriate traditional # formatting on the right. _reserved = { "expires" : "expires", "path" : "Path", "comment" : "Comment", "domain" : "Domain", "max-age" : "Max-Age", "secure" : "Secure", "httponly" : "HttpOnly", "version" : "Version", } _flags = {'secure', 'httponly'} def __init__(self): # Set defaults self._key = self._value = self._coded_value = None # Set default attributes for key in self._reserved: dict.__setitem__(self, key, "") @property def key(self): return self._key @property def value(self): return self._value @property def coded_value(self): return self._coded_value def __setitem__(self, K, V): K = K.lower() if not K in self._reserved: raise CookieError("Invalid attribute %r" % (K,)) dict.__setitem__(self, K, V) def setdefault(self, key, val=None): key = key.lower() if key not in self._reserved: raise CookieError("Invalid attribute %r" % (key,)) return dict.setdefault(self, key, val) def __eq__(self, morsel): if not isinstance(morsel, Morsel): return NotImplemented return (dict.__eq__(self, morsel) and self._value == morsel._value and self._key == morsel._key and self._coded_value == morsel._coded_value) __ne__ = object.__ne__ def copy(self): morsel = Morsel() dict.update(morsel, self) morsel.__dict__.update(self.__dict__) return morsel def update(self, values): data = {} for key, val in dict(values).items(): key = key.lower() if key not in self._reserved: raise CookieError("Invalid attribute %r" % (key,)) data[key] = val dict.update(self, data) def isReservedKey(self, K): return K.lower() in self._reserved def set(self, key, val, coded_val): if key.lower() in self._reserved: raise CookieError('Attempt to set a reserved key %r' % (key,)) if not _is_legal_key(key): raise CookieError('Illegal key %r' % (key,)) # It's a good key, so save it. self._key = key self._value = val self._coded_value = coded_val def __getstate__(self): return { 'key': self._key, 'value': self._value, 'coded_value': self._coded_value, } def __setstate__(self, state): self._key = state['key'] self._value = state['value'] self._coded_value = state['coded_value'] def output(self, attrs=None, header="Set-Cookie:"): return "%s %s" % (header, self.OutputString(attrs)) __str__ = output def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.OutputString()) def js_output(self, attrs=None): # Print javascript return """ <script type="text/javascript"> <!-- begin hiding document.cookie = \"%s\"; // end hiding --> </script> """ % (self.OutputString(attrs).replace('"', r'\"')) def OutputString(self, attrs=None): # Build up our result # result = [] append = result.append # First, the key=value pair append("%s=%s" % (self.key, self.coded_value)) # Now add any defined attributes if attrs is None: attrs = self._reserved items = sorted(self.items()) for key, value in items: if value == "": continue if key not in attrs: continue if key == "expires" and isinstance(value, int): append("%s=%s" % (self._reserved[key], _getdate(value))) elif key == "max-age" and isinstance(value, int): append("%s=%d" % (self._reserved[key], value)) elif key == "comment" and isinstance(value, str): append("%s=%s" % (self._reserved[key], _quote(value))) elif key in self._flags: if value: append(str(self._reserved[key])) else: append("%s=%s" % (self._reserved[key], value)) # Return the result return _semispacejoin(result) # # Pattern for finding cookie # # This used to be strict parsing based on the RFC2109 and RFC2068 # specifications. I have since discovered that MSIE 3.0x doesn't # follow the character rules outlined in those specs. As a # result, the parsing rules here are less strict. # _LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=" _LegalValueChars = _LegalKeyChars + r'\[\]' _CookiePattern = re.compile(r""" \s* # Optional whitespace at start of cookie (?P<key> # Start of group 'key' [""" + _LegalKeyChars + r"""]+? # Any word of at least one letter ) # End of group 'key' ( # Optional group: there may not be a value. \s*=\s* # Equal Sign (?P<val> # Start of group 'val' "(?:[^\\"]|\\.)*" # Any doublequoted string | # or \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr | # or [""" + _LegalValueChars + r"""]* # Any word or empty string ) # End of group 'val' )? # End of optional value group \s* # Any number of spaces. (\s+|;|$) # Ending either at space, semicolon, or EOS. """, re.ASCII | re.VERBOSE) # re.ASCII may be removed if safe. # At long last, here is the cookie class. Using this class is almost just like # using a dictionary. See this module's docstring for example usage. # class BaseCookie(dict): """A container class for a set of Morsels.""" def value_decode(self, val): """real_value, coded_value = value_decode(STRING) Called prior to setting a cookie's value from the network representation. The VALUE is the value read from HTTP header. Override this function to modify the behavior of cookies. """ return val, val def value_encode(self, val): """real_value, coded_value = value_encode(VALUE) Called prior to setting a cookie's value from the dictionary representation. The VALUE is the value being assigned. Override this function to modify the behavior of cookies. """ strval = str(val) return strval, strval def __init__(self, input=None): if input: self.load(input) def __set(self, key, real_value, coded_value): """Private method for setting a cookie's value""" M = self.get(key, Morsel()) M.set(key, real_value, coded_value) dict.__setitem__(self, key, M) def __setitem__(self, key, value): """Dictionary style assignment.""" if isinstance(value, Morsel): # allow assignment of constructed Morsels (e.g. for pickling) dict.__setitem__(self, key, value) else: rval, cval = self.value_encode(value) self.__set(key, rval, cval) def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): """Return a string suitable for HTTP.""" result = [] items = sorted(self.items()) for key, value in items: result.append(value.output(attrs, header)) return sep.join(result) __str__ = output def __repr__(self): l = [] items = sorted(self.items()) for key, value in items: l.append('%s=%s' % (key, repr(value.value))) return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l)) def js_output(self, attrs=None): """Return a string suitable for JavaScript.""" result = [] items = sorted(self.items()) for key, value in items: result.append(value.js_output(attrs)) return _nulljoin(result) def load(self, rawdata): """Load cookies from a string (presumably HTTP_COOKIE) or from a dictionary. Loading cookies from a dictionary 'd' is equivalent to calling: map(Cookie.__setitem__, d.keys(), d.values()) """ if isinstance(rawdata, str): self.__parse_string(rawdata) else: # self.update() wouldn't call our custom __setitem__ for key, value in rawdata.items(): self[key] = value return def __parse_string(self, str, patt=_CookiePattern): i = 0 # Our starting point n = len(str) # Length of string parsed_items = [] # Parsed (type, key, value) triples morsel_seen = False # A key=value pair was previously encountered TYPE_ATTRIBUTE = 1 TYPE_KEYVALUE = 2 # We first parse the whole cookie string and reject it if it's # syntactically invalid (this helps avoid some classes of injection # attacks). while 0 <= i < n: # Start looking for a cookie match = patt.match(str, i) if not match: # No more cookies break key, value = match.group("key"), match.group("val") i = match.end(0) if key[0] == "$": if not morsel_seen: # We ignore attributes which pertain to the cookie # mechanism as a whole, such as "$Version". # See RFC 2965. (Does anyone care?) continue parsed_items.append((TYPE_ATTRIBUTE, key[1:], value)) elif key.lower() in Morsel._reserved: if not morsel_seen: # Invalid cookie string return if value is None: if key.lower() in Morsel._flags: parsed_items.append((TYPE_ATTRIBUTE, key, True)) else: # Invalid cookie string return else: parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value))) elif value is not None: parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(value))) morsel_seen = True else: # Invalid cookie string return # The cookie string is valid, apply it. M = None # current morsel for tp, key, value in parsed_items: if tp == TYPE_ATTRIBUTE: assert M is not None M[key] = value else: assert tp == TYPE_KEYVALUE rval, cval = value self.__set(key, rval, cval) M = self[key] class SimpleCookie(BaseCookie): """ SimpleCookie supports strings as cookie values. When setting the value using the dictionary assignment notation, SimpleCookie calls the builtin str() to convert the value to a string. Values received from HTTP are kept as strings. """ def value_decode(self, val): return _unquote(val), val def value_encode(self, val): strval = str(val) return strval, _quote(strval)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/__init__.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/__init__.py
from enum import IntEnum __all__ = ['HTTPStatus'] class HTTPStatus(IntEnum): """HTTP status codes and reason phrases Status codes from the following RFCs are all observed: * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 * RFC 6585: Additional HTTP Status Codes * RFC 3229: Delta encoding in HTTP * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 * RFC 5842: Binding Extensions to WebDAV * RFC 7238: Permanent Redirect * RFC 2295: Transparent Content Negotiation in HTTP * RFC 2774: An HTTP Extension Framework * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) """ def __new__(cls, value, phrase, description=''): obj = int.__new__(cls, value) obj._value_ = value obj.phrase = phrase obj.description = description return obj # informational CONTINUE = 100, 'Continue', 'Request received, please continue' SWITCHING_PROTOCOLS = (101, 'Switching Protocols', 'Switching to new protocol; obey Upgrade header') PROCESSING = 102, 'Processing' # success OK = 200, 'OK', 'Request fulfilled, document follows' CREATED = 201, 'Created', 'Document created, URL follows' ACCEPTED = (202, 'Accepted', 'Request accepted, processing continues off-line') NON_AUTHORITATIVE_INFORMATION = (203, 'Non-Authoritative Information', 'Request fulfilled from cache') NO_CONTENT = 204, 'No Content', 'Request fulfilled, nothing follows' RESET_CONTENT = 205, 'Reset Content', 'Clear input form for further input' PARTIAL_CONTENT = 206, 'Partial Content', 'Partial content follows' MULTI_STATUS = 207, 'Multi-Status' ALREADY_REPORTED = 208, 'Already Reported' IM_USED = 226, 'IM Used' # redirection MULTIPLE_CHOICES = (300, 'Multiple Choices', 'Object has several resources -- see URI list') MOVED_PERMANENTLY = (301, 'Moved Permanently', 'Object moved permanently -- see URI list') FOUND = 302, 'Found', 'Object moved temporarily -- see URI list' SEE_OTHER = 303, 'See Other', 'Object moved -- see Method and URL list' NOT_MODIFIED = (304, 'Not Modified', 'Document has not changed since given time') USE_PROXY = (305, 'Use Proxy', 'You must use proxy specified in Location to access this resource') TEMPORARY_REDIRECT = (307, 'Temporary Redirect', 'Object moved temporarily -- see URI list') PERMANENT_REDIRECT = (308, 'Permanent Redirect', 'Object moved permanently -- see URI list') # client error BAD_REQUEST = (400, 'Bad Request', 'Bad request syntax or unsupported method') UNAUTHORIZED = (401, 'Unauthorized', 'No permission -- see authorization schemes') PAYMENT_REQUIRED = (402, 'Payment Required', 'No payment -- see charging schemes') FORBIDDEN = (403, 'Forbidden', 'Request forbidden -- authorization will not help') NOT_FOUND = (404, 'Not Found', 'Nothing matches the given URI') METHOD_NOT_ALLOWED = (405, 'Method Not Allowed', 'Specified method is invalid for this resource') NOT_ACCEPTABLE = (406, 'Not Acceptable', 'URI not available in preferred format') PROXY_AUTHENTICATION_REQUIRED = (407, 'Proxy Authentication Required', 'You must authenticate with this proxy before proceeding') REQUEST_TIMEOUT = (408, 'Request Timeout', 'Request timed out; try again later') CONFLICT = 409, 'Conflict', 'Request conflict' GONE = (410, 'Gone', 'URI no longer exists and has been permanently removed') LENGTH_REQUIRED = (411, 'Length Required', 'Client must specify Content-Length') PRECONDITION_FAILED = (412, 'Precondition Failed', 'Precondition in headers is false') REQUEST_ENTITY_TOO_LARGE = (413, 'Request Entity Too Large', 'Entity is too large') REQUEST_URI_TOO_LONG = (414, 'Request-URI Too Long', 'URI is too long') UNSUPPORTED_MEDIA_TYPE = (415, 'Unsupported Media Type', 'Entity body in unsupported format') REQUESTED_RANGE_NOT_SATISFIABLE = (416, 'Requested Range Not Satisfiable', 'Cannot satisfy request range') EXPECTATION_FAILED = (417, 'Expectation Failed', 'Expect condition could not be satisfied') MISDIRECTED_REQUEST = (421, 'Misdirected Request', 'Server is not able to produce a response') UNPROCESSABLE_ENTITY = 422, 'Unprocessable Entity' LOCKED = 423, 'Locked' FAILED_DEPENDENCY = 424, 'Failed Dependency' UPGRADE_REQUIRED = 426, 'Upgrade Required' PRECONDITION_REQUIRED = (428, 'Precondition Required', 'The origin server requires the request to be conditional') TOO_MANY_REQUESTS = (429, 'Too Many Requests', 'The user has sent too many requests in ' 'a given amount of time ("rate limiting")') REQUEST_HEADER_FIELDS_TOO_LARGE = (431, 'Request Header Fields Too Large', 'The server is unwilling to process the request because its header ' 'fields are too large') # server errors INTERNAL_SERVER_ERROR = (500, 'Internal Server Error', 'Server got itself in trouble') NOT_IMPLEMENTED = (501, 'Not Implemented', 'Server does not support this operation') BAD_GATEWAY = (502, 'Bad Gateway', 'Invalid responses from another server/proxy') SERVICE_UNAVAILABLE = (503, 'Service Unavailable', 'The server cannot process the request due to a high load') GATEWAY_TIMEOUT = (504, 'Gateway Timeout', 'The gateway server did not receive a timely response') HTTP_VERSION_NOT_SUPPORTED = (505, 'HTTP Version Not Supported', 'Cannot fulfill request') VARIANT_ALSO_NEGOTIATES = 506, 'Variant Also Negotiates' INSUFFICIENT_STORAGE = 507, 'Insufficient Storage' LOOP_DETECTED = 508, 'Loop Detected' NOT_EXTENDED = 510, 'Not Extended' NETWORK_AUTHENTICATION_REQUIRED = (511, 'Network Authentication Required', 'The client needs to authenticate to gain network access')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/server.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/http/server.py
"""HTTP server classes. Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, and CGIHTTPRequestHandler for CGI scripts. It does, however, optionally implement HTTP/1.1 persistent connections, as of version 0.3. Notes on CGIHTTPRequestHandler ------------------------------ This class implements GET and POST requests to cgi-bin scripts. If the os.fork() function is not present (e.g. on Windows), subprocess.Popen() is used as a fallback, with slightly altered semantics. In all cases, the implementation is intentionally naive -- all requests are executed synchronously. SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL -- it may execute arbitrary Python code or external programs. Note that status code 200 is sent prior to execution of a CGI script, so scripts cannot send other status codes such as 302 (redirect). XXX To do: - log requests even later (to capture byte count) - log user-agent header and other interesting goodies - send error log to separate file """ # See also: # # HTTP Working Group T. Berners-Lee # INTERNET-DRAFT R. T. Fielding # <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen # Expires September 8, 1995 March 8, 1995 # # URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt # # and # # Network Working Group R. Fielding # Request for Comments: 2616 et al # Obsoletes: 2068 June 1999 # Category: Standards Track # # URL: http://www.faqs.org/rfcs/rfc2616.html # Log files # --------- # # Here's a quote from the NCSA httpd docs about log file format. # # | The logfile format is as follows. Each line consists of: # | # | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb # | # | host: Either the DNS name or the IP number of the remote client # | rfc931: Any information returned by identd for this person, # | - otherwise. # | authuser: If user sent a userid for authentication, the user name, # | - otherwise. # | DD: Day # | Mon: Month (calendar name) # | YYYY: Year # | hh: hour (24-hour format, the machine's timezone) # | mm: minutes # | ss: seconds # | request: The first line of the HTTP request as sent by the client. # | ddd: the status code returned by the server, - if not available. # | bbbb: the total number of bytes sent, # | *not including the HTTP/1.0 header*, - if not available # | # | You can determine the name of the file accessed through request. # # (Actually, the latter is only true if you know the server configuration # at the time the request was made!) __version__ = "0.6" __all__ = [ "HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler", ] import copy import datetime import email.utils import html import http.client import io import mimetypes import os import posixpath import select import shutil import socket # For gethostbyaddr() import socketserver import sys import time import urllib.parse from functools import partial from http import HTTPStatus # Default error message template DEFAULT_ERROR_MESSAGE = """\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Error response</title> </head> <body> <h1>Error response</h1> <p>Error code: %(code)d</p> <p>Message: %(message)s.</p> <p>Error code explanation: %(code)s - %(explain)s.</p> </body> </html> """ DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8" class HTTPServer(socketserver.TCPServer): allow_reuse_address = 1 # Seems to make sense in testing environment def server_bind(self): """Override server_bind to store the server name.""" socketserver.TCPServer.server_bind(self) host, port = self.server_address[:2] self.server_name = socket.getfqdn(host) self.server_port = port class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): daemon_threads = True class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """HTTP request handler base class. The following explanation of HTTP serves to guide you through the code as well as to expose any misunderstandings I may have about HTTP (so you don't need to read the code to figure out I'm wrong :-). HTTP (HyperText Transfer Protocol) is an extensible protocol on top of a reliable stream transport (e.g. TCP/IP). The protocol recognizes three parts to a request: 1. One line identifying the request type and path 2. An optional set of RFC-822-style headers 3. An optional data part The headers and data are separated by a blank line. The first line of the request has the form <command> <path> <version> where <command> is a (case-sensitive) keyword such as GET or POST, <path> is a string containing path information for the request, and <version> should be the string "HTTP/1.0" or "HTTP/1.1". <path> is encoded using the URL encoding scheme (using %xx to signify the ASCII character with hex code xx). The specification specifies that lines are separated by CRLF but for compatibility with the widest range of clients recommends servers also handle LF. Similarly, whitespace in the request line is treated sensibly (allowing multiple spaces between components and allowing trailing whitespace). Similarly, for output, lines ought to be separated by CRLF pairs but most clients grok LF characters just fine. If the first line of the request has the form <command> <path> (i.e. <version> is left out) then this is assumed to be an HTTP 0.9 request; this form has no optional headers and data part and the reply consists of just the data. The reply form of the HTTP 1.x protocol again has three parts: 1. One line giving the response code 2. An optional set of RFC-822-style headers 3. The data Again, the headers and data are separated by a blank line. The response code line has the form <version> <responsecode> <responsestring> where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"), <responsecode> is a 3-digit response code indicating success or failure of the request, and <responsestring> is an optional human-readable string explaining what the response code means. This server parses the request and the headers, and then calls a function specific to the request type (<command>). Specifically, a request SPAM will be handled by a method do_SPAM(). If no such method exists the server sends an error response to the client. If it exists, it is called with no arguments: do_SPAM() Note that the request name is case sensitive (i.e. SPAM and spam are different requests). The various request details are stored in instance variables: - client_address is the client IP address in the form (host, port); - command, path and version are the broken-down request line; - headers is an instance of email.message.Message (or a derived class) containing the header information; - rfile is a file object open for reading positioned at the start of the optional input data part; - wfile is a file object open for writing. IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! The first thing to be written must be the response line. Then follow 0 or more header lines, then a blank line, and then the actual data (if any). The meaning of the header lines depends on the command executed by the server; in most cases, when data is returned, there should be at least one header line of the form Content-type: <type>/<subtype> where <type> and <subtype> should be registered MIME types, e.g. "text/html" or "text/plain". """ # The Python system version, truncated to its first component. sys_version = "Python/" + sys.version.split()[0] # The server software version. You may want to override this. # The format is multiple whitespace-separated strings, # where each string is of the form name[/version]. server_version = "BaseHTTP/" + __version__ error_message_format = DEFAULT_ERROR_MESSAGE error_content_type = DEFAULT_ERROR_CONTENT_TYPE # The default request version. This only affects responses up until # the point where the request line is parsed, so it mainly decides what # the client gets back when sending a malformed request line. # Most web servers default to HTTP 0.9, i.e. don't send a status line. default_request_version = "HTTP/0.9" def parse_request(self): """Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, any relevant error response has already been sent back. """ self.command = None # set in case of error on the first line self.request_version = version = self.default_request_version self.close_connection = True requestline = str(self.raw_requestline, 'iso-8859-1') requestline = requestline.rstrip('\r\n') self.requestline = requestline words = requestline.split() if len(words) == 0: return False if len(words) >= 3: # Enough to determine protocol version version = words[-1] try: if not version.startswith('HTTP/'): raise ValueError base_version_number = version.split('/', 1)[1] version_number = base_version_number.split(".") # RFC 2145 section 3.1 says there can be only one "." and # - major and minor numbers MUST be treated as # separate integers; # - HTTP/2.4 is a lower version than HTTP/2.13, which in # turn is lower than HTTP/12.3; # - Leading zeros MUST be ignored by recipients. if len(version_number) != 2: raise ValueError version_number = int(version_number[0]), int(version_number[1]) except (ValueError, IndexError): self.send_error( HTTPStatus.BAD_REQUEST, "Bad request version (%r)" % version) return False if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1": self.close_connection = False if version_number >= (2, 0): self.send_error( HTTPStatus.HTTP_VERSION_NOT_SUPPORTED, "Invalid HTTP version (%s)" % base_version_number) return False self.request_version = version if not 2 <= len(words) <= 3: self.send_error( HTTPStatus.BAD_REQUEST, "Bad request syntax (%r)" % requestline) return False command, path = words[:2] if len(words) == 2: self.close_connection = True if command != 'GET': self.send_error( HTTPStatus.BAD_REQUEST, "Bad HTTP/0.9 request type (%r)" % command) return False self.command, self.path = command, path # Examine the headers and look for a Connection directive. try: self.headers = http.client.parse_headers(self.rfile, _class=self.MessageClass) except http.client.LineTooLong as err: self.send_error( HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE, "Line too long", str(err)) return False except http.client.HTTPException as err: self.send_error( HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE, "Too many headers", str(err) ) return False conntype = self.headers.get('Connection', "") if conntype.lower() == 'close': self.close_connection = True elif (conntype.lower() == 'keep-alive' and self.protocol_version >= "HTTP/1.1"): self.close_connection = False # Examine the headers and look for an Expect directive expect = self.headers.get('Expect', "") if (expect.lower() == "100-continue" and self.protocol_version >= "HTTP/1.1" and self.request_version >= "HTTP/1.1"): if not self.handle_expect_100(): return False return True def handle_expect_100(self): """Decide what to do with an "Expect: 100-continue" header. If the client is expecting a 100 Continue response, we must respond with either a 100 Continue or a final response before waiting for the request body. The default is to always respond with a 100 Continue. You can behave differently (for example, reject unauthorized requests) by overriding this method. This method should either return True (possibly after sending a 100 Continue response) or send an error response and return False. """ self.send_response_only(HTTPStatus.CONTINUE) self.end_headers() return True def handle_one_request(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ try: self.raw_requestline = self.rfile.readline(65537) if len(self.raw_requestline) > 65536: self.requestline = '' self.request_version = '' self.command = '' self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG) return if not self.raw_requestline: self.close_connection = True return if not self.parse_request(): # An error code has been sent, just exit return mname = 'do_' + self.command if not hasattr(self, mname): self.send_error( HTTPStatus.NOT_IMPLEMENTED, "Unsupported method (%r)" % self.command) return method = getattr(self, mname) method() self.wfile.flush() #actually send the response if not already done. except socket.timeout as e: #a read or a write timed out. Discard this connection self.log_error("Request timed out: %r", e) self.close_connection = True return def handle(self): """Handle multiple requests if necessary.""" self.close_connection = True self.handle_one_request() while not self.close_connection: self.handle_one_request() def send_error(self, code, message=None, explain=None): """Send and log an error reply. Arguments are * code: an HTTP error code 3 digits * message: a simple optional 1 line reason phrase. *( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code * explain: a detailed message defaults to the long entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user. """ try: shortmsg, longmsg = self.responses[code] except KeyError: shortmsg, longmsg = '???', '???' if message is None: message = shortmsg if explain is None: explain = longmsg self.log_error("code %d, message %s", code, message) self.send_response(code, message) self.send_header('Connection', 'close') # Message body is omitted for cases described in: # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified) # - RFC7231: 6.3.6. 205(Reset Content) body = None if (code >= 200 and code not in (HTTPStatus.NO_CONTENT, HTTPStatus.RESET_CONTENT, HTTPStatus.NOT_MODIFIED)): # HTML encode to prevent Cross Site Scripting attacks # (see bug #1100201) content = (self.error_message_format % { 'code': code, 'message': html.escape(message, quote=False), 'explain': html.escape(explain, quote=False) }) body = content.encode('UTF-8', 'replace') self.send_header("Content-Type", self.error_content_type) self.send_header('Content-Length', str(len(body))) self.end_headers() if self.command != 'HEAD' and body: self.wfile.write(body) def send_response(self, code, message=None): """Add the response header to the headers buffer and log the response code. Also send two standard headers with the server software version and the current date. """ self.log_request(code) self.send_response_only(code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string()) def send_response_only(self, code, message=None): """Send the response header only.""" if self.request_version != 'HTTP/0.9': if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if not hasattr(self, '_headers_buffer'): self._headers_buffer = [] self._headers_buffer.append(("%s %d %s\r\n" % (self.protocol_version, code, message)).encode( 'latin-1', 'strict')) def send_header(self, keyword, value): """Send a MIME header to the headers buffer.""" if self.request_version != 'HTTP/0.9': if not hasattr(self, '_headers_buffer'): self._headers_buffer = [] self._headers_buffer.append( ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict')) if keyword.lower() == 'connection': if value.lower() == 'close': self.close_connection = True elif value.lower() == 'keep-alive': self.close_connection = False def end_headers(self): """Send the blank line ending the MIME headers.""" if self.request_version != 'HTTP/0.9': self._headers_buffer.append(b"\r\n") self.flush_headers() def flush_headers(self): if hasattr(self, '_headers_buffer'): self.wfile.write(b"".join(self._headers_buffer)) self._headers_buffer = [] def log_request(self, code='-', size='-'): """Log an accepted request. This is called by send_response(). """ if isinstance(code, HTTPStatus): code = code.value self.log_message('"%s" %s %s', self.requestline, str(code), str(size)) def log_error(self, format, *args): """Log an error. This is called when a request cannot be fulfilled. By default it passes the message on to log_message(). Arguments are the same as for log_message(). XXX This should go to the separate error log. """ self.log_message(format, *args) def log_message(self, format, *args): """Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it's just like printf!). The client ip and current date/time are prefixed to every message. """ sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args)) def version_string(self): """Return the server software version string.""" return self.server_version + ' ' + self.sys_version def date_time_string(self, timestamp=None): """Return the current date and time formatted for a message header.""" if timestamp is None: timestamp = time.time() return email.utils.formatdate(timestamp, usegmt=True) def log_date_time_string(self): """Return the current time formatted for logging.""" now = time.time() year, month, day, hh, mm, ss, x, y, z = time.localtime(now) s = "%02d/%3s/%04d %02d:%02d:%02d" % ( day, self.monthname[month], year, hh, mm, ss) return s weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def address_string(self): """Return the client address.""" return self.client_address[0] # Essentially static class variables # The version of the HTTP protocol we support. # Set this to HTTP/1.1 to enable automatic keepalive protocol_version = "HTTP/1.0" # MessageClass used to parse headers MessageClass = http.client.HTTPMessage # hack to maintain backwards compatibility responses = { v: (v.phrase, v.description) for v in HTTPStatus.__members__.values() } class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): """Simple HTTP request handler with GET and HEAD commands. This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method. The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file. """ server_version = "SimpleHTTP/" + __version__ def __init__(self, *args, directory=None, **kwargs): if directory is None: directory = os.getcwd() self.directory = directory super().__init__(*args, **kwargs) def do_GET(self): """Serve a GET request.""" f = self.send_head() if f: try: self.copyfile(f, self.wfile) finally: f.close() def do_HEAD(self): """Serve a HEAD request.""" f = self.send_head() if f: f.close() def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. """ path = self.translate_path(self.path) f = None if os.path.isdir(path): parts = urllib.parse.urlsplit(self.path) if not parts.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(HTTPStatus.MOVED_PERMANENTLY) new_parts = (parts[0], parts[1], parts[2] + '/', parts[3], parts[4]) new_url = urllib.parse.urlunsplit(new_parts) self.send_header("Location", new_url) self.end_headers() return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: f = open(path, 'rb') except OSError: self.send_error(HTTPStatus.NOT_FOUND, "File not found") return None try: fs = os.fstat(f.fileno()) # Use browser cache if possible if ("If-Modified-Since" in self.headers and "If-None-Match" not in self.headers): # compare If-Modified-Since and time of last file modification try: ims = email.utils.parsedate_to_datetime( self.headers["If-Modified-Since"]) except (TypeError, IndexError, OverflowError, ValueError): # ignore ill-formed values pass else: if ims.tzinfo is None: # obsolete format with no timezone, cf. # https://tools.ietf.org/html/rfc7231#section-7.1.1.1 ims = ims.replace(tzinfo=datetime.timezone.utc) if ims.tzinfo is datetime.timezone.utc: # compare to UTC datetime of last modification last_modif = datetime.datetime.fromtimestamp( fs.st_mtime, datetime.timezone.utc) # remove microseconds, like in If-Modified-Since last_modif = last_modif.replace(microsecond=0) if last_modif <= ims: self.send_response(HTTPStatus.NOT_MODIFIED) self.end_headers() f.close() return None self.send_response(HTTPStatus.OK) self.send_header("Content-type", ctype) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f except: f.close() raise def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except OSError: self.send_error( HTTPStatus.NOT_FOUND, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) r = [] try: displaypath = urllib.parse.unquote(self.path, errors='surrogatepass') except UnicodeDecodeError: displaypath = urllib.parse.unquote(path) displaypath = html.escape(displaypath, quote=False) enc = sys.getfilesystemencoding() title = 'Directory listing for %s' % displaypath r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ' '"http://www.w3.org/TR/html4/strict.dtd">') r.append('<html>\n<head>') r.append('<meta http-equiv="Content-Type" ' 'content="text/html; charset=%s">' % enc) r.append('<title>%s</title>\n</head>' % title) r.append('<body>\n<h1>%s</h1>' % title) r.append('<hr>\n<ul>') for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / r.append('<li><a href="%s">%s</a></li>' % (urllib.parse.quote(linkname, errors='surrogatepass'), html.escape(displayname, quote=False))) r.append('</ul>\n<hr>\n</body>\n</html>\n') encoded = '\n'.join(r).encode(enc, 'surrogateescape') f = io.BytesIO() f.write(encoded) f.seek(0) self.send_response(HTTPStatus.OK) self.send_header("Content-type", "text/html; charset=%s" % enc) self.send_header("Content-Length", str(len(encoded))) self.end_headers() return f def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] # Don't forget explicit trailing slash when normalizing. Issue17324 trailing_slash = path.rstrip().endswith('/') try: path = urllib.parse.unquote(path, errors='surrogatepass') except UnicodeDecodeError: path = urllib.parse.unquote(path) path = posixpath.normpath(path) words = path.split('/') words = filter(None, words) path = self.directory for word in words: if os.path.dirname(word) or word in (os.curdir, os.pardir): # Ignore components that are not a simple file/directory name continue path = os.path.join(path, word) if trailing_slash: path += '/' return path def copyfile(self, source, outputfile): """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. """ shutil.copyfileobj(source, outputfile) def guess_type(self, path): """Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file's extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (if slow) to look inside the data to make a better guess. """ base, ext = posixpath.splitext(path) if ext in self.extensions_map: return self.extensions_map[ext] ext = ext.lower() if ext in self.extensions_map: return self.extensions_map[ext] else: return self.extensions_map[''] if not mimetypes.inited: mimetypes.init() # try to read system mime.types extensions_map = mimetypes.types_map.copy() extensions_map.update({ '': 'application/octet-stream', # Default '.py': 'text/plain', '.c': 'text/plain', '.h': 'text/plain', }) # Utilities for CGIHTTPRequestHandler def _url_collapse_path(path): """ Given a URL path, remove extra '/'s and '.' path elements and collapse any '..' references and returns a collapsed path. Implements something akin to RFC-2396 5.2 step 6 to parse relative paths. The utility of this function is limited to is_cgi method and helps preventing some security attacks.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TyphoonCon/2022/pwn/beautifier_player/server/serve.py
ctfs/TyphoonCon/2022/pwn/beautifier_player/server/serve.py
#!/usr/bin/env python from operator import truediv from aiohttp import web from PIL import Image, ImageEnhance from io import BytesIO as buffio from base64 import b64encode as b64 from os import remove, getenv, makedirs, path from filelock import FileLock from time import time application = web.Application() routes = web.RouteTableDef() class logger: @staticmethod def log_success(message): print("[+] %s" % message, flush=True) @staticmethod def log_info(message): print("[!] %s" % message, flush=True) @staticmethod def log_error(message): print("[-] %s" % message, flush=True) uploads = getenv("uploads", None) if not uploads or not path.isdir(uploads): logger.log_info("You have to set the $uploads with a valid directory") uploads = "/tmp/uploads" makedirs(uploads, exist_ok=True) class upload: def __init__(self, size): lock_file = path.join(uploads, "uploads.lck") self.__lock = FileLock(lock_file) self.__lock.acquire() time_stamp = int(time()) while True: image_path = path.join(uploads, "upload_%x" % time_stamp) if not path.isfile(image_path): break time_stamp += 1 self.__path = image_path self.__file = open(image_path, "wb+") self.__lock.release() self.__file.truncate(size) @property def fd(self): return self.__file def __del__(self): self.__lock.acquire() self.__file.close() remove(self.__path) self.__lock.release() @routes.post('/submit') async def server_submit(request): content_type = request.headers.get("Content-Type", None) content_length = request.headers.get("Content-Length", None) if not content_type or not content_type.startswith("image/"): return web.Response(text="Only images can be submitted.", status=415) if not content_length or not content_length.isnumeric(): content_length = 2 ** 10 content_length = int(content_length) if content_length > 10 * (2 ** 20): return web.Response(text="The maximum file size is 10MB.", status=400) logger.log_info("Processing a new image with size %d bytes" % content_length) file = upload(content_length) async for data in request.content.iter_any(): file.fd.write(data) file.fd.flush() file.fd.seek(0) buffer = buffio() try: image = Image.open(file.fd) image = ImageEnhance.Contrast(image).enhance(2) image.save(buffer, format='PNG') except Exception as e: logger.log_error("Image processing exception: %s" % str(e)) return web.Response(text="Unable to process the image.", status=500) buffer = buffer.getvalue() buffer = b"data:image/png;charset=utf-8;base64," + b64(buffer) return web.Response(body=buffer) @routes.get('/') async def server_upload(request): user_agent = request.headers.get("User-Agent", "<unknown>") logger.log_success("Connected to a new client: %s" % user_agent) uploader = open(path.join(path.abspath(path.dirname(__file__)), "static/upload.html"), "r") return web.Response(text=uploader.read(), content_type='text/html') def run(host, port): try: web.run_app(application, host=host, port=int(port)) except Exception as e: logger.log_error(str(e)) def main(): from sys import argv if len(argv) != 3: logger.log_info("%s <server_host> <server_port>" % argv[0]) return logger.log_info("Starting the server on http://%s:%s" % (argv[1], argv[2])) run(argv[1], argv[2]) application.add_routes(routes) if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/Rohald/RoHaLd_ECC.py
ctfs/Crypto/2021/Rohald/RoHaLd_ECC.py
#!/usr/bin/env sage from Crypto.Util.number import * from secret import flag, Curve def ison(C, P): c, d, p = C u, v = P return (u**2 + v**2 - c**2 * (1 + d * u**2*v**2)) % p == 0 def teal(C, P, Q): c, d, p = C u1, v1 = P u2, v2 = Q assert ison(C, P) and ison(C, Q) u3 = (u1 * v2 + v1 * u2) * inverse(c * (1 + d * u1 * u2 * v1 * v2), p) % p v3 = (v1 * v2 - u1 * u2) * inverse(c * (1 - d * u1 * u2 * v1 * v2), p) % p return (int(u3), int(v3)) def peam(C, P, m): assert ison(C, P) c, d, p = C B = bin(m)[2:] l = len(B) u, v = P PP = (-u, v) O = teal(C, P, PP) Q = O if m == 0: return O elif m == 1: return P else: for _ in range(l-1): P = teal(C, P, P) m = m - 2**(l-1) Q, P = P, (u, v) return teal(C, Q, peam(C, P, m)) c, d, p = Curve flag = flag.lstrip(b'CCTF{').rstrip(b'}') l = len(flag) lflag, rflag = flag[:l // 2], flag[l // 2:] s, t = bytes_to_long(lflag), bytes_to_long(rflag) assert s < p and t < p P = (398011447251267732058427934569710020713094, 548950454294712661054528329798266699762662) Q = (139255151342889674616838168412769112246165, 649791718379009629228240558980851356197207) print(f'ison(C, P) = {ison(Curve, P)}') print(f'ison(C, Q) = {ison(Curve, Q)}') print(f'P = {P}') print(f'Q = {Q}') print(f's * P = {peam(Curve, P, s)}') print(f't * Q = {peam(Curve, Q, t)}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/hyper_normal/hyper_normal.py
ctfs/Crypto/2021/hyper_normal/hyper_normal.py
#!/usr/bin/env python3 import random from flag import FLAG p = 8443 def transpose(x): result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))] return result def vsum(u, v): assert len(u) == len(v) l, w = len(u), [] for i in range(l): w += [(u[i] + v[i]) % p] return w def sprod(a, u): w = [] for i in range(len(u)): w += [a*u[i] % p] return w def encrypt(msg): l = len(msg) hyper = [ord(m)*(i+1) for (m, i) in zip(list(msg), range(l))] V, W = [], [] for i in range(l): v = [0]*i + [hyper[i]] + [0]*(l - i - 1) V.append(v) random.shuffle(V) for _ in range(l): R, v = [random.randint(0, 126) for _ in range(l)], [0]*l for j in range(l): v = vsum(v, sprod(R[j], V[j])) W.append(v) random.shuffle(transpose(W)) return W enc = encrypt(FLAG) print(enc)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/linda/linda.py
ctfs/Crypto/2021/linda/linda.py
#!/usr/bin/env python3 from Crypto.Util.number import * from math import gcd from flag import flag def keygen(p): while True: u = getRandomRange(1, p) if pow(u, (p-1) // 2, p) != 1: break x = getRandomRange(1, p) w = pow(u, x, p) while True: r = getRandomRange(1, p-1) if gcd(r, p-1) == 1: y = x * inverse(r, p-1) % (p-1) v = pow(u, r, p) return u, v, w def encrypt(m, pubkey): p, u, v, w = pubkey assert m < p r, s = [getRandomRange(1, p) for _ in '01'] ca = pow(u, r, p) cb = pow(v, s, p) cc = m * pow(w, r + s, p) % p enc = (ca, cb, cc) return enc def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " .:::::: LINDA Cryptosystem has high grade security level ::::::. ", border) pr(border, " Can you break this cryptosystem and find the flag? ", border) pr(border*72) pr('| please wait, preparing the LINDA is time consuming...') from secret import p u, v, w = keygen(p) msg = bytes_to_long(flag) pubkey = p, u, v, w enc = encrypt(msg, pubkey) while True: pr("| Options: \n|\t[E]xpose the parameters \n|\t[T]est the encryption \n|\t[S]how the encrypted flag \n|\t[Q]uit") ans = sc().lower() if ans == 'e': pr(f'| p = {p}') pr(f'| u = {u}') pr(f'| v = {v}') pr(f'| w = {w}') elif ans == 's': print(f'enc = {enc}') elif ans == 't': pr('| send your message to encrypt: ') m = sc() m = bytes_to_long(m.encode('utf-8')) pr(f'| encrypt(m) = {encrypt(m, pubkey)}') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/improved/improved.py
ctfs/Crypto/2021/improved/improved.py
#!/usr/bin/env python3 from Crypto.Util.number import * from gmpy2 import gcd from random import randint import sys, hashlib from flag import flag def lcm(a, b): return (a * b) // gcd(a,b) def gen_params(nbit): p, q = [getPrime(nbit) for _ in range(2)] n, f, g = p * q, lcm(p-1, q-1), p + q e = pow(g, f, n**2) u = divmod(e-1, n)[0] v = inverse(u, n) params = int(n), int(f), int(v) return params def improved(m, params): n, f, v = params if 1 < m < n**2 - 1: e = pow(m, f, n**2) u = divmod(e-1, n)[0] L = divmod(u*v, n)[1] H = hashlib.sha1(str(L).encode('utf-8')).hexdigest() return H def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi talented cryptographers! Your mission is to find hash collision ", border) pr(border, " in the given hash function based on famous cryptographic algorithm ", border) pr(border, " see the source code and get the flag! Its improved version :) ", border) pr(border*72) nbit = 512 params = gen_params(nbit) n = params[0] while True: pr("| Options: \n|\t[R]eport collision! \n|\t[T]ry hash \n|\t[G]et parameters \n|\t[Q]uit") ans = sc().lower() if ans == 'r': pr("| please send the messages split by comma: ") m = sc() try: m_1, m_2 = m.split(',') m_1, m_2 = int(m_1), int(m_2) except: die("| Sorry! your input is invalid, Bye!!") # fix the bug :P if m_1 % n != 0 and m_2 % n != 0 and m_1 != m_2 and 1 < m_1 < n**2-1 and 1 < m_2 < n**2-1 and improved(m_1, params) == improved(m_2, params): die(f"| Congrats! You find the collision!! the flag is: {flag}") else: die("| Sorry! your input is not correct!!") elif ans == 't': pr("| Please send your message to get the hash: ") m = sc() try: m = int(m) pr(f"improved(m) = {improved(m, params)}") except: die("| Sorry! your input is invalid, Bye!!") elif ans == 'g': pr('| Parameters =', params) elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/salt_pepper/salt_pepper.py
ctfs/Crypto/2021/salt_pepper/salt_pepper.py
#!/usr/bin/env python3 from hashlib import md5, sha1 import sys from secret import salt, pepper from flag import flag assert len(salt) == len(pepper) == 19 assert md5(salt).hexdigest() == '5f72c4360a2287bc269e0ccba6fc24ba' assert sha1(pepper).hexdigest() == '3e0d000a4b0bd712999d730bc331f400221008e0' def auth_check(salt, pepper, username, password, h): return sha1(pepper + password + md5(salt + username).hexdigest().encode('utf-8')).hexdigest() == h def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " welcome to hash killers battle, your mission is to login into the ", border) pr(border, " ultra secure authentication server with provided information!! ", border) pr(border*72) USERNAME = b'n3T4Dm1n' PASSWORD = b'P4s5W0rd' while True: pr("| Options: \n|\t[L]ogin to server \n|\t[Q]uit") ans = sc().lower() if ans == 'l': pr('| send your username, password as hex string separated with comma: ') inp = sc() try: inp_username, inp_password = [bytes.fromhex(s) for s in inp.split(',')] except: die('| your input is not valid, bye!!') pr('| send your authentication hash: ') inp_hash = sc() if USERNAME in inp_username and PASSWORD in inp_password: if auth_check(salt, pepper, inp_username, inp_password, inp_hash): die(f'| Congrats, you are master in hash killing, and it is the flag: {flag}') else: die('| your credential is not valid, Bye!!!') else: die('| Kidding me?! Bye!!!') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/Wolf/Wolf.py
ctfs/Crypto/2021/Wolf/Wolf.py
#!/usr/bin/env python3 from Cryptodome.Cipher import AES import os, time, sys, random from flag import flag passphrase = b'HungryTimberWolf' def encrypt(msg, passphrase, niv): msg_header = 'EPOCH:' + str(int(time.time())) msg = msg_header + "\n" + msg + '=' * (15 - len(msg) % 16) aes = AES.new(passphrase, AES.MODE_GCM, nonce = niv) enc = aes.encrypt_and_digest(msg.encode('utf-8'))[0] return enc def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi wolf hunters, welcome to the most dangerous hunting ground!! ", border) pr(border, " decrypt the encrypted message and get the flag as a nice prize! ", border) pr(border*72) niv = os.urandom(random.randint(1, 11)) flag_enc = encrypt(flag, passphrase, niv) while True: pr("| Options: \n|\t[G]et the encrypted flag \n|\t[T]est the encryption \n|\t[Q]uit") ans = sc().lower() if ans == 'g': pr(f'| encrypt(flag) = {flag_enc.hex()}') elif ans == 't': pr("| Please send your message to encrypt: ") msg_inp = sc() enc = encrypt(msg_inp, passphrase, niv).hex() pr(f'| enc = {enc}') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/double_miff/double_miff.py
ctfs/Crypto/2021/double_miff/double_miff.py
#!/usr/bin/env python3 from Crypto.Util.number import * from secret import a, b, p, P, Q from flag import flag def onmiff(a, b, p, G): x, y = G return (a*x*(y**2 - 1) - b*y*(x**2 - 1)) % p == 0 def addmiff(X, Y): x_1, y_1 = X x_2, y_2 = Y x_3 = (x_1 + x_2) * (1 + y_1*y_2) * inverse((1 + x_1*x_2) * (1 - y_1*y_2), p) % p y_3 = (y_1 + y_2) * (1 + x_1*x_2) * inverse((1 + y_1*y_2) * (1 - x_1*x_2), p) % p return (x_3, y_3) l = len(flag) // 2 m1, m2 = bytes_to_long(flag[:l]), bytes_to_long(flag[l:]) assert m1 < (p // 2) and m2 < (p // 2) assert onmiff(a, b, p, P) and onmiff(a, b, p, Q) assert P[0] == m1 and Q[0] == m2 print(f'P + Q = {addmiff(P, Q)}') print(f'Q + Q = {addmiff(Q, Q)}') print(f'P + P = {addmiff(P, P)}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/TRUNC/trunc.py
ctfs/Crypto/2021/TRUNC/trunc.py
#!/usr/bin/env python3 from Crypto.Util.number import * from hashlib import sha256 import ecdsa from flag import FLAG E = ecdsa.SECP256k1 G, n = E.generator, E.order cryptonym = b'Persian Gulf' def keygen(n, G): privkey = getRandomRange(1, n-1) pubkey = privkey * G return (pubkey, privkey) def sign(msg, keypair): nbit, dbit = 256, 25 pubkey, privkey = keypair privkey_bytes = long_to_bytes(privkey) x = int(sha256(privkey_bytes).hexdigest(), 16) % 2**dbit while True: k, l = [(getRandomNBitInteger(nbit) << dbit) + x for _ in '01'] u, v = (k * G).x(), (l * G).y() if u + v > 0: break h = int(sha256(msg).hexdigest(), 16) s = inverse(k, n) * (h * u - v * privkey) % n return (int(u), int(v), int(s)) def verify(msg, pubkey, sig): if any(x < 1 or x >= n for x in sig): return False u, v, s = sig h = int(sha256(msg).hexdigest(), 16) k, l = h * u * inverse(s, n), v * inverse(s, n) X = (k * G + (n - l) * pubkey).x() return (X - u) % n == 0 def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi all, welcome to the high secure elliptic curve signature oracle!", border) pr(border, " Your mission is to sign the out cryptonym, try your best :) ", border) pr(border*72) keypair = keygen(n, G) pubkey, privkey = keypair while True: pr("| Options: \n|\t[P]rint the pubkey \n|\t[S]ign \n|\t[V]erify \n|\t[Q]uit") ans = sc().lower() if ans == 'p': pr("| pubkey =", pubkey.x(), pubkey.y()) elif ans == 's': pr("| send your hex message to sign: ") msg = sc() try: msg = bytes.fromhex(msg) except: die("| your message is not valid! Bye!!") if msg == cryptonym: die('| Kidding me? Bye') msg = msg[:14] sig = sign(msg, keypair) pr("| sign =", sig) elif ans == 'v': pr("| send your hex message to verify: ") msg = sc() try: msg = bytes.fromhex(msg) except: die("| your message is not valid! Bye!!") pr("| send the signature separated with comma: ") sig = sc() try: sig = [int(s) for s in sig.split(',')] except: die("| your signature is not valid! Bye!!") if verify(msg, pubkey, sig): if msg == cryptonym: die("| Good job! Congrats, the flag is:", FLAG) else: pr("| your message is verified!!") else: die("| your signature is not valid! Bye!!") elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/Triplet/Triplet.py
ctfs/Crypto/2021/Triplet/Triplet.py
#!/usr/bin/env python3 from Crypto.Util.number import * from random import randint import sys from flag import FLAG def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi talented cryptographers, the mission is to find the three RSA ", border) pr(border, " modulus with the same public and private exponent! Try your chance!", border) pr(border*72) nbit = 160 while True: pr("| Options: \n|\t[S]end the three nbit prime pairs \n|\t[Q]uit") ans = sc().lower() order = ['first', 'second', 'third'] if ans == 's': P, N = [], [] for i in range(3): pr("| Send the " + order[i] + " RSA primes such that nbit >= " + str(nbit) + ": p_" + str(i+1) + ", q_" + str(i+1) + " ") params = sc() try: p, q = params.split(',') p, q = int(p), int(q) except: die("| your primes are not valid!!") if isPrime(p) and isPrime(q) and len(bin(p)[2:]) >= nbit and len(bin(q)[2:]) >= nbit: P.append((p, q)) n = p * q N.append(n) else: die("| your input is not desired prime, Bye!") if len(set(N)) == 3: pr("| Send the public and private exponent: e, d ") params = sc() try: e, d = params.split(',') e, d = int(e), int(d) except: die("| your parameters are not valid!! Bye!!!") phi_1 = (P[0][0] - 1)*(P[0][1] - 1) phi_2 = (P[1][0] - 1)*(P[1][1] - 1) phi_3 = (P[2][0] - 1)*(P[2][1] - 1) if 1 < e < min([phi_1, phi_2, phi_3]) and 1 < d < min([phi_1, phi_2, phi_3]): b = (e * d % phi_1 == 1) and (e * d % phi_2 == 1) and (e * d % phi_3 == 1) if b: die("| You got the flag:", FLAG) else: die("| invalid exponents, bye!!!") else: die("| the exponents are too small or too large!") else: die("| kidding me?!!, bye!") elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/DoRSA/DoRSA.py
ctfs/Crypto/2021/DoRSA/DoRSA.py
#!/usr/bin/env python3 from Crypto.Util.number import * from math import gcd from flag import FLAG def keygen(nbit, dbit): assert 2*dbit < nbit while True: u, v = getRandomNBitInteger(dbit), getRandomNBitInteger(nbit // 2 - dbit) p = u * v + 1 if isPrime(p): while True: x, y = getRandomNBitInteger(dbit), getRandomNBitInteger(nbit // 2 - dbit) q = u * y + 1 r = x * y + 1 if isPrime(q) and isPrime(r): while True: e = getRandomNBitInteger(dbit) if gcd(e, u * v * x * y) == 1: phi = (p - 1) * (r - 1) d = inverse(e, phi) k = (e * d - 1) // phi s = k * v + 1 if isPrime(s): n_1, n_2 = p * r, q * s return (e, n_1, n_2) def encrypt(msg, pubkey): e, n = pubkey return pow(msg, e, n) nbit, dbit = 1024, 256 e, n_1, n_2 = keygen(nbit, dbit) FLAG = int(FLAG.encode("utf-8").hex(), 16) c_1 = encrypt(FLAG, (e, n_1)) c_2 = encrypt(FLAG, (e, n_2)) print('e =', e) print('n_1 =', n_1) print('n_2 =', n_2) print('enc_1 =', c_1) print('enc_2 =', c_2)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/hamul/hamul.py
ctfs/Crypto/2021/hamul/hamul.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag nbit = 64 while True: p, q = getPrime(nbit), getPrime(nbit) P = int(str(p) + str(q)) Q = int(str(q) + str(p)) PP = int(str(P) + str(Q)) QQ = int(str(Q) + str(P)) if isPrime(PP) and isPrime(QQ): break n = PP * QQ m = bytes_to_long(flag.encode('utf-8')) if m < n: c = pow(m, 65537, n) print('n =', n) print('c =', c)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/maid/maid.py
ctfs/Crypto/2021/maid/maid.py
#!/usr/bin/python3 from Crypto.Util.number import * from gmpy2 import * from secret import * from flag import flag global nbit nbit = 1024 def keygen(nbit): while True: p, q = [getStrongPrime(nbit) for _ in '01'] if p % 4 == q % 4 == 3: return (p**2)*q, p def encrypt(m, pubkey): if GCD(m, pubkey) != 1 or m >= 2**(2*nbit - 2): return None return pow(m, 2, pubkey) def flag_encrypt(flag, p, q): m = bytes_to_long(flag) assert m < p * q return pow(m, 65537, p * q) def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi all, welcome to Rooney Oracle, you can encrypt and decrypt any ", border) pr(border, " message in this oracle, but the flag is still encrypted, Rooney ", border) pr(border, " asked me to find the encrypted flag, I'm trying now, please help! ", border) pr(border*72) pubkey, privkey = keygen(nbit) p, q = privkey, pubkey // (privkey ** 2) while True: pr("| Options: \n|\t[E]ncrypt message \n|\t[D]ecrypt ciphertext \n|\t[S]how encrypted flag \n|\t[Q]uit") ans = sc().lower() if ans == 'e': pr("| Send the message to encrypt: ") msg = sc() try: msg = int(msg) except: die("| your message is not integer!!") pr(f"| encrypt(msg, pubkey) = {encrypt(msg, pubkey)} ") elif ans == 'd': pr("| Send the ciphertext to decrypt: ") enc = sc() try: enc = int(enc) except: die("| your message is not integer!!") pr(f"| decrypt(enc, privkey) = {decrypt(enc, privkey)} ") elif ans == 's': pr(f'| enc = {flag_encrypt(flag, p, q)}') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/tiny_ecc/tiny_ecc.py
ctfs/Crypto/2021/tiny_ecc/tiny_ecc.py
#!/usr/bin/env python3 # In the name of Allah from mini_ecdsa import * from Crypto.Util.number import * from flag import flag def tonelli_shanks(n, p): if pow(n, int((p-1)//2), p) == 1: s = 1 q = int((p-1)//2) while True: if q % 2 == 0: q = q // 2 s += 1 else: break if s == 1: r1 = pow(n, int((p+1)//4), p) r2 = p - r1 return r1, r2 else: z = 2 while True: if pow(z, int((p-1)//2), p) == p - 1: c = pow(z, q, p) break else: z += 1 r = pow(n, int((q+1)//2), p) t = pow(n, q, p) m = s while True: if t == 1: r1 = r r2 = p - r1 return r1, r2 else: i = 1 while True: if pow(t, 2**i, p) == 1: break else: i += 1 b = pow(c, 2**(m-i-1), p) r = r * b % p t = t * b ** 2 % p c = b ** 2 % p m = i else: return False def random_point(p, a, b): while True: gx = getRandomRange(1, p-1) n = (gx**3 + a*gx + b) % p gy = tonelli_shanks(n, p) if gy == False: continue else: return (gx, gy[0]) def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " Dual ECC means two elliptic curve with same coefficients over the ", border) pr(border, " different fields or ring! You should calculate the discrete log ", border) pr(border, " in dual ECCs. So be smart in choosing the first parameters! Enjoy!", border) pr(border*72) bool_coef, bool_prime, nbit = False, False, 128 while True: pr(f"| Options: \n|\t[C]hoose the {nbit}-bit prime p \n|\t[A]ssign the coefficients \n|\t[S]olve DLP \n|\t[Q]uit") ans = sc().lower() if ans == 'a': pr('| send the coefficients a and b separated by comma: ') COEFS = sc() try: a, b = [int(_) for _ in COEFS.split(',')] except: die('| your coefficients are not valid, Bye!!') if a*b == 0: die('| Kidding me?!! a*b should not be zero!!') else: bool_coef = True elif ans == 'c': pr('| send your prime: ') p = sc() try: p = int(p) except: die('| your input is not valid :(') if isPrime(p) and p.bit_length() == nbit and isPrime(2*p + 1): q = 2*p + 1 bool_prime = True else: die(f'| your integer p is not {nbit}-bit prime or 2p + 1 is not prime, bye!!') elif ans == 's': if bool_coef == False: pr('| please assign the coefficients.') if bool_prime == False: pr('| please choose your prime first.') if bool_prime and bool_coef: Ep = CurveOverFp(0, a, b, p) Eq = CurveOverFp(0, a, b, q) xp, yp = random_point(p, a, b) P = Point(xp, yp) xq, yq = random_point(q, a, b) Q = Point(xq, yq) k = getRandomRange(1, p >> 1) kP = Ep.mult(P, k) l = getRandomRange(1, q >> 1) lQ = Eq.mult(Q, l) pr('| We know that: ') pr(f'| P = {P}') pr(f'| k*P = {kP}') pr(f'| Q = {Q}') pr(f'| l*Q = {lQ}') pr('| send the k and l separated by comma: ') PRIVS = sc() try: priv, qriv = [int(s) for s in PRIVS.split(',')] except: die('| your input is not valid, Bye!!') if priv == k and qriv == l: die(f'| Congrats, you got the flag: {flag}') else: die('| sorry, your keys are not correct! Bye!!!') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/tiny_ecc/mini_ecdsa.py
ctfs/Crypto/2021/tiny_ecc/mini_ecdsa.py
#Elliptic curve basics, tools for finding rational points, and ECDSA implementation. #Brendan Cordy, 2015 from fractions import Fraction from math import ceil, sqrt from random import SystemRandom, randrange from hashlib import sha256 from time import time #Useful constant. The order of the subgroup defined in the secp256k1 standard. secp256k1_order = 115792089237316195423570985008687907852837564279074904382605163141518161494337 #Affine Point (+Infinity) on an Elliptic Curve --------------------------------------------------- class Point(object): #Construct a point with two given coordindates. def __init__(self, x, y): self.x, self.y = x, y self.inf = False #Construct the point at infinity. @classmethod def atInfinity(cls): P = cls(0, 0) P.inf = True return P #The secp256k1 generator. @classmethod def secp256k1(cls): return cls(55066263022277343669578718895168534326250603453777594175500187360389116729240, 32670510020758816978083085130507043184471273380659243275938904335757337482424) def __str__(self): if self.inf: return 'Inf' else: return '(' + str(self.x) + ',' + str(self.y) + ')' def __eq__(self,other): if self.inf: return other.inf elif other.inf: return self.inf else: return self.x == other.x and self.y == other.y def is_infinite(self): return self.inf #Elliptic Curves over any Field ------------------------------------------------------------------ class Curve(object): #Set attributes of a general Weierstrass cubic y^2 = x^3 + ax^2 + bx + c over any field. def __init__(self, a, b, c, char, exp): self.a, self.b, self.c = a, b, c self.char, self.exp = char, exp print(self) def __str__(self): #Cases for 0, 1, -1, and general coefficients in the x^2 term. if self.a == 0: aTerm = '' elif self.a == 1: aTerm = ' + x^2' elif self.a == -1: aTerm = ' - x^2' elif self.a < 0: aTerm = " - " + str(-self.a) + 'x^2' else: aTerm = " + " + str(self.a) + 'x^2' #Cases for 0, 1, -1, and general coefficients in the x term. if self.b == 0: bTerm = '' elif self.b == 1: bTerm = ' + x' elif self.b == -1: bTerm = ' - x' elif self.b < 0: bTerm = " - " + str(-self.b) + 'x' else: bTerm = " + " + str(self.b) + 'x' #Cases for 0, 1, -1, and general coefficients in the constant term. if self.c == 0: cTerm = '' elif self.c < 0: cTerm = " - " + str(-self.c) else: cTerm = " + " + str(self.c) #Write out the nicely formatted Weierstrass equation. self.eq = 'y^2 = x^3' + aTerm + bTerm + cTerm #Print prettily. if self.char == 0: return self.eq + ' over Q' elif self.exp == 1: return self.eq + ' over ' + 'F_' + str(self.char) else: return self.eq + ' over ' + 'F_' + str(self.char) + '^' + str(self.exp) #Compute the discriminant. def discriminant(self): a, b, c = self.a, self.b, self.c return -4*a*a*a*c + a*a*b*b + 18*a*b*c - 4*b*b*b - 27*c*c #Compute the order of a point on the curve. def order(self, P): Q = P orderP = 1 #Add P to Q repeatedly until obtaining the identity (point at infinity). while not Q.is_infinite(): Q = self.add(P,Q) orderP += 1 return orderP #List all multiples of a point on the curve. def generate(self, P): Q = P orbit = [str(Point.atInfinity())] #Repeatedly add P to Q, appending each (pretty printed) result. while not Q.is_infinite(): orbit.append(str(Q)) Q = self.add(P,Q) return orbit #Double a point on the curve. def double(self, P): return self.add(P,P) #Add P to itself k times. def mult(self, P, k): if P.is_infinite(): return P elif k == 0: return Point.atInfinity() elif k < 0: return self.mult(self.invert(P), -k) else: #Convert k to a bitstring and use peasant multiplication to compute the product quickly. b = bin(k)[2:] return self.repeat_additions(P, b, 1) #Add efficiently by repeatedly doubling the given point, and adding the result to a running #total when, after the ith doubling, the ith digit in the bitstring b is a one. def repeat_additions(self, P, b, n): if b == '0': return Point.atInfinity() elif b == '1': return P elif b[-1] == '0': return self.repeat_additions(self.double(P), b[:-1], n+1) elif b[-1] == '1': return self.add(P, self.repeat_additions(self.double(P), b[:-1], n+1)) #Returns a pretty printed list of points. def show_points(self): return [str(P) for P in self.get_points()] #Elliptic Curves over Q -------------------------------------------------------------------------- class CurveOverQ(Curve): #Construct a Weierstrass cubic y^2 = x^3 + ax^2 + bx + c over Q. def __init__(self, a, b, c): Curve.__init__(self, a, b, c, 0, 0) def contains(self, P): if P.is_infinite(): return True else: return P.y*P.y == P.x*P.x*P.x + self.a*P.x*P.x + self.b*P.x + self.c def get_points(self): #Start with the point at infinity. points = [Point.atInfinity()] #The only possible y values are divisors of the discriminant. for y in divisors(self.discriminant()): #Each possible y value yields a monic cubic polynomial in x, whose roots #must divide the constant term. const_term = self.c - y*y if const_term != 0: for x in divisors(const_term): P = Point(x,y) if 0 == x*x*x + self.a*x*x + self.b*x + const_term and self.has_finite_order(P): points.append(P) #If the constant term is zero, factor out x and look for rational roots #of the resulting quadratic polynomial. Any such roots must divide b. elif self.b != 0: for x in divisors(self.b): P = Point(x,y) if 0 == x*x*x+self.a*x*x+self.b*x+const_term and self.has_finite_order(P): points.append(P) #If the constant term and b are both zero, factor out x^2 and look for rational #roots of the resulting linear polynomial. Any such roots must divide a. elif self.a != 0: for x in divisors(self.a): P = Point(x,y) if 0 == x*x*x+self.a*x*x+self.b*x+const_term and self.has_finite_order(P): points.append(P) #If the constant term, b, and a are all zero, we have 0 = x^3 + c - y^2 with #const_term = c - y^2 = 0, so (0,y) is a point on the curve. else: points.append(Point(0,y)) #Ensure that there are no duplicates in our list of points. unique_points = [] for P in points: addP = True for Q in unique_points: if P == Q: addP = False if addP: unique_points.append(P) return unique_points def invert(self, P): if P.is_infinite(): return P else: return Point(P.x, -P.y) def add(self, P_1, P_2): #Compute the differences in the coordinates. y_diff = P_2.y - P_1.y x_diff = P_2.x - P_1.x #Cases involving the point at infinity. if P_1.is_infinite(): return P_2 elif P_2.is_infinite(): return P_1 #Case for adding an affine point to its inverse. elif x_diff == 0 and y_diff != 0: return Point.atInfinity() #Case for adding an affine point to itself. elif x_diff == 0 and y_diff == 0: #If the point is on the x-axis, there's a vertical tangent there (assuming #the curve in nonsingular) so we obtain the point at infinity. if P_1.y == 0: return Point.atInfinity() #Otherwise the result is an affine point on the curve we can arrive at by #following the tangent line, whose slope is given below. else: ld = Fraction(3*P_1.x*P_1.x + 2*self.a*P_1.x + self.b, 2*P_1.y) #Case for adding two distinct affine points, where we compute the slope of #the secant line through the two points. else: ld = Fraction(y_diff, x_diff) #Use the slope of the tangent line or secant line to compute the result. nu = P_1.y - ld*P_1.x x = ld*ld - self.a -P_1.x - P_2.x y = -ld*x - nu return Point(x,y) #Use the Nagell-Lutz Theorem and Mazur's Theorem to potentially save time. def order(self, P): Q = P orderP = 1 #Add P to Q repeatedly until obtaining the point at infinity. while not Q.is_infinite(): Q = self.add(P,Q) orderP += 1 #If we ever obtain non integer coordinates, the point has infinite order. if Q.x != int(Q.x) or Q.y != int(Q.y): return -1 #Moreover, all finite order points have order at most 12. if orderP > 12: return -1 return orderP def has_finite_order(self, P): return not self.order(P) == -1 def torsion_group(self): highest_order = 1 #Find the rational point with the highest order. for P in self.get_points(): if self.order(P) > highest_order: highest_order = self.order(P) #If this point generates the entire torsion group, the torsion group is cyclic. if highest_order == len(self.get_points()): print('Z/' + str(highest_order) + 'Z') #If not, by Mazur's Theorem the torsion group must be a direct product of Z/2Z #with the cyclic group generated by the highest order point. else: print('Z/2Z x ' + 'Z/' + str(highest_order) + 'Z') print(C.show_points()) #Elliptic Curves over Prime Order Fields --------------------------------------------------------- class CurveOverFp(Curve): #Construct a Weierstrass cubic y^2 = x^3 + ax^2 + bx + c over Fp. def __init__(self, a, b, c, p): Curve.__init__(self, a, b, c, p, 1) #The secp256k1 curve. @classmethod def secp256k1(cls): return cls(0, 0, 7, 2**256-2**32-2**9-2**8-2**7-2**6-2**4-1) def contains(self, P): if P.is_infinite(): return True else: return (P.y*P.y) % self.char == (P.x*P.x*P.x + self.a*P.x*P.x + self.b*P.x + self.c) % self.char def get_points(self): #Start with the point at infinity. points = [Point.atInfinity()] #Just brute force the rest. for x in range(self.char): for y in range(self.char): P = Point(x,y) if (y*y) % self.char == (x*x*x + self.a*x*x + self.b*x + self.c) % self.char: points.append(P) return points def invert(self, P): if P.is_infinite(): return P else: return Point(P.x, -P.y % self.char) def add(self, P_1, P_2): #Adding points over Fp and can be done in exactly the same way as adding over Q, #but with of the all arithmetic now happening in Fp. y_diff = (P_2.y - P_1.y) % self.char x_diff = (P_2.x - P_1.x) % self.char if P_1.is_infinite(): return P_2 elif P_2.is_infinite(): return P_1 elif x_diff == 0 and y_diff != 0: return Point.atInfinity() elif x_diff == 0 and y_diff == 0: if P_1.y == 0: return Point.atInfinity() else: ld = ((3*P_1.x*P_1.x + 2*self.a*P_1.x + self.b) * mult_inv(2*P_1.y, self.char)) % self.char else: ld = (y_diff * mult_inv(x_diff, self.char)) % self.char nu = (P_1.y - ld*P_1.x) % self.char x = (ld*ld - self.a - P_1.x - P_2.x) % self.char y = (-ld*x - nu) % self.char return Point(x,y) #Elliptic Curves over Prime Power Order Fields --------------------------------------------------- class CurveOverFq(Curve): #Construct a Weierstrass cubic y^2 = x^3 + ax^2 + bx + c over Fp^n. def __init__(self, a, b, c, p, n, irred_poly): self.irred_poly = irred_poly Curve.__init__(self, a, b, c, p, n) #TODO: Implement it! #Number Theoretic Functions ---------------------------------------------------------------------- def divisors(n): divs = [0] for i in range(1, abs(n) + 1): if n % i == 0: divs.append(i) divs.append(-i) return divs #Extended Euclidean algorithm. def euclid(sml, big): #When the smaller value is zero, it's done, gcd = b = 0*sml + 1*big. if sml == 0: return (big, 0, 1) else: #Repeat with sml and the remainder, big%sml. g, y, x = euclid(big % sml, sml) #Backtrack through the calculation, rewriting the gcd as we go. From the values just #returned above, we have gcd = y*(big%sml) + x*sml, and rewriting big%sml we obtain #gcd = y*(big - (big//sml)*sml) + x*sml = (x - (big//sml)*y)*sml + y*big. return (g, x - (big//sml)*y, y) #Compute the multiplicative inverse mod n of a with 0 < a < n. def mult_inv(a, n): g, x, y = euclid(a, n) #If gcd(a,n) is not one, then a has no multiplicative inverse. if g != 1: raise ValueError('multiplicative inverse does not exist') #If gcd(a,n) = 1, and gcd(a,n) = x*a + y*n, x is the multiplicative inverse of a. else: return x % n #ECDSA functions --------------------------------------------------------------------------------- #Use sha256 to hash a message, and return the hash value as an integer. def hash(message): return int(sha256(message.encode('utf-8')).hexdigest(), 16) #Hash the message and return integer whose binary representation is the the L leftmost bits #of the hash value, where L is the bit length of n. def hash_and_truncate(message, n): h = hash(message) b = bin(h)[2:len(bin(n))] return int(b, 2) #Generate a keypair using the point P of order n on the given curve. The private key is a #positive integer d smaller than n, and the public key is Q = dP. def generate_keypair(curve, P, n): sysrand = SystemRandom() d = sysrand.randrange(1, n) Q = curve.mult(P, d) print("Priv key: d = " + str(d)) print("Publ key: Q = " + str(Q)) return (d, Q) #Create a digital signature for the string message using a given curve with a distinguished #point P which generates a prime order subgroup of size n. def sign(message, curve, P, n, keypair): #Extract the private and public keys, and compute z by hashing the message. d, Q = keypair z = hash_and_truncate(message, n) #Choose a randomly selected secret point kP then compute r and s. r, s = 0, 0 while r == 0 or s == 0: sysrand = SystemRandom() k = sysrand.randrange(1, n) R = curve.mult(P, k) r = R.x % n s = (mult_inv(k, n) * (z + r*d)) % n print('ECDSA sig: (Q, r, s) = (' + str(Q) + ', ' + str(r) + ', ' + str(s) + ')') return (Q, r, s) #Verify the string message is authentic, given an ECDSA signature generated using a curve with #a distinguished point P that generates a prime order subgroup of size n. def verify(message, curve, P, n, sig): Q, r, s = sig #Confirm that Q is on the curve. if Q.is_infinite() or not curve.contains(Q): return False #Confirm that Q has order that divides n. if not curve.mult(Q,n).is_infinite(): return False #Confirm that r and s are at least in the acceptable range. if r > n or s > n: return False #Compute z in the same manner used in the signing procedure, #and verify the message is authentic. z = hash_and_truncate(message, n) w = mult_inv(s, n) % n u_1, u_2 = z * w % n, r * w % n C_1, C_2 = curve.mult(P, u_1), curve.mult(Q, u_2) C = curve.add(C_1, C_2) return r % n == C.x % n #Key Cracking Functions -------------------------------------------------------------------------- #Find d for which Q = dP by simply trying all possibilities def crack_brute_force(curve, P, n, Q): start_time = time() for d in range(n): if curve.mult(P,d) == Q: end_time = time() print("Priv key: d = " + str(d)) print("Time: " + str(round(end_time - start_time, 3)) + " secs") break #Find d for which Q = dP using the baby-step giant-step algortihm. def crack_baby_giant(curve, P, n, Q): start_time = time() m = int(ceil(sqrt(n))) #Build a hash table with all bP with 0 < b < m using a dictionary. The dicitonary value #stores b so that it can be quickly recovered after a matching giant step hash. baby_table = {} for b in range(m): bP = curve.mult(P,b) baby_table[str(bP)] = b #Check if Q - gmP is in the hash table for all 0 < g < m. If we get such a matching hash, #we have Q - gmP = bP, so extract b from the dictionary, then Q = (b + gm)P. for g in range(m): R = curve.add(Q, curve.invert(curve.mult(P, g*m))) if str(R) in baby_table.keys(): b = baby_table[str(R)] end_time = time() print("Priv key: d = " + str((b + g*m) % n)) print("Time: " + str(round(end_time - start_time, 3)) + " secs") break #Find d for which Q = dP using Pollard's rho algorithm. Assumes subgroup has prime order n. def crack_rho(curve, P, n, Q, bits): start_time = time() R_list = [] #Compute 2^bits randomly selected linear combinations of P and Q, storing them as triples #of the form (aP + bQ, a, b) in R_list. for i in range(2**bits): a, b = randrange(0,n), randrange(0,n) R_list.append((curve.add(curve.mult(P,a), curve.mult(Q,b)), a, b)) #Compute a new random linear combination of P and Q to start the cycle-finding. aT, bT = randrange(0,n), randrange(0,n) aH, bH = aT, bT T = curve.add(curve.mult(P,aT), curve.mult(Q,bT)) H = curve.add(curve.mult(P,aH), curve.mult(Q,bH)) while True: #Advance the tortoise one step, by adding a point in R_list determined by the last b #bits in the binary explansion of the x coordinate of the current position. j = int(bin(T.x)[len(bin(T.x)) - bits : len(bin(T.x))], 2) T, aT, bT = curve.add(T, R_list[j][0]), (aT + R_list[j][1]) % n, (bT + R_list[j][2]) % n #Advance the hare two steps, again by adding points in R_list determined by the last #b bits in the binary explansion of the x coordinate of the current position. for i in range(2): j = int(bin(H.x)[len(bin(H.x)) - bits : len(bin(H.x))], 2) H, aH, bH = curve.add(H, R_list[j][0]), (aH + R_list[j][1]) % n, (bH + R_list[j][2]) % n #If the tortoise and hare arrive at the same point, a cycle has been found. if(T == H): break #It is possible that the tortoise and hare arrive at exactly the same linear combination. if bH == bT: end_time = time() print("Rho failed with identical linear combinations") print(str(end_time - start_time) + " secs") else: end_time = time() print("Priv key: d = " + str((aT - aH) * mult_inv((bH - bT) % n, n) % n)) print("Time: " + str(round(end_time - start_time, 3)) + " secs") #Find d from two messages signed with the same nonce k. Assumes subgroup has prime order n. def crack_from_ECDSA_repeat_k(curve, P, n, m1, sig1, m2, sig2): Q1, r1, s1 = sig1 Q2, r2, s2 = sig2 #Check that the two messages were signed with the same k. This check may pass even if m1 #and m2 were signed with distinct k, in which case the value of d computed below will be #wrong, but this is a very unlikely scenario. if not r1 == r2: print("Messages signed with distinct k") else: z1 = hash_and_truncate(m1, n) z2 = hash_and_truncate(m2, n) k = (z1 - z2) * mult_inv((s1 - s2) % n, n) % n d = mult_inv(r1, n) * ((s1 * k) % n - z1) % n print("Priv key: d = " + str(d))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/lower/lower.py
ctfs/Crypto/2021/lower/lower.py
#!/usr/bin/env python3 from Crypto.Util.number import * import sys from flag import flag flag = flag.lstrip('CCTF{').rstrip('}') def query(n, X, E, p): assert n == len(X) > len(E) C = [getRandomRange(0, p) for _ in range(n)] e = E[getRandomRange(0, len(E))] S = e for _ in range(n): S += X[_] * C[_] S %= p return C, S def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi all, welcome to the learning by mistakes class of cryptography! ", border) pr(border, " try hard to find the flag by querying this oracle times and times!!", border) pr(border*72) p = 127 E = [getRandomRange(0, p) for _ in range(5)] n = len(flag) X = [ord(c) for c in flag] while True: pr("| Options: \n|\t[Q]uery to oracle \n|\t[E]xit") ans = sc().lower() if ans == 'q': for i in range(12): pr(f'| Q_{i+1}: {query(n, X, E, p)}') elif ans == 'e': die("Exiting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/Tuti/tuti.py
ctfs/Crypto/2021/Tuti/tuti.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag l = len(flag) m_1, m_2 = flag[: l // 2], flag[l // 2:] x, y = bytes_to_long(m_1), bytes_to_long(m_2) k = ''' 000bfdc32162934ad6a054b4b3db8578674e27a165113f8ed018cbe9112 4fbd63144ab6923d107eee2bc0712fcbdb50d96fdf04dd1ba1b69cb1efe 71af7ca08ddc7cc2d3dfb9080ae56861d952e8d5ec0ba0d3dfdf2d12764 '''.replace('\n', '') assert((x**2 + 1)*(y**2 + 1) - 2*(x - y)*(x*y - 1) == 4*(int(k, 16) + x*y))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/elegant_curve/elegant_curve.py
ctfs/Crypto/2021/elegant_curve/elegant_curve.py
#!/usr/bin/env python3 from Crypto.Util.number import * import sys from flag import flag def tonelli_shanks(n, p): if pow(n, int((p-1)//2), p) == 1: s = 1 q = int((p-1)//2) while True: if q % 2 == 0: q = q // 2 s += 1 else: break if s == 1: r1 = pow(n, int((p+1)//4), p) r2 = p - r1 return r1, r2 else: z = 2 while True: if pow(z, int((p-1)//2), p) == p - 1: c = pow(z, q, p) break else: z += 1 r = pow(n, int((q+1)//2), p) t = pow(n, q, p) m = s while True: if t == 1: r1 = r r2 = p - r1 return r1, r2 else: i = 1 while True: if pow(t, 2**i, p) == 1: break else: i += 1 b = pow(c, 2**(m-i-1), p) r = r * b % p t = t * b ** 2 % p c = b ** 2 % p m = i else: return False def add(A, B, p): if A == 0: return B if B == 0: return A l = ((B[1] - A[1]) * inverse(B[0] - A[0], p)) % p x = (l*l - A[0] - B[0]) % p y = (l*(A[0] - x) - A[1]) % p return (int(x), int(y)) def double(G, a, p): if G == 0: return G l = ((3*G[0]*G[0] + a) * inverse(2*G[1], p)) % p x = (l*l - 2*G[0]) % p y = (l*(G[0] - x) - G[1]) % p return (int(x), int(y)) def multiply(point, exponent, a, p): r0 = 0 r1 = point for i in bin(exponent)[2:]: if i == '0': r1 = add(r0, r1, p) r0 = double(r0, a, p) else: r0 = add(r0, r1, p) r1 = double(r1, a, p) return r0 def random_point(a, b, p): while True: x = getRandomRange(1, p-1) try: y, _ = tonelli_shanks((x**3 + a*x + b) % p, p) return (x, y) except: continue def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi talented cryptographers, the mission is decrypt a secret message", border) pr(border, " with given parameters for two elliptic curve, so be genius and send", border) pr(border, " suitable parameters, now try to get the flag! ", border) pr(border*72) nbit = 160 while True: pr("| Options: \n|\t[S]end ECC parameters and solve the task \n|\t[Q]uit") ans = sc().lower() if ans == 's': pr("| Send the parameters of first ECC y^2 = x^3 + ax + b like: a, b, p ") params = sc() try: a, b, p = params.split(',') a, b, p = int(a), int(b), int(p) except: die("| your parameters are not valid!!") if isPrime(p) and 0 < a < p and 0 < b < p and p.bit_length() == nbit: pr("| Send the parameters of second ECC y^2 = x^3 + cx + d like: c, d, q ") pr("| such that 0 < q - p <= 2022") params = sc() try: c, d, q = params.split(',') c, d, q = int(c), int(d), int(q) except: die("| your parameters are not valid!!") if isPrime(q) and 0 < c < q and 0 < d < q and 0 < q - p <= 2022 and q.bit_length() == nbit: G, H = random_point(a, b, p), random_point(c, d, q) r, s = [getRandomRange(1, p-1) for _ in range(2)] pr(f"| G is on first ECC and G =", {G}) pr(f"| H is on second ECC and H =", {H}) U = multiply(G, r, a, p) V = multiply(H, s, c, q) pr(f"| r * G =", {U}) pr(f"| s * H =", {V}) pr("| Send r, s to get the flag: ") rs = sc() try: u, v = rs.split(',') u, v = int(u), int(v) except: die("| invalid input, bye!") if u == r and v == s: die("| You got the flag:", flag) else: die("| the answer is not correct, bye!") else: die("| invalid parameters, bye!") else: die("| invalid parameters, bye!") elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/Rima/rima.py
ctfs/Crypto/2021/Rima/rima.py
#!/usr/bin/env python from Crypto.Util.number import * from flag import FLAG def nextPrime(n): while True: n += (n % 2) + 1 if isPrime(n): return n f = [int(x) for x in bin(int(FLAG.hex(), 16))[2:]] f.insert(0, 0) for i in range(len(f)-1): f[i] += f[i+1] a = nextPrime(len(f)) b = nextPrime(a) g, h = [[_ for i in range(x) for _ in f] for x in [a, b]] c = nextPrime(len(f) >> 2) for _ in [g, h]: for __ in range(c): _.insert(0, 0) for i in range(len(_) - c): _[i] += _[i+c] g, h = [int(''.join([str(_) for _ in __]), 5) for __ in [g, h]] for _ in [g, h]: if _ == g: fname = 'g' else: fname = 'h' of = open(f'{fname}.enc', 'wb') of.write(long_to_bytes(_)) of.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/frozen/frozen_server.py
ctfs/Crypto/2021/frozen/frozen_server.py
#!/usr/bin/env python3 from Crypto.Util.number import * from gmpy2 import * import sys, random, string from flag import FLAG def genrandstr(N): return ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(N)) def paramaker(nbit): p = getPrime(nbit) r = getRandomRange(1, p) return p, r def keygen(params, l, d): p, r = params s = getRandomRange(1, p) U = [pow(r, c + 1, p) * s % p for c in range(0,l)] V = [int(bin(u)[2:][:-d] + '0' * d, 2) for u in U] S = [int(bin(u)[2:][-d:], 2) for u in U] privkey, pubkey = S, V return pubkey, privkey def sign(msg, privkey, d): msg = msg.encode('utf-8') l = len(msg) // 4 M = [bytes_to_long(msg[4*i:4*(i+1)]) for i in range(l)] q = int(next_prime(max(M))) sign = [M[i]*privkey[i] % q for i in range(l)] return sign def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi young cryptographers, welcome to the frozen signature battle!! ", border) pr(border, " Your mission is to forge the signature for a given message, ready?!", border) pr(border*72) randstr = genrandstr(20) nbit, dbit = 128, 32 params = paramaker(nbit) l = 5 pubkey, privkey = keygen(params, l, dbit) while True: pr("| Options: \n|\t[S]how the params \n|\t[P]rint pubkey \n|\t[E]xample signature \n|\t[F]orge the signature \n|\t[Q]uit") ans = sc().lower() if ans == 's': pr(f'| p = {params[0]}') pr(f'| r = {params[1]}') elif ans == 'p': pr(f'pubkey = {pubkey}') elif ans == 'e': pr(f'| the signature for "{randstr}" is :') pr(f'| signature = {sign(randstr, privkey, dbit)}') elif ans == 'f': randmsg = genrandstr(20) pr(f'| send the signature of the following message like example: {randmsg}') SIGN = sc() try: SIGN = [int(s) for s in SIGN.split(',')] except: die('| your signature is not valid! Bye!!') if SIGN == sign(randmsg, privkey, dbit): die(f'| Congrats, you got the flag: {FLAG}') else: die(f'| Your signature is not correct, try later! Bye!') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2021/keybase/keybase.py
ctfs/Crypto/2021/keybase/keybase.py
#!/usr/bin/env python3 from Crypto.Util import number from Crypto.Cipher import AES import os, sys, random from flag import flag def keygen(): iv, key = [os.urandom(16) for _ in '01'] return iv, key def encrypt(msg, iv, key): aes = AES.new(key, AES.MODE_CBC, iv) return aes.encrypt(msg) def decrypt(enc, iv, key): aes = AES.new(key, AES.MODE_CBC, iv) return aes.decrypt(enc) def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi all, welcome to the simple KEYBASE cryptography task, try to ", border) pr(border, " decrypt the encrypted message and get the flag as a nice prize! ", border) pr(border*72) iv, key = keygen() flag_enc = encrypt(flag, iv, key).hex() while True: pr("| Options: \n|\t[G]et the encrypted flag \n|\t[T]est the encryption \n|\t[Q]uit") ans = sc().lower() if ans == 'g': pr("| encrypt(flag) =", flag_enc) elif ans == 't': pr("| Please send your 32 bytes message to encrypt: ") msg_inp = sc() if len(msg_inp) == 32: enc = encrypt(msg_inp, iv, key).hex() r = random.randint(0, 4) s = 4 - r mask_key = key[:-2].hex() + '*' * 4 mask_enc = enc[:r] + '*' * 28 + enc[32-s:] pr("| enc =", mask_enc) pr("| key =", mask_key) else: die("| SEND 32 BYTES MESSAGE :X") elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Risk/risk.py
ctfs/Crypto/2023/Risk/risk.py
#!/usr/bin/env python3 from Crypto.Util.number import * from secret import m, flag def genPrime(m, nbit): assert m >= 2 while True: a = getRandomNBitInteger(nbit // m) r = getRandomNBitInteger(m ** 2 - m + 2) p = a ** m + r if isPrime(p): return (p, r) def genkey(m, nbit): p, r = genPrime(m, nbit // 2) q, s = genPrime(m, nbit // 2) n = p * q e = r * s return (e, n) def encrypt(msg, pkey): e, n = pkey m = bytes_to_long(msg) c = pow(m, e, n) return c pkey = genkey(m, 2048) enc = encrypt(flag, pkey) print(f'pkey = {pkey}') print(f'enc = {enc}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Resuction/resuction.py
ctfs/Crypto/2023/Resuction/resuction.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag from decimal import * def keygen(nbit, r): while True: p, q = [getPrime(nbit) for _ in '__'] d, n = getPrime(64), p * q phi = (p - 1) * (q - 1) if GCD(d, phi) == 1: e = inverse(d, phi) N = bin(n)[2:-r] E = bin(e)[2:-r] PKEY = N + E pkey = (n, e) return PKEY, pkey def encrypt(msg, pkey, r): m = bytes_to_long(msg) n, e = pkey c = pow(m, e, n) C = bin(c)[2:-r] return C r, nbit = 8, 1024 PKEY, pkey = keygen(nbit, r) print(f'PKEY = {int(PKEY, 2)}') FLAG = flag.lstrip(b'CCTF{').rstrip(b'}') enc = encrypt(FLAG, pkey, r) print(f'enc = {int(enc, 2)}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Trex/trex.py
ctfs/Crypto/2023/Trex/trex.py
#!/usr/bin/env python3 import random import sys from flag import flag def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.buffer.readline() def check_inputs(a, b, c): if not all(isinstance(x, int) for x in [a, b, c]): return False if a == 0 or b == 0 or c == 0: return False if a == b or b == c or a == c: return False return True def check_solution(a, x, y, z): return (x*x + y*y - x*y - a*(z**3)) == 0 def main(): border = "|" pr(border*72) pr(border, ".:: Hi all, she DID it, you should do it too! Are you ready? ::. ", border) pr(border, "Welcome to the Ternary World! You need to pass each level until 20 ", border) pr(border, "to get the flag. Pay attention that your solutions should be nonzero", border) pr(border, "distinct integers. Let's start! ", border) pr(border*72) level, step = 0, 19 while level <= step: a = random.randint(2**(level * 12), 2**(level*12 + 12)) equation = f'x^2 + y^2 - xy = {a}*z^3' pr(f"Level {level + 1}: {equation}") inputs = input().strip().split(",") try: x, y, z = map(int, inputs) except: die(border, "Invalid input, Bye!!") if check_inputs(x, y, z): if check_solution(a, x, y, z): pr(border, "Correct! Try the next level :)") level += 1 else: pr(border, "You didn't provide the correct solution.") die(border, "Better luck next time!") else: pr(border, "Your solutions should be non-zero distinct integers") die(border, "Quiting...") if level == step: pr(border, "Congratulations! You've successfully solved all the equations!") die(border, f"flag: {flag}") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Bertrand/Bertrand.py
ctfs/Crypto/2023/Bertrand/Bertrand.py
#!/usr/bin/env python3 import sys import math import functools from PIL import Image from random import randint import string from secret import flag, key, n def pad(s, l): while len(s) < l: s += string.printable[randint(0, 61)] return s def sox(n, d): x, y, t = 0, 0, d for s in range(n - 1): u = 1 & t // 2 v = 1 & t ^ u x, y = spin(2**s, x, y, u, v) x += 2**s * u y += 2**s * v t = t // 4 return x, y def spin(n, x, y, u, v): if v == 0: if u == 1: x = n - 1 - x y = n - 1 - y x, y = y, x return x, y def encrypt(msg, key, n): _msg = pad(msg, n ** 2) _msg, _key = [ord(_) for _ in _msg], [ord(_) for _ in key] img = Image.new('RGBA', (n, n), 'darkblue') pix = img.load() for _ in range(len(key)): w = len(_key) h = n**2 // w + 1 arr = [[_msg[w*x + y] if w*x + y < n**2 else None for x in range(h)] for y in range(w)] _conf = sorted([(_key[i], i) for i in range(w)]) _marshal = [arr[_conf[i][1]] for i in range(w)] _msg = functools.reduce(lambda a, r: a + _marshal[r], range(w), []) _msg = list(filter(lambda x: x is not None, _msg)) _msg = [(_msg[_] + _key[_ % w]) % 256 for _ in range(n**2)] for d in range(n**2): x, y = sox(n, d) pix[x,y] = (_msg[d], _msg[d], _msg[d]) keysum = sum(_key) if w > 0 else 0 orient = keysum % 4 img = img.rotate(90*orient) return img assert len(key) == 3 img = encrypt(flag, key, n) img.save('enc.png')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/ASIv2/ASIv2.py
ctfs/Crypto/2023/ASIv2/ASIv2.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag def base(n, l): D = [] while n > 0: n, r = divmod(n, l) D.append(r) return ''.join(str(d) for d in reversed(D)) or '0' def asiv_prng(seed): l = len(seed) _seed = base(bytes_to_long(seed), 3) _l = len(_seed) R = [[getRandomRange(0, 3) for _ in range(_l)] for _ in range(_l**2)] S = [] for r in R: s = 0 for _ in range(_l): b = ((int(r[_]) + int(_seed[_])) % 3) % 2 s = s ^ b S.append(s) print(len(S)) return R, S seed = flag.lstrip(b'CCTF{').rstrip(b'}') R, S = asiv_prng(seed) f = open('output.txt', 'w') f.write(f'R = {R}\nS = {S}') f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Blue_Office/blue_office.py
ctfs/Crypto/2023/Blue_Office/blue_office.py
#!/usr/bin/enc python3 import binascii from secret import seed, flag def gen_seed(s): i, j, k = 0, len(s), 0 while i < j: k = k + ord(s[i]) i += 1 i = 0 while i < j: if (i % 2) != 0: k = k - (ord(s[i]) * (j - i + 1)) else: k = k + (ord(s[i]) * (j - i + 1)) k = k % 2147483647 i += 1 k = (k * j) % 2147483647 return k def reseed(s): return s * 214013 + 2531011 def encrypt(s, msg): assert s <= 2**32 c, d = 0, s enc, l = b'', len(msg) while c < l: d = reseed(d) enc += (msg[c] ^ ((d >> 16) & 0xff)).to_bytes(1, 'big') c += 1 return enc enc = encrypt(seed, flag) print(f'enc = {binascii.hexlify(enc)}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Vinefruit/vinefruit.py
ctfs/Crypto/2023/Vinefruit/vinefruit.py
#!/usr/bin/env python3 import sys import random import binascii from flag import flag def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.buffer.readline() def vinefruit(msg, mod, flag = 0): P = [16777619, 1099511628211, 309485009821345068724781371] O = [2166136261, 14695981039346656037, 144066263297769815596495629667062367629] assert mod in [0, 1, 2] p, o, m = P[mod], O[mod], 2 ** (2 << (4 + mod)) vine = o for b in msg: if flag == 1: vine = (vine + b) % (2 ** 128) else: vine = vine ^ b vine = (vine * p) % m return vine def main(): border = "|" pr(border*72) pr(border, " Hi all, I have designed a gorgeous cryptography hash function in ", border) pr(border, " order to secure the world! Your mission is to find collision for ", border) pr(border, " this function with specific conditions. ", border) pr(border*72) step = 19 while True: pr("| Options: \n|\t[S]ubmit collision \n|\t[Q]uit") ans = sc().decode().lower().strip() if ans == 's': S = [] for level in range(step): mod = random.randint(0, 2) pr(border, f'Submit two different string such that vinefruit(m1, {mod}, 1) = vinefruit(m2, {mod}, 1)') pr(border, f'You are at level: {level + 1}') if level == step - 1 and len(S) == step - 1: die(border, f'Congrats, you got the flag: {flag}') try: pr(border, f'Please send first byte string: ') s1 = sc()[:-1] pr(border, f'Please send second byte string: ') s2 = sc()[:-1] s1, s2 = binascii.unhexlify(s1), binascii.unhexlify(s2) except: pr(border, 'You should send valid hex strings.') break if len(s1) == len(s2) == 35 - level and s1 != s2: if vinefruit(s1, mod, 1) == vinefruit(s2, mod, 1): if vinefruit(s1, mod, 1) not in S: S.append(vinefruit(s1, mod, 1)) pr(border, 'gj, try the next level :)') else: break else: break else: die(border, 'Kidding me?! Try again and be smart!! Bye!!!') elif ans == 'q': die(border, 'Quitting...') else: die(border, 'You should select valid choice!') if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Derik/Derik.py
ctfs/Crypto/2023/Derik/Derik.py
#!/usr/bin/env python3 from Crypto.Util.number import * from secret import C, e, d, p, q, r, flag O = [1391526622949983, 2848691279889518, 89200900157319, 31337] assert isPrime(e) and isPrime(d) and isPrime(p) and isPrime(q) and isPrime(r) assert C[0] * p - C[1] * q >= 0 assert C[2] * q - C[3] * r >= 0 assert C[4] * r - C[5] * p >= 0 assert (C[0] * p - C[1] * q) ** e + (C[2] * q - C[3] * r) ** e + (C[4] * r - C[5] * p) ** e == d * (C[0] * p - C[1] * q) * (C[2] * q - C[3] * r) * (C[4] * r - C[5] * p) assert C[6] * e - C[7] * d == O[3] n = e * d * p * q * r m = bytes_to_long(flag) c = pow(m, 65537, n) print(f'C = {C}') print(f'c = {c}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Blobfish/blobfish.py
ctfs/Crypto/2023/Blobfish/blobfish.py
#!/usr/bin/env python3 import os from hashlib import md5 from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from PIL import Image from PIL import ImageDraw from flag import flag key = get_random_bytes(8) * 2 iv = md5(key).digest() cipher = AES.new(key, AES.MODE_CFB, iv=iv) enc = cipher.encrypt(flag) img = Image.new('RGB', (800, 50)) drw = ImageDraw.Draw(img) drw.text((20, 20), enc.hex(), fill=(255, 0, 0)) img.save("flag.png") hkey = ''.join('\\x{:02x}'.format(x) for x in key[:10]) os.system(f'/bin/zip -0 flag.zip flag.png -e -P \"$(/bin/echo -en \"{hkey}\")\"')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Roldy/Roldy.py
ctfs/Crypto/2023/Roldy/Roldy.py
#!/usr/bin/env python3 from Crypto.Util.number import * from pyope.ope import OPE as enc from pyope.ope import ValueRange import sys from secret import key, flag def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.buffer.readline() def encrypt(msg, key, params): if len(msg) % 16 != 0: msg += (16 - len(msg) % 16) * b'*' p, k1, k2 = params msg = [msg[_*16:_*16 + 16] for _ in range(len(msg) // 16)] m = [bytes_to_long(_) for _ in msg] inra = ValueRange(0, 2**128) oura = ValueRange(k1 + 1, k2 * p + 1) _enc = enc(key, in_range = inra, out_range = oura) C = [_enc.encrypt(_) for _ in m] return C def main(): border = "|" pr(border*72) pr(border, " Welcome to Roldy combat, we implemented an encryption method to ", border) pr(border, " protect our secret. Please note that there is a flaw in our method ", border) pr(border, " Can you examine it and get the flag? ", border) pr(border*72) pr(border, 'Generating parameters, please wait...') p, k1, k2 = [getPrime(129)] + [getPrime(64) for _ in '__'] C = encrypt(flag, key, (p, k1, k2)) while True: pr("| Options: \n|\t[E]ncrypted flag! \n|\t[T]ry encryption \n|\t[Q]uit") ans = sc().decode().lower().strip() if ans == 'e': pr(border, f'encrypt(flag, key, params) = {C}') elif ans == 't': pr(border, 'Please send your message to encrypt: ') msg = sc().rstrip(b'\n') if len(msg) > 64: pr(border, 'Your message is too long! Sorry!!') C = encrypt(msg, key, (p, k1, k2)) pr(border, f'C = {C}') elif ans == 'q': die(border, "Quitting ...") else: die(border, "Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Suction/suction.py
ctfs/Crypto/2023/Suction/suction.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag def keygen(nbit, r): while True: p, q = [getPrime(nbit) for _ in '__'] e, n = getPrime(16), p * q phi = (p - 1) * (q - 1) if GCD(e, phi) == 1: N = bin(n)[2:-r] E = bin(e)[2:-r] PKEY = N + E pkey = (n, e) return PKEY, pkey def encrypt(msg, pkey, r): m = bytes_to_long(msg) n, e = pkey c = pow(m, e, n) C = bin(c)[2:-r] return C r, nbit = 8, 128 PKEY, pkey = keygen(nbit, r) print(f'PKEY = {int(PKEY, 2)}') FLAG = flag.lstrip(b'CCTF{').rstrip(b'}') enc = encrypt(FLAG, pkey, r) print(f'enc = {int(enc, 2)}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2023/Did_it/did.py
ctfs/Crypto/2023/Did_it/did.py
#!/usr/bin/env python3 from random import randint import sys from flag import flag def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.buffer.readline() def did(n, l, K, A): A, K = set(A), set(K) R = [pow(_, 2, n) + randint(0, 1) for _ in A - K] return R def main(): border = "+" pr(border*72) pr(border, ".:: Hi all, she DID it, you should do it too! Are you ready? ::. ", border) pr(border*72) _flag = False n, l = 127, 20 N = set(list(range(0, n))) K = [randint(0, n-1) for _ in range(l)] cnt, STEP = 0, 2 * n // l - 1 while True: ans = sc().decode().strip() try: _A = [int(_) for _ in ans.split(',')] if len(_A) <= l and set(_A).issubset(N): DID = did(n, l, K, _A) pr(border, f'DID = {DID}') if set(_A) == set(K): _flag = True else: die(border, 'Exception! Bye!!') except: die(border, 'Your input is not valid! Bye!!') if _flag: die(border, f'Congrats! the flag: {flag}') if cnt > STEP: die(border, f'Too many tries, bye!') cnt += 1 if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/fiercest/fiercest.py
ctfs/Crypto/2022/fiercest/fiercest.py
#!/usr/bin/env python3 from Crypto.Util.number import * import sys from flag import flag def diff(a, b): assert a.bit_length() == b.bit_length() w, l = 0, a.bit_length() for _ in range(l): if bin(a)[2:][_] != bin(b)[2:][_]: w += 1 return w def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, "Hello guys! This is a challenge on fault attack for signatures, our ", border) pr(border, "storage can apply at most `l' bit flip-flop on signature modulus, so", border) pr(border, "try to locate the critical bits, we'll changed them to forge a sign!", border) pr(border*72) nbit = 512 p, q = [getPrime(nbit) for _ in '__'] n, e = p * q, 65537 B, l = [int(b) for b in bin(n)[2:]], 2 MSG = "4lL crypt0sy5t3ms suck5 fr0m faul7 atTaCk5 :P" m = bytes_to_long(MSG.encode('utf-8')) while True: pr("| Options: \n|\t[A]pply fault \n|\t[G]et the parameters \n|\t[V]erify the signature \n|\t[Q]uit") ans = sc().lower() if ans == 'a': _B = B pr(border, f"please send at most {l}-tuple array from indices of bits of modulus, like: 14, 313") ar = sc() try: ar = [int(_) for _ in ar.split(',')] if len(ar) <= l: for i in range(len(ar)): _B[ar[i]] = (_B[ar[i]] + 1) % 2 N = int(''.join([str(b) for b in _B]), 2) else: raise Exception('Invalid length!') except: pr(border, "Something went wrong!!") elif ans == 'g': pr(border, f'e = {e}') pr(border, f'n = {n}') elif ans == "v": pr(border, "please send signature to verify: ") _flag, signature = False, sc() try: signature = int(signature) if pow(signature, e, N) == m: _flag = True else: pr(border, "Your signature is not valid!!") except: pr(border, "Something went wrong!!") if _flag: die(border, "Congrats! your got the flag: " + flag) elif ans == 'q': die("Quitting ...") else: die("Bye bye ...") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/313_loyal/313loyal.py
ctfs/Crypto/2022/313_loyal/313loyal.py
#!/usr/bin/env python3 from Crypto.Util.number import * from random import * import sys from flag import flag def keygen(nbit): p, q = [getPrime(nbit) for _ in '__'] n, phi = p * q, (p - 1) * (q - 1) // 2 while True: g = getRandomRange(2, n ** 2) if GCD(g, n) == 1: w = (pow(g, phi, n ** 2) - 1) // n if GCD(w, n) == 1: u = inverse(w, n) break pkey, skey = (n, g), (phi, u) return pkey, skey def encrypt(pkey, m): n, g = pkey while True: r = getRandomRange(2, n) if GCD(r, n) == 1: break return (pow(g, m, n ** 2) * pow(r, n, n ** 2)) % (n ** 2) def add(pkey, a, b): n, g = pkey return pow(a * b, 1, n ** 2) def multiply(pkey, a, k): n, g = pkey return pow(a, k, n ** 2) def mul_poly(n, P, Q): R = [0] * (len(P) + len(Q)) for i in range(len(P)): for j in range(len(y)): R[i+j] += (R[i + j] + P[i] * Q[j]) % n return R def encrypt_poly(pkey, poly): return [encrypt(pkey, term) for term in poly] def client_genpoly(pkey, points): n, g = pkey result = [1] for point in points: result = mul_poly(n, result, [-point, 1]) return encrypt_poly(pkey, result) def evaluate_poly(pkey, poly, point): n, g = pkey _point = point result = poly[0] for term in poly[1:]: result = add((n, g), result, multiply((n, g), term, _point)) _point = (_point * point) % n return result def backend(pkey, poly, points): n, g = pkey R = [] for point in points: result = evaluate_poly((n, g), poly, point) result = multiply((n, g), result, getRandomRange(2, n)) result = add((n, g), result, encrypt((n, g), point)) R.append(result) return R def main(): border = "|" pr(border*72) pr(border, " Hi cryptographers, our mission is analyzing a modern crypto-system ", border) pr(border, " with given parameters, be motivated and try to grab the flag! ", border) pr(border*72) nbit = 256 while True: POINTS = [] for i in range(len(flag)): POINTS.append(getRandomRange(2, 2 ** 64) * 2 ** 10) POINTS.sort() for i in range(len(flag)): POINTS[i] += flag[i] pr("| Options: \n|\t[S]end parameters and try the oracle \n|\t[Q]uit") ans = sc().lower() if ans == 's': pr(border, "Send the parameters of crypto-system like: n, g, poly ") params = sc() try: n, g, poly = params.split(',') n, g, poly = int(n), int(g), poly.strip() poly = list(map(int, poly.replace('[', '').replace(']', '').split(' '))) if (n < 2 ** nbit): die(border, "n is too small :(") pkey = (n, g) result = backend(pkey, poly, POINTS) shuffle(result) except: die(border, "your parameters are not valid!!") for i in range(len(result)): pr(border, f'result[{i}] = {result[i]}') elif ans == 'q': die(border, "Quitting ...") else: die(border, "Bye ...") def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/sidestep/sidestep.py
ctfs/Crypto/2022/sidestep/sidestep.py
#!/usr/bin/env python3 from Crypto.Util.number import * import random, sys from flag import flag def pow_d(g, e, n): t, r = 0, 1 for _ in bin(e)[2:]: if r == 4: t += 1 r = pow(r, 2, n) if _ == '1': r = r * g % n return t, r def ts(m, p): m = m % p return pow(m, (p - 1) // 2, p) == 1 def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, "Hi all cryptographers! Welcome to the Sidestep task, we do powing!!!", border) pr(border, "You should solve a DLP challenge in some special way to get the flag", border) p = 2 ** 1024 - 2 ** 234 - 2 ** 267 - 2 ** 291 - 2 ** 403 - 1 s = random.randint(2, (p - 1) // 2) while True: pr("| Options: \n|\t[T]ry the magic machine \n|\t[Q]uit") ans = sc().lower() if ans == 't': pr(border, "please send your desired integer: ") g = sc() try: g = int(g) except: die(border, "The given input is not integer!") if ts(g, p): t, r = pow_d(g, s, p) if r == 4: die(border, f'Great! you got the flag: {flag}') else: pr(border, f"t, r = {t, r}") else: pr(border, "The given base is NOT valid!!!") elif ans == 'q': die(border, "Quitting ...") else: die(border, "Bye bye ...") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/oak_land/oak_land.py
ctfs/Crypto/2022/oak_land/oak_land.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag p = 7389313481223384214994762619823300589978423075857540712007981373887018860174846208000957230283669342186460652521580595183523706412588695116906905718440770776239313669678685198683933547601793742596023475603667 e = 31337 f = 7236042467316654159796543399639966340258093274047941788600980451877044636122969830708918356119442228154447395855689559447196348683125675305629837437591088260218138895919514078948650757100432223219969122629790 g = 1878626136321051642174045874618248475160620873585704351202865003185878331837410979441756843820270907300810543618813757245154196050399357659526631164136221434463496532263979506870318259276669412698827040743576 x = bytes_to_long(flag.encode('utf-8')) assert x < p c = (110 * pow(e, x, p) + 313 * pow(f, x, p) + 114 * pow(g, x, p)) % p print(f'c = {c}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/jeksign/jeksign.py
ctfs/Crypto/2022/jeksign/jeksign.py
#!/usr/bin/env python3 from Crypto.Util.number import * from secret import gensol, nbit_gensol from flag import flag m = bytes_to_long(flag.encode('utf-8')) print(m) a = 1337 b = 31337 def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, "Welcome crypto guys! Here we are looking for the solution of special", border) pr(border, "Diophantine equation: 1337(z^4 - x^2) = 31337(y^2 - z^4) in natural ", border) pr(border, "numbers, in each stage solve the equation in mentioned interval :) ", border) pr(border*72) STEP, level = 0, 19 while True: p, q = nbit_gensol(1337, 31337, STEP + 30) x, y, z = gensol(a, b, p, q) pr(border, f"Send a solution like `x, y, z' such that the `z' is {STEP + 30}-bit: ") ans = sc() try: X, Y, Z = [int(_) for _ in ans.split(',')] NBIT = Z.bit_length() except: die(border, 'Your input is not valid, Bye!') if 1337*(Z**4 - X**2) == 31337*(Y**2 - Z**4) and NBIT == STEP + 30: if STEP == level - 1: die(border, f'Congrats, you got the flag: {flag}') else: pr('| good job, try to solve the next challenge :P') STEP += 1 else: die(border, 'your answer is not correct, Bye!!') if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/shaim/shaim.py
ctfs/Crypto/2022/shaim/shaim.py
#!/usr/bin/env python3 from Crypto.Util.number import * from Crypto.Cipher import DES from hashlib import sha256 import sys, string from flag import flag def shaim(msg): SBOX = [ 0xbe, 0xc5, 0x0f, 0x83, 0xb2, 0x77, 0xa8, 0x40, 0x4c, 0x53, 0x65, 0xd6, 0x27, 0xa7, 0x7c, 0x48, 0x1a, 0x60, 0x30, 0x17, 0xf3, 0x80, 0x04, 0x74, 0xd2, 0x5a, 0x2c, 0x8e, 0xa0, 0x32, 0x38, 0xcb, 0xe5, 0x4d, 0x19, 0x8f, 0xd9, 0x6d, 0x86, 0x58, 0xfc, 0xfa, 0xba, 0xdd, 0xc7, 0x57, 0xc1, 0x1c, 0x6a, 0x0c, 0x7b, 0x4b, 0xc8, 0x52, 0x54, 0x82, 0x47, 0x5d, 0xc9, 0xe8, 0x6b, 0xdb, 0x5e, 0x08, 0xfb, 0x8d, 0x0e, 0x43, 0x37, 0x39, 0x50, 0x91, 0x7e, 0xf4, 0xe7, 0x35, 0xb8, 0x88, 0x20, 0x8b, 0x90, 0xe9, 0xee, 0xd5, 0xd3, 0xc3, 0xff, 0xa9, 0xae, 0x64, 0xf5, 0xac, 0x11, 0x4a, 0x76, 0x06, 0x18, 0x8a, 0xa3, 0xec, 0x56, 0x94, 0xdf, 0x42, 0x00, 0x22, 0xda, 0x6c, 0xb1, 0x12, 0xf2, 0xfe, 0xbf, 0x21, 0x1b, 0x4e, 0x9f, 0x97, 0xa6, 0x2b, 0x0b, 0xd4, 0x93, 0xc6, 0x03, 0x71, 0x14, 0x7a, 0x02, 0x0a, 0xc4, 0xdc, 0x36, 0x96, 0xd0, 0x09, 0x33, 0x26, 0xbc, 0x1d, 0xb6, 0xde, 0xe6, 0xe3, 0xeb, 0x28, 0x8c, 0x24, 0x99, 0x3f, 0xc0, 0x6f, 0xa2, 0xc2, 0xfd, 0x3c, 0x2d, 0x15, 0xf6, 0xad, 0x2f, 0xbd, 0x67, 0x05, 0x68, 0xa1, 0x69, 0x13, 0xca, 0x9d, 0x3a, 0x01, 0x63, 0xd7, 0x75, 0x07, 0x59, 0xb9, 0x46, 0xf8, 0xcd, 0x5c, 0x70, 0x95, 0xf9, 0x16, 0x45, 0xd1, 0x98, 0x79, 0x9c, 0x81, 0x44, 0x62, 0x6e, 0xb4, 0x34, 0xce, 0x84, 0xab, 0x29, 0x1e, 0x2a, 0x9b, 0xe2, 0x25, 0xb5, 0x87, 0x23, 0x3d, 0x5f, 0xaa, 0xf7, 0x9e, 0xed, 0xb3, 0xe1, 0x72, 0x7d, 0x3b, 0xb7, 0x0d, 0x51, 0x9a, 0x4f, 0x55, 0xf1, 0xf0, 0xe0, 0x31, 0x7f, 0xbb, 0x89, 0x5b, 0xe4, 0x78, 0x73, 0xef, 0xea, 0x92, 0x61, 0x41, 0x1f, 0xcc, 0xb0, 0x49, 0x85, 0x3e, 0x66, 0xaf, 0xd8, 0x2e, 0xa5, 0x10, 0xa4, 0xcf ] nbit, hmsg = 64, msg.hex() hmsg += 'f' + hex(len(msg.hex())*4)[2:] hmsg += (nbit - (4*len(hmsg) % nbit)) // 4 * 'f' H, SBOX_M = [], '' for i in range (0, len(hmsg) - 1, 2): tmp = hex(SBOX[int(hmsg[i:i+2], 16)])[2:] tmp = '0' + tmp if len(tmp) % 2 else tmp SBOX_M += tmp hmsg = SBOX_M l = nbit // 4 H.append((int(hmsg[0:l], 16))) for i in range(1, len(hmsg) // l): plain = long_to_bytes(int(hmsg[i*l:(i+1)*l], 16)) key = long_to_bytes(H[i-1]) _DES = DES.new(key = key, mode = DES.MODE_OFB, IV = key) H.append(bytes_to_long(_DES.encrypt(plain)) ^ bytes_to_long(key)) dgst = sha256(long_to_bytes(H[-1])).hexdigest() return dgst def randstr(l): rstr = [(string.printable[:62] + '_')[getRandomRange(0, 62)] for _ in range(l)] return ''.join(rstr).encode('utf-8') def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, " Hey hash breakers! Try to find the collision for given message and ", border) pr(border, " get the flag! You have only one chance to get it in each round! :P ", border) pr(border*72) msg = randstr(getRandomRange(40, 72)) while True: pr("| Options: \n|\t[G]et the message with hash \n|\t[S]end collision \n|\t[Q]uit") ans = sc().lower() if ans == 'g': pr(border, f'msg = {msg}') pr(border, f'shaim(msg) = {shaim(msg)}') elif ans == 's': pr(border, f'please send message with same hash: ') nmsg = sc().encode('utf-8') hmsg = shaim(nmsg) if hmsg == shaim(msg) and nmsg != msg: die(border, f'Congrats, you got the flag: {flag}') else: die(border, 'your answer is not correct, Bye!!') elif ans == 'q': die(border, 'Quitting...') else: die(border, 'your answer is not correct, Bye!!') if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/resign/resign.py
ctfs/Crypto/2022/resign/resign.py
#!/usr/bin/env python3 from Crypto.Util.number import * from hashlib import sha1 import sys from flag import flag def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, " Hi, Try to guess our RSA private key to sign my message, talented ", border) pr(border, " hackers like you ;) are able to do it, they are *Super Guesser* :) ", border) pr(border*72) p, q = [getPrime(1024) for _ in '__'] n, e = p * q, 65537 phi = (p - 1) * (q - 1) d = inverse(e, phi) MSG = b'::. Can you forge any signature? .::' h = bytes_to_long(sha1(MSG).digest()) SIGN = pow(h, d, n) while True: pr("| Options: \n|\t[G]uess the secret key \n|\t[R]eveal the parameters \n|\t[S]ign the message \n|\t[P]rint the signature \n|\t[Q]uit") ans = sc().lower() if ans == 'g': pr(border, f"please send the RSA public exponent and PARAMS p, q separated by comma like e, p, q: ") PARAMS = sc() try: E, P, Q = [int(_) for _ in PARAMS.split(',')] if P.bit_length() == Q.bit_length() == 1024 and P != Q: N = P * Q PHI = (P - 1) * (Q - 1) D = inverse(E, PHI) if pow(h, D, N) == SIGN: e, n, d = E, N, D pr(border, 'Great guess, now you are able to sign any message!!!') else: pr(border, 'Your RSA parameters are not correct!!') else: raise Exception('Invalid RSA parameters!!') except: pr(border, "Something went wrong!!") elif ans == 'r': pr(border, f'e = {e}') pr(border, f'n = {n}') elif ans == "p": pr(border, f'SIGN = {SIGN}') elif ans == 's': pr(border, "Please send the signature of this message: ") pr(border, f"MSG = {MSG[4:-4]}") sgn = sc() try: sgn = int(sgn) _continue = True except: pr(border, "Something went wrong!!") _continue = False if _continue: _MSG = MSG[4:-4] _h = bytes_to_long(sha1(_MSG).digest()) if pow(sgn, e, n) == _h: die(border, "Congrats! your got the flag: " + flag) else: pr(border, "Sorry, your signature is not correct!") elif ans == 'q': die("Quitting ...") else: die("Bye bye ...") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/sparse/sparse.py
ctfs/Crypto/2022/sparse/sparse.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag def sparse(p, k): nbit = p.bit_length() while True: CF = [getRandomRange(-1, 1) for _ in '_' * k] XP = [getRandomRange(3, nbit - 3) for _ in '_' * k] A = sum([CF[_] * 2 ** XP[_] for _ in range(0, k)]) q = p + A if isPrime(q) * A != 0: return q p = getPrime(417) q = sparse(p, 5) e, n = 65537, p * q print(f'n = {n}') m = bytes_to_long(flag.encode('utf-8')) assert m < n c = pow(m, e, n) print(f'c = {c}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/persian_cat/persian_cat.py
ctfs/Crypto/2022/persian_cat/persian_cat.py
#!/usr/bin/env python3 import random, sys from secret import skey, flag Omega = [ 0x4e, 0x96, 0xfd, 0x7d, 0x8d, 0xf6, 0xdb, 0x33, 0x1e, 0x16, 0x9b, 0x6a, 0xe2, 0xc9, 0xa9, 0xe0, 0x34, 0xe6, 0x86, 0xd6, 0x52, 0x02, 0x25, 0x1f, 0x23, 0xdf, 0xd5, 0x12, 0x45, 0x6b, 0x6f, 0x4d, 0x31, 0x77, 0x09, 0xbf, 0x93, 0xca, 0x4b, 0xef, 0xee, 0x7c, 0x53, 0x1a, 0xc8, 0xea, 0x9d, 0xda, 0x32, 0xa4, 0x11, 0x7b, 0xd8, 0x3f, 0x13, 0x57, 0x75, 0xcb, 0x37, 0x9a, 0x83, 0xa5, 0x3e, 0xd3, 0x4a, 0x1d, 0x29, 0xb9, 0x18, 0x27, 0x2d, 0x0f, 0x15, 0x0d, 0x66, 0xae, 0xf5, 0xfa, 0x08, 0x9f, 0xc6, 0x55, 0xa0, 0xb7, 0x28, 0x0e, 0xf4, 0x01, 0x04, 0x46, 0xf9, 0x39, 0xe3, 0x7f, 0x5e, 0x61, 0x40, 0x26, 0xec, 0xb6, 0x14, 0xf0, 0x59, 0x50, 0xcf, 0x3a, 0x8b, 0x43, 0xaf, 0x10, 0xe5, 0xe8, 0x03, 0xbd, 0x51, 0xa7, 0x1c, 0x8e, 0x7a, 0x98, 0x3c, 0xeb, 0xac, 0x54, 0x84, 0xf7, 0x62, 0x88, 0x64, 0xa8, 0xbb, 0xab, 0xe1, 0x95, 0x94, 0x41, 0x2a, 0x60, 0x30, 0xcc, 0x48, 0xd2, 0x89, 0xb2, 0x65, 0x76, 0x0a, 0xb8, 0x56, 0x4f, 0xc3, 0x87, 0xdd, 0x4c, 0xc2, 0xd4, 0x82, 0x35, 0x90, 0xa2, 0x5f, 0xad, 0x19, 0x74, 0x73, 0xd0, 0x24, 0x69, 0x20, 0x07, 0xdc, 0x1b, 0x44, 0x58, 0xff, 0x5a, 0x6c, 0xf2, 0xfb, 0x8c, 0x79, 0x97, 0xa6, 0x22, 0xb4, 0x7e, 0x5b, 0x17, 0x2f, 0x91, 0x71, 0xfe, 0x38, 0xa3, 0x05, 0xb1, 0xba, 0x99, 0xd9, 0xf1, 0x21, 0x5c, 0x67, 0x6d, 0xde, 0xaa, 0xc7, 0x8f, 0x81, 0x0b, 0xb0, 0xbc, 0x0c, 0xcd, 0x63, 0xc1, 0xfc, 0xc0, 0x42, 0x78, 0xc5, 0x8a, 0x06, 0x3d, 0x2e, 0x9e, 0xa1, 0x80, 0xb3, 0xf8, 0xe9, 0x68, 0xd1, 0x36, 0x70, 0x49, 0xc4, 0xd7, 0x2c, 0x6e, 0xe7, 0xb5, 0xbe, 0x92, 0xce, 0xed, 0xf3, 0x9c, 0xe4, 0x3b, 0x47, 0x2b, 0x85, 0x5d, 0x72, 0x01 ] def padding(msg): if len(msg) % 32 != 0: extra = '*' * (32 - len(msg) % 32) return msg + extra else: return msg def keygen(u, v): return [a ^ b for a, b in zip(u, v)][:20] def roadrunner(table, roadrunner_wile, lili, lilibeth, omega): for z in range(16): roadrunner_wile[z] = (((omega[table[lili[z][0]]] | omega[table[lili[z][1]]]) + (omega[table[lili[z][2]]] | omega[table[lili[z][3]]])) ^ ((omega[table[lili[z][4]]] + omega[table[lili[z][5]]]) + (omega[table[lili[z][6]]] ^ omega[table[lili[z][7]]]))) % 256 roadrunner_wile[z] = (roadrunner_wile[z] + (((~omega[table[lili[z][8]]] ^ omega[table[lili[z][9]]]) + (omega[table[lili[z][10]]] & ~omega[table[lili[z][11]]])) ^ ((omega[table[lili[z][12]]] ^ ~omega[table[lili[z][13]]]) + (omega[table[lili[z][14]]] ^ omega[table[lili[z][15]]])))) % 256 roadrunner_wile[z] = (roadrunner_wile[z] + lilibeth[roadrunner_wile[z]] + lilibeth[z]) % 256 return roadrunner_wile def roadrunner_init(table, roadrunner_wile, lili, lilibeth, omega): SBOX = [ [10, 11, 4, 5, 15, 0, 2, 3, 1, 9, 14, 6, 7, 12, 8, 13], [1, 11, 13, 2, 0, 7, 3, 8, 14, 4, 6, 15, 5, 10, 12, 9], [1, 9, 0, 4, 11, 5, 2, 8, 15, 7, 3, 6, 10, 14, 13, 12], [5, 0, 9, 8, 3, 10, 12, 4, 1, 6, 7, 11, 15, 14, 2, 13], [10, 6, 13, 3, 2, 11, 12, 14, 5, 9, 4, 1, 0, 8, 15, 7], [15, 6, 1, 10, 7, 13, 14, 8, 3, 12, 0, 5, 2, 9, 4, 11], [13, 7, 9, 5, 14, 12, 8, 15, 6, 0, 10, 4, 3, 11, 2, 1], [13, 15, 8, 10, 6, 11, 9, 7, 12, 2, 3, 4, 14, 0, 5, 1], [11, 3, 14, 7, 4, 8, 12, 2, 13, 0, 6, 1, 9, 10, 5, 15], [2, 3, 14, 9, 11, 5, 15, 0, 4, 7, 1, 6, 12, 13, 8, 10], [13, 3, 14, 1, 10, 0, 6, 5, 7, 2, 4, 9, 12, 8, 11, 15], [15, 7, 4, 12, 14, 2, 9, 6, 3, 1, 13, 5, 0, 8, 11, 10], [10, 7, 5, 14, 6, 2, 15, 1, 8, 11, 12, 9, 0, 3, 4, 13], [1, 5, 0, 4, 6, 9, 11, 12, 3, 14, 7, 2, 15, 8, 13, 10], [14, 9, 11, 2, 10, 4, 3, 0, 5, 8, 6, 15, 1, 12, 13, 7], [11, 13, 6, 2, 0, 9, 3, 12, 1, 8, 7, 15, 4, 5, 10, 14] ] for z in range(16): roadrunner_wile[z] = (((omega[table[SBOX[z][0]]] | omega[table[SBOX[z][1]]]) + (omega[table[SBOX[z][2]]] | omega[table[SBOX[z][3]]])) ^ ((omega[table[SBOX[z][4]]] + omega[table[SBOX[z][5]]]) + ( omega[table[SBOX[z][6]]] ^ omega[table[SBOX[z][7]]]))) % 256 roadrunner_wile[z] = (roadrunner_wile[z] + (((~omega[table[SBOX[z][8]]] ^ omega[table[SBOX[z][9]]]) + (omega[table[SBOX[z][10]]] & ~omega[table[SBOX[z][11]]])) ^ ((omega[table[SBOX[z][12]]] ^ ~omega[table[SBOX[z][13]]]) + (omega[table[SBOX[z][14]]] ^ omega[table[SBOX[z][15]]])))) % 256 return roadrunner_wile def circle_it_out(msg, ruler, roadrunner_wile, lili, lilibeth, enc, l, r, omega): for i in range(16): l[0][i] = msg[i] r[0][i] = msg[i+16] for i in range(1, ruler): roadrunner_wile = roadrunner(r[i-1], roadrunner_wile, lili, lilibeth, omega) for y in range(16): l[i][y] = r[i-1][y] r[i][y] = (l[i-1][y] ^ roadrunner_wile[y])%256 for i in range(16): enc[i+16] = l[ruler-1][i]%256 enc[i] = r[ruler-1][i]%256 return roadrunner_wile, enc, l, r def circle_it_out_init(msg, ruler, roadrunner_wile, lili, lilibeth, enc, l, r, omega): for i in range(16): l[0][i] = msg[i] r[0][i] = msg[i+16] for i in range(1,ruler): roadrunner_wile = roadrunner_init(r[i-1], roadrunner_wile, lili, lilibeth, omega) for y in range(16): l[i][y] = r[i-1][y] r[i][y] = (l[i-1][y] ^ roadrunner_wile[y])%256 for i in range(16): enc[i] = l[ruler-1][i]%256 enc[i+16] = r[ruler-1][i]%256 return roadrunner_wile, enc, l, r def persian_init(key, roadrunner_wile, lili, lilibeth, enc, l, r, omega, Omega): stkey = [88, 20, 64, 181, 251, 167, 69, 243, 205, 166, 110, 65, 90, 176, 229, 46, 206, 104, 15, 19, 49, 101, 3, 223, 221, 231, 232, 43, 62, 193, 80, 228] for compt in range(256): omega[compt] = (Omega[compt]^key[compt%20]) % 256 for w in range(4): roadrunner_wile, enc, l, r = circle_it_out_init(stkey, 32, roadrunner_wile, lili, lilibeth, enc, l, r, omega); for compt in range(256): omega[compt] = (omega[compt]^enc[compt%32])%256 for compt in range(32): stkey[compt] = enc[compt] for compt in range(16): err = 0 ix = 0 while ix < 16: roadrunner_wile, enc, l, r = circle_it_out_init(enc, 4, roadrunner_wile, lili, lilibeth, enc, l, r, omega) x = 0 while x < ix: if lili[compt][x] == (enc[7]%16): x = ix err = 1 roadrunner_wile, enc, l, r = circle_it_out_init(enc, 4, roadrunner_wile, lili, lilibeth, enc, l, r, omega) else: x += 1 if err == 0: lili[compt][ix] = enc[7]%16 else: err = 0; ix = ix-1; ix += 1 err = 0 ix = 0 while ix < 256: roadrunner_wile, enc, l, r = circle_it_out_init(enc, 4, roadrunner_wile, lili, lilibeth, enc, l, r, omega) x = 0 while x < ix: if lilibeth[x] == ( enc[7]%256): x = ix err = 1 roadrunner_wile, enc, l, r = circle_it_out_init(enc, 4, roadrunner_wile, lili, lilibeth, enc, l, r, omega) else: x += 1 if err == 0: lilibeth[ix]=enc[7]%256 else: err = 0; ix = ix-1; ix += 1 for compt in range(256): omega[compt] = (omega[compt] ^ key[compt%20])%256 for w in range(4): roadrunner_wile, enc, l, r = circle_it_out_init(stkey, 32, roadrunner_wile, lili, lilibeth, enc, l, r, omega) for compt in range(256): omega[compt] = (omega[compt] ^ enc[compt%32])%256 for compt in range(32): stkey[compt] = enc[compt] return roadrunner_wile, lili, lilibeth, enc, l, r, omega def encrypt_iginition(msg, key): roadrunner_wile = [0 for x in range(16)] lili = [[0 for x in range(16)] for y in range(256)] lilibeth, omega = [[0 for x in range(256)] for _ in '01'] enc = [0 for x in range(32)] l, r = [[[0 for x in range(16)] for y in range(32)] for _ in '01'] roadrunner_wile, lili, lilibeth, enc, l, r, omega = persian_init(key, roadrunner_wile, lili, lilibeth, enc, l, r, omega, Omega) roadrunner_wile, enc, l, r = circle_it_out(msg, 6, roadrunner_wile, lili, lilibeth, enc, l, r, omega) return enc def encrypt(msg, key): msg = padding(msg) blocks = [msg[i*32:i*32+32] for i in range(len(msg) // 32)] ciphers = [] enc = encrypt_iginition([ord(item) for item in blocks[0]], key) ciphers.append(enc) for i in range(len(blocks)-1): enc = encrypt_iginition([ord(item) for item in blocks[i+1]], keygen([ord(item) for item in blocks[i]], ciphers[i])) ciphers.append(enc) return "".join("".join(str(format(i, "02x")) for i in item) for item in ciphers) def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, "Hello guys! This challenge is about breaking a symmetric cipher that", border) pr(border, "we have implemented here, your mission is find the flag, have fun :)", border) pr(border*72) while True: pr("| Options: \n|\t[E]encrypt message \n|\t[Q]uit") ans = sc().lower() if ans == 'e': pr(border, 'please send you message: ') msg = sc() enc = encrypt(msg + flag, skey) pr(border, f'enc = {enc}') elif ans == 'q': die("Quitting ...") else: die("Bye bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/cantilever/cantilever.py
ctfs/Crypto/2022/cantilever/cantilever.py
#!/usr/bin/env python3 from Crypto.Util.number import * from flag import flag def gen_primes(nbit, imbalance): p = 2 FACTORS = [p] while p.bit_length() < nbit - 2 * imbalance: factor = getPrime(imbalance) FACTORS.append(factor) p *= factor rbit = (nbit - p.bit_length()) // 2 while True: r, s = [getPrime(rbit) for _ in '01'] _p = p * r * s if _p.bit_length() < nbit: rbit += 1 if _p.bit_length() > nbit: rbit -= 1 if isPrime(_p + 1): FACTORS.extend((r, s)) p = _p + 1 break FACTORS.sort() return (p, FACTORS) def genkey(nbit, imbalance, e): while True: p, FACTORS = gen_primes(nbit // 2, imbalance) if len(FACTORS) != len(set(FACTORS)): continue q, q_factors = gen_primes(nbit // 2, imbalance + 1) if len(q_factors) != len(set(q_factors)): continue factors = FACTORS + q_factors if e not in factors: break n = p * q return n, (p, q) nbit = 2048 imbalance = 19 e = 0x10001 m_1 = bytes_to_long(flag[:len(flag) // 2]) m_2 = bytes_to_long(flag[len(flag) // 2:]) n, PRIMES = genkey(nbit, imbalance, e) c_1 = pow(m_1, e, n) c_2 = pow(e, m_2, n) print(f'n = {n}') print(f'c_1 = {c_1}') print(f'c_2 = {c_2}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/baphomet/baphomet.py
ctfs/Crypto/2022/baphomet/baphomet.py
#!/usr/bin/env python3 from base64 import b64encode from flag import flag def encrypt(msg): ba = b64encode(msg.encode('utf-8')) baph, key = '', '' for b in ba.decode('utf-8'): if b.islower(): baph += b.upper() key += '0' else: baph += b.lower() key += '1' baph = baph.encode('utf-8') key = int(key, 2).to_bytes(len(key) // 8, 'big') enc = b'' for i in range(len(baph)): enc += (baph[i] ^ key[i % len(key)]).to_bytes(1, 'big') return enc enc = encrypt(flag) f = open('flag.enc', 'wb') f.write(enc) f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/infinity_castle/infinity_castle.py
ctfs/Crypto/2022/infinity_castle/infinity_castle.py
#!/usr/bin/env python3 from Crypto.Util.number import * from os import urandom class TaylorSeries(): def __init__(self, order): self.order = order def coefficient(self, n): i = 0 coef = 1 while i < n: i += 1 coef *= (coef * (1/2-i+1)) / i return coef def find(self, center): sum = 0 center -= 1 i = 0 while i < self.order: sum += (center**(1/2-i) * self.coefficient(i)) i += 1 return sum def xor(cip, key): repeation = 1 + (len(cip) // len(key)) key = key * repeation key = key[:len(cip)] msg = bytes([c ^ k for c, k in zip(cip, key)]) return msg # If you run these 3 functions (diamond, triage, summarize) with big numbers, they will never end # You need to optimize them first def diamond(num): output = 0 for i in range(num): output += i*2 + 1 return output def triage(num): output = 0 index = 0 for i in range(num): output += (i+index)*6 + 1 index += i return output def summarize(b): order = getRandomRange(1000, 2000) t = TaylorSeries(order) output = 0 i = 2 while i < b: b1 = t.find(i) b2 = t.find(i+1) output += (b1+b2) / 2 i += 1 return output KEY_SIZE = 2048 p, q = [getPrime(KEY_SIZE) for _ in '01'] e, n = 0x10001, p*q f = open ('./message.txt', 'rb') message = f.read() f.close() msg_length = len(message) padded_msg = message + urandom(len(long_to_bytes(n)) - msg_length) padded_msg_length = len(padded_msg) xor_key = long_to_bytes(int(summarize(n)))[:padded_msg_length] assert(len(xor_key) == 512) enc0 = xor(padded_msg, xor_key) assert(bytes_to_long(enc0) < n) c0 = abs(diamond(p) - diamond(q)) c1 = triage(p) c1 += 3*n*(p+q) c1 += triage(q) m = bytes_to_long(enc0) enc1 = pow(m, e, n) print(f"c0 = {c0}") print(f"c1 = {c1}") print(f"enc = {enc1}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/faonsa/faonsa.py
ctfs/Crypto/2022/faonsa/faonsa.py
#!/usr/bin/env python3 from Crypto.Util.number import * from math import gcd import sys from flag import flag def diff(a, b): assert a.bit_length() == b.bit_length() w, l = 0, a.bit_length() for _ in range(l): if bin(a)[2:][_] != bin(b)[2:][_]: w += 1 return w def sign_esa(pubkey, x, m): g, p, y = pubkey while True: k = getRandomRange(2, p-1) if gcd(k, p-1) == 1: break u = pow(g, k, p) v = (m - x * u) * inverse(k, p - 1) % (p - 1) return (u, v) def verify_esa(pubkey, sgn, m): g, p, y = pubkey u, v = sgn return pow(y, u, p) * pow(u, v, p) % p == pow(g, m, p) def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, "Hello guys! This is a another challenge on fault attack too, again ", border) pr(border, "our storage could apply at most `l' bit fault on ElGamal modulus, p,", border) pr(border, "try to sign the given message and get the flag! Have fun and enjoy!!", border) pr(border*72) pr(border, "Generating the parameters, it's time consuming ...") nbit = 256 while True: _p = getPrime(255) p = 2 * _p + 1 if isPrime(p): g = 2 if pow(g, _p, p) != 1: break else: g += 1 x = getRandomRange(2, p // 2) y = pow(g, x, p) B, l = [int(b) for b in bin(p)[2:]], 30 MSG = "4lL crypt0sy5t3ms suck5 fr0m faul7 atTaCk5 :P" m = bytes_to_long(MSG.encode('utf-8')) while True: pr("| Options: \n|\t[A]pply fault \n|\t[G]et the parameters \n|\t[S]ign the message \n|\t[V]erify the signature \n|\t[Q]uit") ans = sc().lower() if ans == 'a': _B = B pr(border, f"please send at most {l}-tuple array from indices of bits of ElGamal modulus, like: 5, 12, ...") ar = sc() try: ar = [int(_) for _ in ar.split(',')] if len(ar) <= l: for i in range(len(ar)): _B[ar[i]] = (_B[ar[i]] + 1) % 2 P = int(''.join([str(b) for b in _B]), 2) Y = pow(g, x, P) else: raise Exception('Invalid length!') except: pr(border, "Something went wrong!!") elif ans == 'g': pr(border, f'p = {p}') pr(border, f'g = {g}') pr(border, f'y = {y}') elif ans == "v": pr(border, "please send signature to verify: ") _flag, signature = False, sc() try: signature = [int(_) for _ in signature.split(',')] if verify_esa((g, P, Y), signature, m): _flag = True else: pr(border, "Your signature is not valid!!") except: pr(border, "Something went wrong!!") if _flag: die(border, "Congrats! your got the flag: " + flag) elif ans == 's': pr(border, "Please send your message to sign: ") msg = sc().encode('utf-8') if msg != MSG.encode('utf-8'): _m = bytes_to_long(msg) try: sgn = sign_esa((g, P, Y), x, _m) pr(border, f'sign = {sgn}') except: pr(border, "Something went wrong!!") else: pr(border, "Kidding me!? Really?") elif ans == 'q': die("Quitting ...") else: die("Bye bye ...") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/watery_soup/watery_soup.py
ctfs/Crypto/2022/watery_soup/watery_soup.py
#!/usr/bin/env python3 from Crypto.Util.number import * import sys from flag import flag flag = bytes_to_long(flag) assert 256 < flag.bit_length() < 512 def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, "Hi crypto-experts, send us your prime and we will mix the flag with ", border) pr(border, "it! Now can you find the flag in the mixed watery soup!? Good luck! ", border) pr(border*72) while True: pr("| Options: \n|\t[S]end the prime! \n|\t[Q]uit") ans = sc().lower() if ans == 's': pr(border, "Send your prime here: ") p = sc() try: p = int(p) except: die(border, "Your input is not valid!!") if not (128 <= p.bit_length() <= 224): die(border, "Your prime is out of bounds :(") if not isPrime(p): die(border, "Your input is NOT prime! Kidding me!?") pr(border, "Send the base here: ") g = sc() try: g = int(g) % p except: die("| Your base is not valid!!") if not (64 < g.bit_length() < 128): die(border, "Your base is too small!!") result = (pow(g ** 3 * flag, flag - g, p) * flag + flag * flag + g) % p pr(border, f"WooW, here is the mixed flag: {result}") elif ans == 'q': die(border, "Quitting ...") else: die(border, "Bye ...") if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/mino/mino.py
ctfs/Crypto/2022/mino/mino.py
#!/usr/bin/env python3 import sys from flag import flag def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "|" pr(border*72) pr(border, "Hi crypto programmers! I'm looking for some very special permutation", border) pr(border, "p name MINO such that sum(p(i) * (-2)^i) = 0 from 0 to n - 1, for ", border) pr(border, "example for n = 6, the permutation p = (4, 2, 6, 5, 3, 1) is MINO: ", border) pr(border, "4*(-2)^0 + 2*(-2)^1 + 6*(-2)^2 + 5*(-2)^3 + 3*(-2)^4 + 1*(-2)^5 = 0 ", border) pr(border, "In each step find such permutation and send to server, if there is ", border) pr(border, "NOT such permutation for given n, just send `TINP', good luck :) ", border) pr(border*72) step, final = 3, 40 while True: pr(border, f"Send a MINO permutation of length = {step} separated by comma: ") p = sc().split(',') if step % 3 == 1: if p == ['TINP']: if step == final: die(border, f"Congrats, you got the flag: {flag}") else: pr(border, "Great, try the next level :)") step += 1 else: die(border, "the answer is not correct, bye!!!") elif len(p) == step: try: p = [int(_) for _ in p] except: pr(border, "the permutation is not valid") if set(p) == set([_ for _ in range(1, step + 1)]): S = 0 for _ in range(step): S += p[_] * (-2) ** _ if S == 0: if step == final: die(border, f"Congrats, you got the flag: {flag}") else: pr(border, "Great, try the next level :)") step += 1 else: die(border, "the answer is not correct, bye!!!") else: pr(border, "the permutation is not valid!!!") else: die(border, f"the length of permutation is not equal to {step}") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/aniely/aniely.py
ctfs/Crypto/2022/aniely/aniely.py
#!/usr/bin/env python3 from struct import * from os import * from secret import passphrase, flag def aniely_stream(passphrase): def mixer(u, v): return ((u << v) & 0xffffffff) | u >> (32 - v) def forge(w, a, b, c, d): for i in range(2): w[a] = (w[a] + w[b]) & 0xffffffff w[d] = mixer(w[a] ^ w[d], 16 // (i + 1)) w[c] = (w[c] + w[d]) & 0xffffffff w[b] = mixer(w[b] ^ w[c], (12 + 2*i) // (i + 1)) bring = [0] * 16 bring[:4] = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574] bring[4:12] = unpack('<8L', passphrase) bring[12] = bring[13] = 0x0 bring[14:] = [0] * 2 while True: w = list(bring) for _ in range(10): forge(w, 0x0, 0x4, 0x8, 0xc) forge(w, 0x1, 0x5, 0x9, 0xd) forge(w, 0x2, 0x6, 0xa, 0xe) forge(w, 0x3, 0x7, 0xb, 0xf) forge(w, 0x0, 0x5, 0xa, 0xf) forge(w, 0x1, 0x6, 0xb, 0xc) forge(w, 0x2, 0x7, 0x8, 0xd) forge(w, 0x3, 0x4, 0x9, 0xe) for c in pack('<16L', *((w[_] + bring[_]) & 0xffffffff for _ in range(16))): yield c bring[12] = (bring[12] + 1) & 0xffffffff if bring[12] == 0: bring[13] = (bring[13] + 1) & 0xffffffff def aniely_encrypt(msg, passphrase): if len(passphrase) < 32: passphrase = (passphrase * (32 // len(passphrase) + 1))[:32] rand = urandom(2) * 16 return bytes(a ^ b ^ c for a, b, c in zip(msg, aniely_stream(passphrase), rand)) key = bytes(a ^ b for a, b in zip(passphrase, flag)) enc = aniely_encrypt(passphrase, key) print(f'key = {key.hex()}') print(f'enc = {enc.hex()}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/keydream/keydream.py
ctfs/Crypto/2022/keydream/keydream.py
#!/usr/bin/env python3 from Crypto.Util.number import * import string from flag import flag def randstr(l): rstr = [(string.printable[:62] + '_')[getRandomRange(0, 62)] for _ in range(l)] return ''.join(rstr) def encrypt(msg, l): while True: rstr = 'CCTF{it_is_fake_flag_' + randstr(l) + '_90OD_luCk___!!}' p = bytes_to_long(rstr.encode('utf-8')) q = bytes_to_long(rstr[::-1].encode('utf-8')) if isPrime(p) and isPrime(q): n = p * q e, m = 65537, bytes_to_long(msg.encode('utf-8')) c = pow(m, e, n) return n, c n, c = encrypt(flag, 27) print(f'n = {n}') print(f'c = {c}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false