code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def ProcessingInstruction(target, text=None): """Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. *target* is a string containing the processing instruction, *text* is a string containing the processing instruction contents, if any. """ element = Element(ProcessingInstruction) element.text = target if text: element.text = element.text + " " + text return element
Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. *target* is a string containing the processing instruction, *text* is a string containing the processing instruction contents, if any.
ProcessingInstruction
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def getroot(self): """Return root element of this tree.""" return self._root
Return root element of this tree.
getroot
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def _setroot(self, element): """Replace root element of this tree. This will discard the current contents of the tree and replace it with the given element. Use with care! """ # assert iselement(element) self._root = element
Replace root element of this tree. This will discard the current contents of the tree and replace it with the given element. Use with care!
_setroot
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def parse(self, source, parser=None): """Load external XML document into element tree. *source* is a file name or file object, *parser* is an optional parser instance that defaults to XMLParser. ParseError is raised if the parser fails to parse the document. Returns the root element of the given source document. """ close_source = False if not hasattr(source, "read"): source = open(source, "rb") close_source = True try: if parser is None: # If no parser was specified, create a default XMLParser parser = XMLParser() if hasattr(parser, '_parse_whole'): # The default XMLParser, when it comes from an accelerator, # can define an internal _parse_whole API for efficiency. # It can be used to parse the whole source without feeding # it with chunks. self._root = parser._parse_whole(source) return self._root while True: data = source.read(65536) if not data: break parser.feed(data) self._root = parser.close() return self._root finally: if close_source: source.close()
Load external XML document into element tree. *source* is a file name or file object, *parser* is an optional parser instance that defaults to XMLParser. ParseError is raised if the parser fails to parse the document. Returns the root element of the given source document.
parse
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def iter(self, tag=None): """Create and return tree iterator for the root element. The iterator loops over all elements in this tree, in document order. *tag* is a string with the tag name to iterate over (default is to return all elements). """ # assert self._root is not None return self._root.iter(tag)
Create and return tree iterator for the root element. The iterator loops over all elements in this tree, in document order. *tag* is a string with the tag name to iterate over (default is to return all elements).
iter
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def find(self, path, namespaces=None): """Find first matching element by tag name or path. Same as getroot().find(path), which is Element.find() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return the first matching element, or None if no element was found. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.find(path, namespaces)
Find first matching element by tag name or path. Same as getroot().find(path), which is Element.find() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return the first matching element, or None if no element was found.
find
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def findtext(self, path, default=None, namespaces=None): """Find first matching element by tag name or path. Same as getroot().findtext(path), which is Element.findtext() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return the first matching element, or None if no element was found. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.findtext(path, default, namespaces)
Find first matching element by tag name or path. Same as getroot().findtext(path), which is Element.findtext() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return the first matching element, or None if no element was found.
findtext
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def findall(self, path, namespaces=None): """Find all matching subelements by tag name or path. Same as getroot().findall(path), which is Element.findall(). *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return list containing all matching elements in document order. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.findall(path, namespaces)
Find all matching subelements by tag name or path. Same as getroot().findall(path), which is Element.findall(). *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return list containing all matching elements in document order.
findall
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def iterfind(self, path, namespaces=None): """Find all matching subelements by tag name or path. Same as getroot().iterfind(path), which is element.iterfind() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return an iterable yielding all matching elements in document order. """ # assert self._root is not None if path[:1] == "/": path = "." + path warnings.warn( "This search is broken in 1.3 and earlier, and will be " "fixed in a future version. If you rely on the current " "behaviour, change it to %r" % path, FutureWarning, stacklevel=2 ) return self._root.iterfind(path, namespaces)
Find all matching subelements by tag name or path. Same as getroot().iterfind(path), which is element.iterfind() *path* is a string having either an element tag or an XPath, *namespaces* is an optional mapping from namespace prefix to full name. Return an iterable yielding all matching elements in document order.
iterfind
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def write(self, file_or_filename, encoding=None, xml_declaration=None, default_namespace=None, method=None, *, short_empty_elements=True): """Write element tree to a file as XML. Arguments: *file_or_filename* -- file name or a file object opened for writing *encoding* -- the output encoding (default: US-ASCII) *xml_declaration* -- bool indicating if an XML declaration should be added to the output. If None, an XML declaration is added if encoding IS NOT either of: US-ASCII, UTF-8, or Unicode *default_namespace* -- sets the default XML namespace (for "xmlns") *method* -- either "xml" (default), "html, "text", or "c14n" *short_empty_elements* -- controls the formatting of elements that contain no content. If True (default) they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags """ if not method: method = "xml" elif method not in _serialize: raise ValueError("unknown method %r" % method) if not encoding: if method == "c14n": encoding = "utf-8" else: encoding = "us-ascii" enc_lower = encoding.lower() with _get_writer(file_or_filename, enc_lower) as write: if method == "xml" and (xml_declaration or (xml_declaration is None and enc_lower not in ("utf-8", "us-ascii", "unicode"))): declared_encoding = encoding if enc_lower == "unicode": # Retrieve the default encoding for the xml declaration import locale declared_encoding = locale.getpreferredencoding() write("<?xml version='1.0' encoding='%s'?>\n" % ( declared_encoding,)) if method == "text": _serialize_text(write, self._root) else: qnames, namespaces = _namespaces(self._root, default_namespace) serialize = _serialize[method] serialize(write, self._root, qnames, namespaces, short_empty_elements=short_empty_elements)
Write element tree to a file as XML. Arguments: *file_or_filename* -- file name or a file object opened for writing *encoding* -- the output encoding (default: US-ASCII) *xml_declaration* -- bool indicating if an XML declaration should be added to the output. If None, an XML declaration is added if encoding IS NOT either of: US-ASCII, UTF-8, or Unicode *default_namespace* -- sets the default XML namespace (for "xmlns") *method* -- either "xml" (default), "html, "text", or "c14n" *short_empty_elements* -- controls the formatting of elements that contain no content. If True (default) they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags
write
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def register_namespace(prefix, uri): """Register a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. *prefix* is the namespace prefix, *uri* is a namespace uri. Tags and attributes in this namespace will be serialized with prefix if possible. ValueError is raised if prefix is reserved or is invalid. """ if re.match(r"ns\d+$", prefix): raise ValueError("Prefix format reserved for internal use") for k, v in list(_namespace_map.items()): if k == uri or v == prefix: del _namespace_map[k] _namespace_map[uri] = prefix
Register a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. *prefix* is the namespace prefix, *uri* is a namespace uri. Tags and attributes in this namespace will be serialized with prefix if possible. ValueError is raised if prefix is reserved or is invalid.
register_namespace
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def tostring(element, encoding=None, method=None, *, short_empty_elements=True): """Generate string representation of XML element. All subelements are included. If encoding is "unicode", a string is returned. Otherwise a bytestring is returned. *element* is an Element instance, *encoding* is an optional output encoding defaulting to US-ASCII, *method* is an optional output which can be one of "xml" (default), "html", "text" or "c14n". Returns an (optionally) encoded string containing the XML data. """ stream = io.StringIO() if encoding == 'unicode' else io.BytesIO() ElementTree(element).write(stream, encoding, method=method, short_empty_elements=short_empty_elements) return stream.getvalue()
Generate string representation of XML element. All subelements are included. If encoding is "unicode", a string is returned. Otherwise a bytestring is returned. *element* is an Element instance, *encoding* is an optional output encoding defaulting to US-ASCII, *method* is an optional output which can be one of "xml" (default), "html", "text" or "c14n". Returns an (optionally) encoded string containing the XML data.
tostring
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def dump(elem): """Write element tree or element structure to sys.stdout. This function should be used for debugging only. *elem* is either an ElementTree, or a single Element. The exact output format is implementation dependent. In this version, it's written as an ordinary XML file. """ # debugging if not isinstance(elem, ElementTree): elem = ElementTree(elem) elem.write(sys.stdout, encoding="unicode") tail = elem.getroot().tail if not tail or tail[-1] != "\n": sys.stdout.write("\n")
Write element tree or element structure to sys.stdout. This function should be used for debugging only. *elem* is either an ElementTree, or a single Element. The exact output format is implementation dependent. In this version, it's written as an ordinary XML file.
dump
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def parse(source, parser=None): """Parse XML document into element tree. *source* is a filename or file object containing XML data, *parser* is an optional parser instance defaulting to XMLParser. Return an ElementTree instance. """ tree = ElementTree() tree.parse(source, parser) return tree
Parse XML document into element tree. *source* is a filename or file object containing XML data, *parser* is an optional parser instance defaulting to XMLParser. Return an ElementTree instance.
parse
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def iterparse(source, events=None, parser=None): """Incrementally parse XML document into ElementTree. This class also reports what's going on to the user based on the *events* it is initialized with. The supported events are the strings "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get detailed namespace information). If *events* is omitted, only "end" events are reported. *source* is a filename or file object containing XML data, *events* is a list of events to report back, *parser* is an optional parser instance. Returns an iterator providing (event, elem) pairs. """ # Use the internal, undocumented _parser argument for now; When the # parser argument of iterparse is removed, this can be killed. pullparser = XMLPullParser(events=events, _parser=parser) def iterator(): try: while True: yield from pullparser.read_events() # load event buffer data = source.read(16 * 1024) if not data: break pullparser.feed(data) root = pullparser._close_and_return_root() yield from pullparser.read_events() it.root = root finally: if close_source: source.close() class IterParseIterator(collections.abc.Iterator): __next__ = iterator().__next__ it = IterParseIterator() it.root = None del iterator, IterParseIterator close_source = False if not hasattr(source, "read"): source = open(source, "rb") close_source = True return it
Incrementally parse XML document into ElementTree. This class also reports what's going on to the user based on the *events* it is initialized with. The supported events are the strings "start", "end", "start-ns" and "end-ns" (the "ns" events are used to get detailed namespace information). If *events* is omitted, only "end" events are reported. *source* is a filename or file object containing XML data, *events* is a list of events to report back, *parser* is an optional parser instance. Returns an iterator providing (event, elem) pairs.
iterparse
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def feed(self, data): """Feed encoded data to parser.""" if self._parser is None: raise ValueError("feed() called after end of stream") if data: try: self._parser.feed(data) except SyntaxError as exc: self._events_queue.append(exc)
Feed encoded data to parser.
feed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def close(self): """Finish feeding data to parser. Unlike XMLParser, does not return the root element. Use read_events() to consume elements from XMLPullParser. """ self._close_and_return_root()
Finish feeding data to parser. Unlike XMLParser, does not return the root element. Use read_events() to consume elements from XMLPullParser.
close
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def read_events(self): """Return an iterator over currently available (event, elem) pairs. Events are consumed from the internal event queue as they are retrieved from the iterator. """ events = self._events_queue while events: event = events.popleft() if isinstance(event, Exception): raise event else: yield event
Return an iterator over currently available (event, elem) pairs. Events are consumed from the internal event queue as they are retrieved from the iterator.
read_events
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def XML(text, parser=None): """Parse XML document from string constant. This function can be used to embed "XML Literals" in Python code. *text* is a string containing XML data, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an Element instance. """ if not parser: parser = XMLParser(target=TreeBuilder()) parser.feed(text) return parser.close()
Parse XML document from string constant. This function can be used to embed "XML Literals" in Python code. *text* is a string containing XML data, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an Element instance.
XML
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def XMLID(text, parser=None): """Parse XML document from string constant for its IDs. *text* is a string containing XML data, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an (Element, dict) tuple, in which the dict maps element id:s to elements. """ if not parser: parser = XMLParser(target=TreeBuilder()) parser.feed(text) tree = parser.close() ids = {} for elem in tree.iter(): id = elem.get("id") if id: ids[id] = elem return tree, ids
Parse XML document from string constant for its IDs. *text* is a string containing XML data, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an (Element, dict) tuple, in which the dict maps element id:s to elements.
XMLID
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def fromstringlist(sequence, parser=None): """Parse XML document from sequence of string fragments. *sequence* is a list of other sequence, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an Element instance. """ if not parser: parser = XMLParser(target=TreeBuilder()) for text in sequence: parser.feed(text) return parser.close()
Parse XML document from sequence of string fragments. *sequence* is a list of other sequence, *parser* is an optional parser instance, defaulting to the standard XMLParser. Returns an Element instance.
fromstringlist
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def close(self): """Flush builder buffers and return toplevel document Element.""" assert len(self._elem) == 0, "missing end tags" assert self._last is not None, "missing toplevel element" return self._last
Flush builder buffers and return toplevel document Element.
close
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def data(self, data): """Add text to current element.""" self._data.append(data)
Add text to current element.
data
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def start(self, tag, attrs): """Open new element and return it. *tag* is the element name, *attrs* is a dict containing element attributes. """ self._flush() self._last = elem = self._factory(tag, attrs) if self._elem: self._elem[-1].append(elem) self._elem.append(elem) self._tail = 0 return elem
Open new element and return it. *tag* is the element name, *attrs* is a dict containing element attributes.
start
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def end(self, tag): """Close and return current Element. *tag* is the element name. """ self._flush() self._last = self._elem.pop() assert self._last.tag == tag,\ "end tag mismatch (expected %s, got %s)" % ( self._last.tag, tag) self._tail = 1 return self._last
Close and return current Element. *tag* is the element name.
end
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def doctype(self, name, pubid, system): """(Deprecated) Handle doctype declaration *name* is the Doctype name, *pubid* is the public identifier, and *system* is the system identifier. """ warnings.warn( "This method of XMLParser is deprecated. Define doctype() " "method on the TreeBuilder target.", DeprecationWarning, )
(Deprecated) Handle doctype declaration *name* is the Doctype name, *pubid* is the public identifier, and *system* is the system identifier.
doctype
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def feed(self, data): """Feed encoded data to parser.""" try: self.parser.Parse(data, 0) except self._error as v: self._raiseerror(v)
Feed encoded data to parser.
feed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def close(self): """Finish feeding data to parser and return element structure.""" try: self.parser.Parse("", 1) # end of data except self._error as v: self._raiseerror(v) try: close_handler = self.target.close except AttributeError: pass else: return close_handler() finally: # get rid of circular references del self.parser, self._parser del self.target, self._target
Finish feeding data to parser and return element structure.
close
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/xml/etree/ElementTree.py
MIT
def auth(): """Return a token once the user is successfully authenticated. """ user = request.args.get("user") password = request.args.get("password", "") if not user or user not in USER_DB: return response("Bad or missing 'user'", 400) password_hash = USER_DB[user] given = hashlib.pbkdf2_hmac("SHA256", password.encode(), user.encode(), 1000).hex() if password_hash != given: return response("Bad 'password'", 400) # User is authenticated! Return a super strong token. return response(encrypt_token(user, SERVER_KEY).hex())
Return a token once the user is successfully authenticated.
auth
python
sajjadium/ctf-archives
ctfs/Block/2023/crypto/enCRCroach/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Block/2023/crypto/enCRCroach/server.py
MIT
def read(path: str): """Read a static file under the user's directory. Lists contents if no path is provided. Decrypts the token to auth the request and get the user's name. """ try: user = decrypt_token(bytes.fromhex(request.args.get("token", "")), SERVER_KEY) except ValueError: user = None if not user: return response("Bad or missing token", 400) user_dir = werkzeug.security.safe_join("users", user) if path is None: listing = "\n".join(sorted(os.listdir(os.path.join(app.root_path, user_dir)))) return response(listing) return send_from_directory(user_dir, path)
Read a static file under the user's directory. Lists contents if no path is provided. Decrypts the token to auth the request and get the user's name.
read
python
sajjadium/ctf-archives
ctfs/Block/2023/crypto/enCRCroach/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Block/2023/crypto/enCRCroach/server.py
MIT
def encrypt_token(user: str, key: bytes) -> bytes: """Encrypt the user string using "authenticated encryption". JWTs and JWEs scare me. Too many CVEs! I think I can do better... Here's the token format we use to encrypt and authenticate a user's name. This is sent to/from the server in ascii-hex: len : 16 variable 42 8 data: IV || USER || NONCE || MAC '------------------------' Encrypted """ assert len(key) == KEY_LEN user_bytes = user.encode("utf-8") iv = secrets.token_bytes(IV_LEN) nonce = secrets.token_bytes(NONCE_LEN) cipher = Cipher(algorithms.AES(key), modes.CTR(iv)).encryptor() mac = gen_mac(iv + user_bytes + nonce) ciphertext = cipher.update(user_bytes + nonce + mac) + cipher.finalize() return iv + ciphertext
Encrypt the user string using "authenticated encryption". JWTs and JWEs scare me. Too many CVEs! I think I can do better... Here's the token format we use to encrypt and authenticate a user's name. This is sent to/from the server in ascii-hex: len : 16 variable 42 8 data: IV || USER || NONCE || MAC '------------------------' Encrypted
encrypt_token
python
sajjadium/ctf-archives
ctfs/Block/2023/crypto/enCRCroach/server.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Block/2023/crypto/enCRCroach/server.py
MIT
def segregate(str): """3.1 Basic code point segregation""" base = bytearray() extended = set() for c in str: if ord(c) < 128: base.append(ord(c)) else: extended.add(c) extended = sorted(extended) return bytes(base), extended
3.1 Basic code point segregation
segregate
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def selective_len(str, max): """Return the length of str, considering only characters below max.""" res = 0 for c in str: if ord(c) < max: res += 1 return res
Return the length of str, considering only characters below max.
selective_len
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def selective_find(str, char, index, pos): """Return a pair (index, pos), indicating the next occurrence of char in str. index is the position of the character considering only ordinals up to and including char, and pos is the position in the full string. index/pos is the starting position in the full string.""" l = len(str) while 1: pos += 1 if pos == l: return (-1, -1) c = str[pos] if c == char: return index+1, pos elif c < char: index += 1
Return a pair (index, pos), indicating the next occurrence of char in str. index is the position of the character considering only ordinals up to and including char, and pos is the position in the full string. index/pos is the starting position in the full string.
selective_find
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def insertion_unsort(str, extended): """3.2 Insertion unsort coding""" oldchar = 0x80 result = [] oldindex = -1 for c in extended: index = pos = -1 char = ord(c) curlen = selective_len(str, char) delta = (curlen+1) * (char - oldchar) while 1: index,pos = selective_find(str,c,index,pos) if index == -1: break delta += index - oldindex result.append(delta-1) oldindex = index delta = 0 oldchar = char return result
3.2 Insertion unsort coding
insertion_unsort
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def generate_generalized_integer(N, bias): """3.3 Generalized variable-length integers""" result = bytearray() j = 0 while 1: t = T(j, bias) if N < t: result.append(digits[N]) return bytes(result) result.append(digits[t + ((N - t) % (36 - t))]) N = (N - t) // (36 - t) j += 1
3.3 Generalized variable-length integers
generate_generalized_integer
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def generate_integers(baselen, deltas): """3.4 Bias adaptation""" # Punycode parameters: initial bias = 72, damp = 700, skew = 38 result = bytearray() bias = 72 for points, delta in enumerate(deltas): s = generate_generalized_integer(delta, bias) result.extend(s) bias = adapt(delta, points==0, baselen+points+1) return bytes(result)
3.4 Bias adaptation
generate_integers
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def decode_generalized_number(extended, extpos, bias, errors): """3.3 Generalized variable-length integers""" result = 0 w = 1 j = 0 while 1: try: char = ord(extended[extpos]) except IndexError: if errors == "strict": raise UnicodeError("incomplete punicode string") return extpos + 1, None extpos += 1 if 0x41 <= char <= 0x5A: # A-Z digit = char - 0x41 elif 0x30 <= char <= 0x39: digit = char - 22 # 0x30-26 elif errors == "strict": raise UnicodeError("Invalid extended code point '%s'" % extended[extpos-1]) else: return extpos, None t = T(j, bias) result += digit * w if digit < t: return extpos, result w = w * (36 - t) j += 1
3.3 Generalized variable-length integers
decode_generalized_number
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def insertion_sort(base, extended, errors): """3.2 Insertion unsort coding""" char = 0x80 pos = -1 bias = 72 extpos = 0 while extpos < len(extended): newpos, delta = decode_generalized_number(extended, extpos, bias, errors) if delta is None: # There was an error in decoding. We can't continue because # synchronization is lost. return base pos += delta+1 char += pos // (len(base) + 1) if char > 0x10FFFF: if errors == "strict": raise UnicodeError("Invalid character U+%x" % char) char = ord('?') pos = pos % (len(base) + 1) base = base[:pos] + chr(char) + base[pos:] bias = adapt(delta, (extpos == 0), len(base)) extpos = newpos return base
3.2 Insertion unsort coding
insertion_sort
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/punycode.py
MIT
def normalize_encoding(encoding): """ Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are collapsed and replaced with a single underscore, e.g. ' -;#' becomes '_'. Leading and trailing underscores are removed. Note that encoding names should be ASCII only. """ if isinstance(encoding, bytes): encoding = str(encoding, "ascii") chars = [] punct = False for c in encoding: if c.isalnum() or c == '.': if punct and chars: chars.append('_') if c.isascii(): chars.append(c) punct = False else: punct = True return ''.join(chars)
Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are collapsed and replaced with a single underscore, e.g. ' -;#' becomes '_'. Leading and trailing underscores are removed. Note that encoding names should be ASCII only.
normalize_encoding
python
sajjadium/ctf-archives
ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/__init__.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2022/Quals/adamd/lib/python3.12/encodings/__init__.py
MIT
def make_alice(plaintext=alice_plain, key=alice_key, name='alice'): """ Make Alice network, who encrypts messages with the key. """ ainput = keras.layers.concatenate([plaintext, key], axis=1) adense1 = keras.layers.Dense(units=(m_bits + k_bits))(ainput) adense1a = keras.layers.Activation('sigmoid')(adense1) areshape = keras.layers.Reshape((m_bits + k_bits, 1,))(adense1a) aconv1 = keras.layers.Conv1D(filters=2, kernel_size=4, strides=1, padding=pad)(areshape) aconv1a = keras.layers.Activation('sigmoid')(aconv1) aconv2 = keras.layers.Conv1D(filters=4, kernel_size=2, strides=2, padding=pad)(aconv1a) aconv2a = keras.layers.Activation('sigmoid')(aconv2) aconv3 = keras.layers.Conv1D(filters=4, kernel_size=1, strides=1, padding=pad)(aconv2a) aconv3a = keras.layers.Activation('sigmoid')(aconv3) aconv4 = keras.layers.Conv1D(filters=1, kernel_size=1, strides=1, padding=pad)(aconv3a) aconv4a = keras.layers.Activation('tanh')(aconv4) aoutput = keras.layers.Flatten()(aconv4a) return keras.models.Model([plaintext, key], aoutput, name=name)
Make Alice network, who encrypts messages with the key.
make_alice
python
sajjadium/ctf-archives
ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
MIT
def make_bob(ciphertext=bob_cipher, key=bob_key, name='bob'): """ Make bob network, who decrypts messages with the key. """ binput = keras.layers.concatenate([ciphertext, key], axis=1) bdense1 = keras.layers.Dense(units=(m_bits + k_bits))(binput) bdense1a = keras.layers.Activation('sigmoid')(bdense1) breshape = keras.layers.Reshape((m_bits + k_bits, 1,))(bdense1a) bconv1 = keras.layers.Conv1D(filters=2, kernel_size=4, strides=1, padding=pad)(breshape) bconv1a = keras.layers.Activation('sigmoid')(bconv1) bconv2 = keras.layers.Conv1D(filters=4, kernel_size=2, strides=2, padding=pad)(bconv1a) bconv2a = keras.layers.Activation('sigmoid')(bconv2) bconv3 = keras.layers.Conv1D(filters=4, kernel_size=1, strides=1, padding=pad)(bconv2a) bconv3a = keras.layers.Activation('sigmoid')(bconv3) bconv4 = keras.layers.Conv1D(filters=1, kernel_size=1, strides=1, padding=pad)(bconv3a) bconv4a = keras.layers.Activation('tanh')(bconv4) boutput = keras.layers.Flatten()(bconv4a) return keras.models.Model([ciphertext, key], boutput, name=name)
Make bob network, who decrypts messages with the key.
make_bob
python
sajjadium/ctf-archives
ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
MIT
def make_eve(ciphertext=eve_cipher, name='eve'): """ Make Eve network, who tries to decrypt messages without the key. """ edense1 = keras.layers.Dense(units=(c_bits + k_bits))(ciphertext) edense1a = keras.layers.Activation('sigmoid')(edense1) edense2 = keras.layers.Dense(units=(c_bits + k_bits))(edense1a) edense2a = keras.layers.Activation('sigmoid')(edense2) ereshape = keras.layers.Reshape((c_bits + k_bits, 1,))(edense2a) econv1 = keras.layers.Conv1D(filters=2, kernel_size=4, strides=1, padding=pad)(ereshape) econv1a = keras.layers.Activation('sigmoid')(econv1) econv2 = keras.layers.Conv1D(filters=4, kernel_size=2, strides=2, padding=pad)(econv1a) econv2a = keras.layers.Activation('sigmoid')(econv2) econv3 = keras.layers.Conv1D(filters=4, kernel_size=1, strides=1, padding=pad)(econv2a) econv3a = keras.layers.Activation('sigmoid')(econv3) econv4 = keras.layers.Conv1D(filters=1, kernel_size=1, strides=1, padding=pad)(econv3a) econv4a = keras.layers.Activation('tanh')(econv4) eoutput = keras.layers.Flatten()(econv4a)# Eve's attempt at guessing the plaintext return keras.models.Model(eve_cipher, eoutput, name=name)
Make Eve network, who tries to decrypt messages without the key.
make_eve
python
sajjadium/ctf-archives
ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
MIT
def encode_message(m): """ Encodes bytes into ML inputs. """ n = int(binascii.hexlify(m).ljust(m_bytes*2, b'0'), 16) encoded = [ (-1 if b == '0' else 1 ) for b in bin(n)[2:].rjust(m_bits, '0') ] assert decode_message(encoded) == m return encoded
Encodes bytes into ML inputs.
encode_message
python
sajjadium/ctf-archives
ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
MIT
def decode_message(a, threshold=0): """ Decodes ML output into bytes. """ i = int(''.join('0' if b < threshold else '1' for b in a), 2) return binascii.unhexlify(hex(i)[2:].rjust(m_bytes*2, '0'))
Decodes ML output into bytes.
decode_message
python
sajjadium/ctf-archives
ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DEFCON/2021/Quals/crypto/smart-cryptooo/anc.py
MIT
def __init__(self, x=None): """Initialize an instance. Optional argument x controls seeding, as for Random.seed(). """ self.seed(x) self.gauss_next = None
Initialize an instance. Optional argument x controls seeding, as for Random.seed().
__init__
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def seed(self, a=None, version=1): """Initialize internal state from a seed. The only supported seed types are None, int, float, str, bytes, and bytearray. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds. """ if version == 1 and isinstance(a, (str, bytes)): a = a.decode('latin-1') if isinstance(a, bytes) else a x = ord(a[0]) << 7 if a else 0 for c in map(ord, a): x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF x ^= len(a) a = -2 if x == -1 else x elif version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str): a = a.encode() a = int.from_bytes(a + _sha512(a).digest()) elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)): raise TypeError('The only supported seed types are: None,\n' 'int, float, str, bytes, and bytearray.') super().seed(a) self.gauss_next = None
Initialize internal state from a seed. The only supported seed types are None, int, float, str, bytes, and bytearray. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds.
seed
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def getstate(self): """Return internal state; can be passed to setstate() later.""" return self.VERSION, super().getstate(), self.gauss_next
Return internal state; can be passed to setstate() later.
getstate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 3: version, internalstate, self.gauss_next = state super().setstate(internalstate) elif version == 2: version, internalstate, self.gauss_next = state # In version 2, the state was saved as signed ints, which causes # inconsistencies between 32/64-bit systems. The state is # really unsigned 32-bit ints, so we convert negative ints from # version 2 to positive longs for version 3. try: internalstate = tuple(x % (2 ** 32) for x in internalstate) except ValueError as e: raise TypeError from e super().setstate(internalstate) else: raise ValueError("state with version %s passed to " "Random.setstate() of version %s" % (version, self.VERSION))
Restore internal state from object returned by getstate().
setstate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def __init_subclass__(cls, /, **kwargs): """Control how subclasses generate random integers. The algorithm a subclass can use depends on the random() and/or getrandbits() implementation available to it and determines whether it can generate random integers from arbitrarily large ranges. """ for c in cls.__mro__: if '_randbelow' in c.__dict__: # just inherit it break if 'getrandbits' in c.__dict__: cls._randbelow = cls._randbelow_with_getrandbits break if 'random' in c.__dict__: cls._randbelow = cls._randbelow_without_getrandbits break
Control how subclasses generate random integers. The algorithm a subclass can use depends on the random() and/or getrandbits() implementation available to it and determines whether it can generate random integers from arbitrarily large ranges.
__init_subclass__
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF): """Return a random int in the range [0,n). Defined for n > 0. The implementation does not use getrandbits, but only random. """ random = self.random if n >= maxsize: _warn("Underlying random() generator does not supply \n" "enough bits to choose from a population range this large.\n" "To remove the range limitation, add a getrandbits() method.") return _floor(random() * n) rem = maxsize % n limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 r = random() while r >= limit: r = random() return _floor(r * maxsize) % n
Return a random int in the range [0,n). Defined for n > 0. The implementation does not use getrandbits, but only random.
_randbelow_without_getrandbits
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def randbytes(self, n): """Generate n random bytes.""" return self.getrandbits(n * 8).to_bytes(n, 'little')
Generate n random bytes.
randbytes
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def randrange(self, start, stop=None, step=_ONE): """Choose a random item from range(stop) or range(start, stop[, step]). Roughly equivalent to ``choice(range(start, stop, step))`` but supports arbitrarily large ranges and is optimized for common cases. """ # This code is a bit messy to make it fast for the # common case while still doing adequate error checking. try: istart = _index(start) except TypeError: istart = int(start) if istart != start: _warn('randrange() will raise TypeError in the future', DeprecationWarning, 2) raise ValueError("non-integer arg 1 for randrange()") _warn('non-integer arguments to randrange() have been deprecated ' 'since Python 3.10 and will be removed in a subsequent ' 'version', DeprecationWarning, 2) if stop is None: # We don't check for "step != 1" because it hasn't been # type checked and converted to an integer yet. if step is not _ONE: raise TypeError('Missing a non-None stop argument') if istart > 0: return self._randbelow(istart) raise ValueError("empty range for randrange()") # stop argument supplied. try: istop = _index(stop) except TypeError: istop = int(stop) if istop != stop: _warn('randrange() will raise TypeError in the future', DeprecationWarning, 2) raise ValueError("non-integer stop for randrange()") _warn('non-integer arguments to randrange() have been deprecated ' 'since Python 3.10 and will be removed in a subsequent ' 'version', DeprecationWarning, 2) width = istop - istart try: istep = _index(step) except TypeError: istep = int(step) if istep != step: _warn('randrange() will raise TypeError in the future', DeprecationWarning, 2) raise ValueError("non-integer step for randrange()") _warn('non-integer arguments to randrange() have been deprecated ' 'since Python 3.10 and will be removed in a subsequent ' 'version', DeprecationWarning, 2) # Fast path. if istep == 1: if width > 0: return istart + self._randbelow(width) raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width)) # Non-unit step argument supplied. if istep > 0: n = (width + istep - 1) // istep elif istep < 0: n = (width + istep + 1) // istep else: raise ValueError("zero step for randrange()") if n <= 0: raise ValueError("empty range for randrange()") return istart + istep * self._randbelow(n)
Choose a random item from range(stop) or range(start, stop[, step]). Roughly equivalent to ``choice(range(start, stop, step))`` but supports arbitrarily large ranges and is optimized for common cases.
randrange
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def randint(self, a, b): """Return random integer in range [a, b], including both end points. """ return self.randrange(a, b+1)
Return random integer in range [a, b], including both end points.
randint
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def choice(self, seq): """Choose a random element from a non-empty sequence.""" if not seq: raise IndexError('Cannot choose from an empty sequence') return seq[self._randbelow(len(seq))]
Choose a random element from a non-empty sequence.
choice
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def shuffle(self, x): """Shuffle list x in place, and return None.""" randbelow = self._randbelow for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = randbelow(i + 1) x[i], x[j] = x[j], x[i]
Shuffle list x in place, and return None.
shuffle
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def sample(self, population, k, *, counts=None): """Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. Repeated elements can be specified one at a time or with the optional counts parameter. For example: sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to: sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5) To choose a sample from a range of integers, use range() for the population argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) """ # Sampling without replacement entails tracking either potential # selections (the pool) in a list or previous selections in a set. # When the number of selections is small compared to the # population, then tracking selections is efficient, requiring # only a small set and an occasional reselection. For # a larger number of selections, the pool tracking method is # preferred since the list takes less space than the # set and it doesn't suffer from frequent reselections. # The number of calls to _randbelow() is kept at or near k, the # theoretical minimum. This is important because running time # is dominated by _randbelow() and because it extracts the # least entropy from the underlying random number generators. # Memory requirements are kept to the smaller of a k-length # set or an n-length list. # There are other sampling algorithms that do not require # auxiliary memory, but they were rejected because they made # too many calls to _randbelow(), making them slower and # causing them to eat more entropy than necessary. if not isinstance(population, _Sequence): raise TypeError("Population must be a sequence. " "For dicts or sets, use sorted(d).") n = len(population) if counts is not None: cum_counts = list(_accumulate(counts)) if len(cum_counts) != n: raise ValueError('The number of counts does not match the population') total = cum_counts.pop() if not isinstance(total, int): raise TypeError('Counts must be integers') if total <= 0: raise ValueError('Total of counts must be greater than zero') selections = self.sample(range(total), k=k) bisect = _bisect return [population[bisect(cum_counts, s)] for s in selections] randbelow = self._randbelow if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative") result = [None] * k setsize = 21 # size of a small set minus size of an empty list if k > 5: setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets if n <= setsize: # An n-length list is smaller than a k-length set. # Invariant: non-selected at pool[0 : n-i] pool = list(population) for i in range(k): j = randbelow(n - i) result[i] = pool[j] pool[j] = pool[n - i - 1] # move non-selected item into vacancy else: selected = set() selected_add = selected.add for i in range(k): j = randbelow(n) while j in selected: j = randbelow(n) selected_add(j) result[i] = population[j] return result
Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. Repeated elements can be specified one at a time or with the optional counts parameter. For example: sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to: sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5) To choose a sample from a range of integers, use range() for the population argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60)
sample
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def choices(self, population, weights=None, *, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ random = self.random n = len(population) if cum_weights is None: if weights is None: floor = _floor n += 0.0 # convert to float for a small speed improvement return [population[floor(random() * n)] for i in _repeat(None, k)] try: cum_weights = list(_accumulate(weights)) except TypeError: if not isinstance(weights, int): raise k = weights raise TypeError( f'The number of choices must be a keyword argument: {k=}' ) from None elif weights is not None: raise TypeError('Cannot specify both weights and cumulative weights') if len(cum_weights) != n: raise ValueError('The number of weights does not match the population') total = cum_weights[-1] + 0.0 # convert to float if total <= 0.0: raise ValueError('Total of weights must be greater than zero') if not _isfinite(total): raise ValueError('Total of weights must be finite') bisect = _bisect hi = n - 1 return [population[bisect(cum_weights, random() * total, 0, hi)] for i in _repeat(None, k)]
Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability.
choices
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def triangular(self, low=0.0, high=1.0, mode=None): """Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution """ u = self.random() try: c = 0.5 if mode is None else (mode - low) / (high - low) except ZeroDivisionError: return low if u > c: u = 1.0 - u c = 1.0 - c low, high = high, low return low + (high - low) * _sqrt(u * c)
Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution
triangular
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def normalvariate(self, mu=0.0, sigma=1.0): """Normal distribution. mu is the mean, and sigma is the standard deviation. """ # Uses Kinderman and Monahan method. Reference: Kinderman, # A.J. and Monahan, J.F., "Computer generation of random # variables using the ratio of uniform deviates", ACM Trans # Math Software, 3, (1977), pp257-260. random = self.random while True: u1 = random() u2 = 1.0 - random() z = NV_MAGICCONST * (u1 - 0.5) / u2 zz = z * z / 4.0 if zz <= -_log(u2): break return mu + z * sigma
Normal distribution. mu is the mean, and sigma is the standard deviation.
normalvariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def gauss(self, mu=0.0, sigma=1.0): """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. """ # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z * sigma
Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls.
gauss
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def lognormvariate(self, mu, sigma): """Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero. """ return _exp(self.normalvariate(mu, sigma))
Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.
lognormvariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def expovariate(self, lambd): """Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative. """ # lambd: rate lambd = 1/mean # ('lambda' is a Python reserved word) # we use 1-random() instead of random() to preclude the # possibility of taking the log of zero. return -_log(1.0 - self.random()) / lambd
Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.
expovariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def vonmisesvariate(self, mu, kappa): """Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. """ # Based upon an algorithm published in: Fisher, N.I., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. # Thanks to Magnus Kessler for a correction to the # implementation of step 4. random = self.random if kappa <= 1e-6: return TWOPI * random() s = 0.5 / kappa r = s + _sqrt(1.0 + s * s) while True: u1 = random() z = _cos(_pi * u1) d = z / (r + z) u2 = random() if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d): break q = 1.0 / r f = (q + z) / (1.0 + q * z) u3 = random() if u3 > 0.5: theta = (mu + _acos(f)) % TWOPI else: theta = (mu - _acos(f)) % TWOPI return theta
Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.
vonmisesvariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha """ # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 # Warning: a few older sources define the gamma distribution in terms # of alpha > -1.0 if alpha <= 0.0 or beta <= 0.0: raise ValueError('gammavariate: alpha and beta must be > 0.0') random = self.random if alpha > 1.0: # Uses R.C.H. Cheng, "The generation of Gamma # variables with non-integral shape parameters", # Applied Statistics, (1977), 26, No. 1, p71-74 ainv = _sqrt(2.0 * alpha - 1.0) bbb = alpha - LOG4 ccc = alpha + ainv while True: u1 = random() if not 1e-7 < u1 < 0.9999999: continue u2 = 1.0 - random() v = _log(u1 / (1.0 - u1)) / ainv x = alpha * _exp(v) z = u1 * u1 * u2 r = bbb + ccc * v - x if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z): return x * beta elif alpha == 1.0: # expovariate(1/beta) return -_log(1.0 - random()) * beta else: # alpha is between 0 and 1 (exclusive) # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle while True: u = random() b = (_e + alpha) / _e p = b * u if p <= 1.0: x = p ** (1.0 / alpha) else: x = -_log((b - p) / alpha) u1 = random() if p > 1.0: if u1 <= x ** (alpha - 1.0): break elif u1 <= _exp(-x): break return x * beta
Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha
gammavariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def betavariate(self, alpha, beta): """Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. """ ## See ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html ## for Ivan Frohne's insightful analysis of why the original implementation: ## ## def betavariate(self, alpha, beta): ## # Discrete Event Simulation in C, pp 87-88. ## ## y = self.expovariate(alpha) ## z = self.expovariate(1.0/beta) ## return z/(y+z) ## ## was dead wrong, and how it probably got that way. # This version due to Janne Sinkkonen, and matches all the std # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). y = self.gammavariate(alpha, 1.0) if y: return y / (y + self.gammavariate(beta, 1.0)) return 0.0
Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.
betavariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def paretovariate(self, alpha): """Pareto distribution. alpha is the shape parameter.""" # Jain, pg. 495 u = 1.0 - self.random() return u ** (-1.0 / alpha)
Pareto distribution. alpha is the shape parameter.
paretovariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def weibullvariate(self, alpha, beta): """Weibull distribution. alpha is the scale parameter and beta is the shape parameter. """ # Jain, pg. 499; bug fix courtesy Bill Arms u = 1.0 - self.random() return alpha * (-_log(u)) ** (1.0 / beta)
Weibull distribution. alpha is the scale parameter and beta is the shape parameter.
weibullvariate
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def random(self): """Get the next random number in the range [0.0, 1.0).""" return (int.from_bytes(_urandom(7)) >> 3) * RECIP_BPF
Get the next random number in the range [0.0, 1.0).
random
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def getrandbits(self, k): """getrandbits(k) -> x. Generates an int with k random bits.""" if k < 0: raise ValueError('number of bits must be non-negative') numbytes = (k + 7) // 8 # bits / 8 and rounded up x = int.from_bytes(_urandom(numbytes)) return x >> (numbytes * 8 - k) # trim excess bits
getrandbits(k) -> x. Generates an int with k random bits.
getrandbits
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def randbytes(self, n): """Generate n random bytes.""" # os.urandom(n) fails with ValueError for n < 0 # and returns an empty bytes string for n == 0. return _urandom(n)
Generate n random bytes.
randbytes
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Modnar/random.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Modnar/random.py
MIT
def bytes2matrix(text): """ Converts a 16-byte array into a 4x4 matrix. """ return [list(text[i:i+4]) for i in range(0, len(text), 4)]
Converts a 16-byte array into a 4x4 matrix.
bytes2matrix
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
MIT
def matrix2bytes(matrix): """ Converts a 4x4 matrix into a 16-byte array. """ return bytes(sum(matrix, []))
Converts a 4x4 matrix into a 16-byte array.
matrix2bytes
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
MIT
def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i^j for i, j in zip(a, b))
Returns a new byte array with the elements xor'ed.
xor_bytes
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
MIT
def pad(plaintext): """ Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes. Note that if the plaintext size is a multiple of 16, a whole block will be added. """ padding_len = 16 - (len(plaintext) % 16) padding = bytes([padding_len] * padding_len) return plaintext + padding
Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes. Note that if the plaintext size is a multiple of 16, a whole block will be added.
pad
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
MIT
def __init__(self, master_key): """ Initializes the object with a given key. """ assert len(master_key) in notAES.rounds_by_key_size self.n_rounds = notAES.rounds_by_key_size[len(master_key)] self._key_matrices = self._expand_key(master_key)
Initializes the object with a given key.
__init__
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
MIT
def _expand_key(self, master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Initialize round keys with raw key material. key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (self.n_rounds + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: # Run word through S-box in the fourth iteration when using a # 256-bit key. word = [s_box[b] for b in word] # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
Expands and returns a list of key matrices for the given master_key.
_expand_key
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
MIT
def encrypt_block(self, plaintext): """ Encrypts a single block of 16 byte long plaintext. """ assert len(plaintext) == 16 plain_state = bytes2matrix(plaintext) add_round_key(plain_state, self._key_matrices[0]) for i in range(1, self.n_rounds): sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, self._key_matrices[i]) sub_bytes(plain_state) shift_rows(plain_state) add_round_key(plain_state, self._key_matrices[-1]) return matrix2bytes(plain_state)
Encrypts a single block of 16 byte long plaintext.
encrypt_block
python
sajjadium/ctf-archives
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
MIT
def api_new(): """Add a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['title'], str) assert isinstance(data['content'], str) except: return flask.abort(400, "Invalid request") err, post_id = db.add(data['title'], get_username(), data['content']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'id': post_id})
Add a blog post
api_new
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def api_delete(): """Delete a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['id'], str) except: return flask.abort(400, "Invalid request") err = db.delete(data['id']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'})
Delete a blog post
api_delete
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def api_export(): """Export blog posts""" db = get_database() if db is None: return flask.redirect('/login') err, blob = db.export_posts(get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'export': blob})
Export blog posts
api_export
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def api_import(): """Import blog posts""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['import'], str) except: return flask.abort(400, "Invalid request") err = db.import_posts(data['import'], get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'})
Import blog posts
api_import
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def __iter__(self): """Return blog posts sorted by publish date""" def enumerate_posts(workdir): posts = [] for path in glob.glob(f'{workdir}/*.json'): with open(path, "r") as f: posts.append(json.load(f)) for post in sorted(posts, key=lambda post: datetime.datetime.strptime( post['date'], "%Y/%m/%d %H:%M:%S" ))[::-1]: yield post return enumerate_posts(self.workdir)
Return blog posts sorted by publish date
__iter__
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def to_snake(s): """Convert string to snake case""" for i, c in enumerate(s): if not c.isalnum(): s = s[:i] + '_' + s[i+1:] return s
Convert string to snake case
to_snake
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def add(self, title, author, content): """Add new blog post""" # Validate title and content if len(title) == 0: return 'Title is emptry', None if len(title) > 64: return 'Title is too long', None if len(content) == 0 : return 'HTML is empty', None if len(content) > 1024*64: return 'HTML is too long', None if '{%' in content: return 'The pattern "{%" is forbidden', None for m in re.finditer(r"{{", content): p = m.start() if not (content[p:p+len('{{title}}')] == '{{title}}' or \ content[p:p+len('{{author}}')] == '{{author}}' or \ content[p:p+len('{{date}}')] == '{{date}}'): return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None # Save the blog post now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") post_id = Database.to_snake(title) data = { 'title': title, 'id': post_id, 'date': now, 'author': author, 'content': content } with open(f'{self.workdir}/{post_id}.json', "w") as f: json.dump(data, f) return None, post_id
Add new blog post
add
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def read(self, title): """Load a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are looking for does not exist', None with open(f'{self.workdir}/{post_id}.json', "r") as f: return None, json.load(f)
Load a blog post
read
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def delete(self, title): """Delete a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are trying to delete does not exist' os.unlink(f'{self.workdir}/{post_id}.json')
Delete a blog post
delete
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def export_posts(self, username, passhash): """Export all blog posts with encryption and signature""" buf = io.BytesIO() with zipfile.ZipFile(buf, 'a', zipfile.ZIP_DEFLATED) as z: # Archive blog posts for path in glob.glob(f'{self.workdir}/*.json'): z.write(path) # Add signature so that anyone else cannot import this backup z.comment = f'SIGNATURE:{username}:{passhash}'.encode() # Encrypt archive so that anyone else cannot read the contents buf.seek(0) iv = os.urandom(16) cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv) encbuf = iv + cipher.encrypt(buf.read()) return None, base64.b64encode(encbuf).decode()
Export all blog posts with encryption and signature
export_posts
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def import_posts(self, b64encbuf, username, passhash): """Import blog posts from backup file""" encbuf = base64.b64decode(b64encbuf) cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16]) buf = io.BytesIO(cipher.decrypt(encbuf[16:])) try: with zipfile.ZipFile(buf, 'r', zipfile.ZIP_DEFLATED) as z: # Check signature if z.comment != f'SIGNATURE:{username}:{passhash}'.encode(): return 'This is not your database' # Extract archive z.extractall() except: return 'The database is broken' return None
Import blog posts from backup file
import_posts
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
MIT
def api_new(): """Add a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['title'], str) assert isinstance(data['content'], str) except: return flask.abort(400, "Invalid request") err, post_id = db.add(data['title'], get_username(), data['content']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'id': post_id})
Add a blog post
api_new
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def api_delete(): """Delete a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['id'], str) except: return flask.abort(400, "Invalid request") err = db.delete(data['id']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'})
Delete a blog post
api_delete
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def api_export(): """Export blog posts""" db = get_database() if db is None: return flask.redirect('/login') err, blob = db.export_posts(get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'export': blob})
Export blog posts
api_export
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def api_import(): """Import blog posts""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['import'], str) except: return flask.abort(400, "Invalid request") err = db.import_posts(data['import'], get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'})
Import blog posts
api_import
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def __iter__(self): """Return blog posts sorted by publish date""" def enumerate_posts(workdir): posts = [] for path in glob.glob(f'{workdir}/*.json'): with open(path, "rb") as f: posts.append(json.loads(f.read().decode('latin-1'))) for post in sorted(posts, key=lambda post: datetime.datetime.strptime( post['date'], "%Y/%m/%d %H:%M:%S" ))[::-1]: yield post return enumerate_posts(self.workdir)
Return blog posts sorted by publish date
__iter__
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def to_snake(s): """Convert string to snake case""" for i, c in enumerate(s): if not c.isalnum(): s = s[:i] + '_' + s[i+1:] return s
Convert string to snake case
to_snake
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def add(self, title, author, content): """Add new blog post""" # Validate title and content if len(title) == 0: return 'Title is emptry', None if len(title) > 64: return 'Title is too long', None if len(content) == 0 : return 'HTML is empty', None if len(content) > 1024*64: return 'HTML is too long', None if '{%' in content: return 'The pattern "{%" is forbidden', None for m in re.finditer(r"{{", content): p = m.start() if not (content[p:p+len('{{title}}')] == '{{title}}' or \ content[p:p+len('{{author}}')] == '{{author}}' or \ content[p:p+len('{{date}}')] == '{{date}}'): return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None # Save the blog post now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") post_id = Database.to_snake(title) data = { 'title': title, 'id': post_id, 'date': now, 'author': author, 'content': content } with open(f'{self.workdir}/{post_id}.json', "w") as f: json.dump(data, f) return None, post_id
Add new blog post
add
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def read(self, title): """Load a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are looking for does not exist', None with open(f'{self.workdir}/{post_id}.json', "rb") as f: return None, json.loads(f.read().decode('latin-1'))
Load a blog post
read
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def delete(self, title): """Delete a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are trying to delete does not exist' os.unlink(f'{self.workdir}/{post_id}.json')
Delete a blog post
delete
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def export_posts(self, username, passhash): """Export all blog posts with encryption and signature""" buf = io.BytesIO() with zipfile.ZipFile(buf, 'a', zipfile.ZIP_STORED) as z: # Archive blog posts for path in glob.glob(f'{self.workdir}/*.json'): z.write(path) # Add signature so that anyone else cannot import this backup z.comment = f'SIGNATURE:{username}:{passhash}'.encode() # Encrypt archive so that anyone else cannot read the contents buf.seek(0) iv = os.urandom(16) cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv) encbuf = iv + cipher.encrypt(buf.read()) return None, base64.b64encode(encbuf).decode()
Export all blog posts with encryption and signature
export_posts
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT
def import_posts(self, b64encbuf, username, passhash): """Import blog posts from backup file""" encbuf = base64.b64decode(b64encbuf) cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16]) buf = io.BytesIO(cipher.decrypt(encbuf[16:])) try: with zipfile.ZipFile(buf, 'r', zipfile.ZIP_STORED) as z: # Check signature if z.comment != f'SIGNATURE:{username}:{passhash}'.encode(): return 'This is not your database' # Extract archive z.extractall() except: return 'The database is broken' return None
Import blog posts from backup file
import_posts
python
sajjadium/ctf-archives
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
MIT