def all_crcs(): """Generates a dictionary of all the known CRC formats from: http://reveng.sourceforge.net/crc-catalogue/all.htm""" import os, re data = pwn.read(os.path.join(pwn.installpath, 'data', 'crcsums')) out = {} def fixup(s): if s == 'true': return True elif s == 'false': return False elif s.startswith('"'): assert re.match('"[^"]+"', s) return s[1:-1] elif s.startswith('0x'): assert re.match('0x[0-9a-fA-F]+', s) return int(s[2:], 16) else: assert re.match('[0-9]+', s) return int(s, 10) data = [l for l in data.strip().split('\n') if l and l[0] != '#'] assert len(data) % 2 == 0 for ref, l in pwn.group(2, data): cur = {} cur['link'] = 'http://reveng.sourceforge.net/crc-catalogue/all.htm#' + ref for key in ['width', 'poly', 'init', 'refin', 'refout', 'xorout', 'check', 'name']: cur[key] = fixup(re.findall('%s=(\S+)' % key, l)[0]) cur['impl'] = make_crc(cur['name'], cur['poly'], cur['width'], cur['init'], cur['refin'], cur['refout'], cur['xorout'], 'See also: ' + cur['link']) assert cur['impl']('123456789') == cur['check'] assert cur['name'] not in out out[cur['name']] = cur return out
def upload(self, remote=None, local=None, raw=None): '''Uploads a file to the remote server. If remote is set to None, then the remote filename is inferred from the local filename. If raw is None, then the file specified by local is uploaded. Otherwise the data in the raw variable is uploaded instead.''' self._initialize_sftp() if remote == None: remote = os.path.normpath(local) remote = os.path.basename(remote) if self._supports_sftp: if raw == None: self._sftp.put(local, remote) else: f = self._sftp.open(remote, 'wb') f.write(raw) f.close() else: if raw == None: raw = pwn.read(local) s = self.run('cat>"$(echo %s|base64 -d)"' % pwn.b64(remote), silent=True) s.send(raw) s._channel.shutdown_write() s.recvall()
def english_freq(i): resource_dir = os.path.dirname(__file__) ngram_file = os.path.join(resource_dir, "count_%dl.txt") data = pwn.read(ngram_file % (i)).split() total = sum(map(int, data[1::2])) * 1. return dict(zip(data[0::2], [int(x) / total for x in data[1::2]]))
def upload(self, remote = None, local = None, raw = None): '''Uploads a file to the remote server. If remote is set to None, then the remote filename is inferred from the local filename. If raw is None, then the file specified by local is uploaded. Otherwise the data in the raw variable is uploaded instead.''' self._initialize_sftp() if remote == None: remote = os.path.normpath(local) remote = os.path.basename(remote) if self._supports_sftp: if raw == None: self._sftp.put(local, remote) else: f = self._sftp.open(remote, 'wb') f.write(raw) f.close() else: if raw == None: raw = pwn.read(local) s = self.run('cat>"$(echo %s|base64 -d)"' % pwn.b64(remote), silent = True) s.send(raw) s._channel.shutdown_write() s.recvall()
def FlagFinder(cible, flag): # {{{ regex = flag file = cible t = pwn.read(file) c = re.findall(regex, str(t)) if not c: pwn.warn("Flag non trouvé") else: for a in c: pwn.success("Yeah !!!! flag found: {result}\n".format(result=a)) pwn.warn("flag is now copied in flag.txt") pwn.write("flag.txt", a)
def Exploit(fichier, pattern): regex = pattern file = fichier pwn.info("Opening file: {fichier}\n".format(fichier=file)) s = pwn.read(file) pwn.info("Searching for pattern: {flag}\n".format(flag=regex)) c = re.findall(regex, str(s)) if not c: pwn.warn("No flag for you my friend, check your regex") else: for a in c: pwn.success("Yeah !!!! flag found: {result}\n".format(result=a)) pwn.warn("flag is now copied in flag.txt") pwn.write("flag.txt", a)
def download(self, remote, local=None, raw=False): '''Downloads a file from the remote server. The file is cached in /tmp/pwn-ssh-cache using a hash of the file, so calling the function twice has little overhead. Set raw to True, if you want the data returned instead of saved to a file. If local is None and the data is to be saved, then the local filename is inferred from the remote.''' import shutil local_tmp = self._download_to_cache(remote) if raw: return pwn.read(local_tmp) if not local: local = os.path.basename(os.path.normpath(remote)) shutil.copy2(local_tmp, local)
def all_crcs(): """Generates a dictionary of all the known CRC formats from: http://reveng.sourceforge.net/crc-catalogue/all.htm""" import os, re data = pwn.read(os.path.join(pwn.installpath, 'data', 'crcsums')) out = {} def fixup(s): if s == 'true': return True elif s == 'false': return False elif s.startswith('"'): assert re.match('"[^"]+"', s) return s[1:-1] elif s.startswith('0x'): assert re.match('0x[0-9a-fA-F]+', s) return int(s[2:], 16) else: assert re.match('[0-9]+', s) return int(s, 10) data = [l for l in data.strip().split('\n') if l and l[0] != '#'] assert len(data) % 2 == 0 for ref, l in pwn.group(2, data): cur = {} cur['link'] = 'http://reveng.sourceforge.net/crc-catalogue/all.htm#' + ref for key in [ 'width', 'poly', 'init', 'refin', 'refout', 'xorout', 'check', 'name' ]: cur[key] = fixup(re.findall('%s=(\S+)' % key, l)[0]) cur['impl'] = make_crc(cur['name'], cur['poly'], cur['width'], cur['init'], cur['refin'], cur['refout'], cur['xorout'], 'See also: ' + cur['link']) assert cur['impl']('123456789') == cur['check'] assert cur['name'] not in out out[cur['name']] = cur return out
def download(self, remote, local = None, raw = False): '''Downloads a file from the remote server. The file is cached in /tmp/pwn-ssh-cache using a hash of the file, so calling the function twice has little overhead. Set raw to True, if you want the data returned instead of saved to a file. If local is None and the data is to be saved, then the local filename is inferred from the remote.''' import shutil local_tmp = self._download_to_cache(remote) if raw: return pwn.read(local_tmp) if not local: local = os.path.basename(os.path.normpath(remote)) shutil.copy2(local_tmp, local)
def get_agents(): return pwn.read(os.path.join(pwn.installpath, 'pwn', 'useragents.txt')).strip().split('\n')
def _asm(target_arch, target_os, code_blocks, emit_asm=0, keep_tmp=False): import pwn.internal.shellcode_helper as H import os.path, tempfile, subprocess, string, shutil if target_arch == None: raise Exception('You need to set the architecture with context') tmpdir = tempfile.mkdtemp(prefix='pwn-asm-') def path(s): return os.path.join(tmpdir, s) try: magic = pwn.randoms(32, only=string.ascii_lowercase) code = [] cpp = ['cpp', '-nostdinc', '-undef', '-w'] if pwn.DEBUG: cpp += ['-D', 'DEBUG'] if target_os != None: include = os.path.join(pwn.installpath, 'pwn', 'include', target_os) cpp += ['-I', include] if target_os == 'linux': if os.path.isfile(os.path.join(include, target_arch + '.h')): cpp += ['-I', os.path.join(include, 'diet')] code += ['#include <%s.h>' % target_arch] elif target_os == 'freebsd': code += ['#include <common.h>'] code += [magic] if target_arch not in ['i386', 'amd64']: code += ['.section .shellcode,"ax"'] asm_extra = [] if target_arch == 'arm': code += ['.arm'] elif target_arch == 'thumb': code += ['.thumb'] target_arch = 'arm' elif target_arch == 'i386': code += ['bits 32'] elif target_arch == 'amd64': code += ['bits 64'] elif target_arch in ['mips', 'mipsel']: code += ['.set mips2'] code += ['.set noreorder'] if target_arch == 'mips': asm_extra += ['--EB'] else: asm_extra += ['--EL'] target_arch = 'mips' code += code_blocks code = '\n'.join(code) if target_arch in ['i386', 'amd64']: assembler = ['nasm', '-Ox'] + asm_extra objcopy = ['objcopy'] else: assembler = [ os.path.join(pwn.installpath, 'binutils', target_arch + '-as') ] + asm_extra if not os.path.isfile(assembler[0]): raise Exception( 'Could not find the gnu assembler for this architecture: %s' % target_arch) objcopy = [ os.path.join(pwn.installpath, 'binutils', 'promisc-objcopy') ] objcopy += ['-j.shellcode', '-Obinary'] if emit_asm == 2: output = [] output += [ "/*", " Assemble with:", " %s [input] -o [input].tmp1" % ' '.join(cpp), " sed -e '0,/^%s$/d' [input].tmp1 > [input].tmp2" % magic, " %s [input].tmp2 -o [input].tmp3" % ' '.join(assembler) ] if target_arch not in ['i386', 'amd64']: output += [" %s [input].tmp3 [output]" % ' '.join(objcopy)] output += ["*/", "", code] return '\n'.join(output) pwn.write(path('step1'), code) _run(cpp + [path('step1'), path('step2')]) code = pwn.read(path('step2')) _code = code.split('\n' + magic + '\n') if len(_code) != 2: raise Exception("The output from cpp was weird:\n%s" % code) code = _code[1] if emit_asm == 1: output = [] if target_arch in ['i386', 'amd64']: output += [ ';; Assemble with:', ';; %s <input> -o <output>' % ' '.join(assembler) ] else: output += [ "/*", " Assemble with:", ' %s <input> -o <input>.tmp' % ' '.join(assembler), ' %s [input].tmp [output]' % ' '.join(objcopy), '*/', ] output += ["", code] return '\n'.join(output) pwn.write(path('step3'), code) _run(assembler + ['-o', path('step4'), path('step3')]) if target_arch in ['i386', 'amd64']: return pwn.read(path('step4')) # Sanity check for seeing if the output has relocations relocs = subprocess.check_output(['readelf', '-r', path('step4')]).strip() if len(relocs.split('\n')) > 1: raise Exception('There were relocations in the shellcode:\n\n%s' % relocs) _run(objcopy + [path('step4'), path('step5')]) return pwn.read(path('step5')) finally: if not keep_tmp: try: shutil.rmtree(tmpdir) except: pass
def get_agents(): return pwn.read( os.path.join(pwn.installpath, 'pwn', 'useragents.txt') ).strip().split('\n')
from math import sqrt, log10 from os import path from pwn import read resource_dir = path.dirname(__file__) ngram_file = path.join(resource_dir, "count_%dl.txt") english_freq = {} for i in [2,3]: data = read(ngram_file % (i)).split() total = sum(map(int, data[1::2])) * 1. english_freq[i] = dict(zip(data[0::2], [int(x) / total for x in data[1::2]])) def generate_ngram(text, n=3): """ Generate n-gram frequency table for given text. """ occurences = ngram = dict() for i in range(len(text) - n): try: cur = text[i:i+n] if cur in occurences: occurences[cur] += 1 else: occurences[cur] = 1 except IndexError: pass for (key,value) in occurences.items(): ngram[key] = float(value) / (len(text) - n + 1)
from math import sqrt from pwn import read english_freq = {} for i in [2,3]: data = read('count_%dl.txt' % (i)).split() total = sum(map(int, data[1::2])) * 1. english_freq[i] = dict(zip(data[0::2], [int(x) / total for x in data[1::2]])) def generate_ngram(text, n=3): """ Generate n-gram frequency table for given text. """ occurences = ngram = dict() for i in range(len(text)): try: cur = text[i:i+n] if cur in occurences: occurences[cur] += 1 else: occurences[cur] = 1 except IndexError: pass for (key,value) in occurences.items(): ngram[key] = float(value) / (len(text) - n + 1) return ngram
cipher = AES.new(self.enc_key, AES.MODE_CTR, counter=counter) return cipher.decrypt(encrypted) if __name__ == '__main__': from Crypto.Util import number import requests if len(sys.argv) < 2 or 3 < len(sys.argv): print('- Indirect and encrypted poke through pastebins -') print('Usage: %s password [filename]' % sys.argv[0]) sys.exit(1) password = sys.argv[1] filename = sys.argv[2] if len(sys.argv) == 3 else None data = read(filename) if filename is not None else sys.stdin.read() cipher = Encryption(password) upload_data = b64(cipher.encrypt(data)) try: upload = {'public':False, 'files':{'data':{'content':upload_data}}} req = requests.post('https://api.github.com/gists', data=json.dumps(upload)) except Exception as e: print('Unable to upload data to Github.') print(str(e)) sys.exit(1) if req.status_code != 201: print('Unable to upload to github, debug information follows') print(req.text)
from math import sqrt, log10 from os import path from pwn import read resource_dir = path.dirname(__file__) ngram_file = path.join(resource_dir, "count_%dl.txt") english_freq = {} for i in [2, 3]: data = read(ngram_file % (i)).split() total = sum(map(int, data[1::2])) * 1. english_freq[i] = dict( zip(data[0::2], [int(x) / total for x in data[1::2]])) def generate_ngram(text, n=3): """ Generate n-gram frequency table for given text. """ occurences = ngram = dict() for i in range(len(text) - n): try: cur = text[i:i + n] if cur in occurences: occurences[cur] += 1 else: occurences[cur] = 1 except IndexError: pass
return cipher.decrypt(encrypted) if __name__ == '__main__': from Crypto.Util import number import requests if len(sys.argv) < 2 or 3 < len(sys.argv): print('- Indirect and encrypted poke through pastebins -') print('Usage: %s password [filename]' % sys.argv[0]) sys.exit(1) password = sys.argv[1] filename = sys.argv[2] if len(sys.argv) == 3 else None data = read(filename) if filename is not None else sys.stdin.read() cipher = Encryption(password) upload_data = b64(cipher.encrypt(data)) try: upload = {'public': False, 'files': {'data': {'content': upload_data}}} req = requests.post('https://api.github.com/gists', data=json.dumps(upload)) except Exception as e: print('Unable to upload data to Github.') print(str(e)) sys.exit(1) if req.status_code != 201: print('Unable to upload to github, debug information follows')
def _asm(target_arch, target_os, code_blocks, emit_asm = 0, keep_tmp = False): import pwn.internal.shellcode_helper as H import os.path, tempfile, subprocess, string, shutil if target_arch == None: raise Exception('You need to set the architecture with context') tmpdir = tempfile.mkdtemp(prefix = 'pwn-asm-') def path(s): return os.path.join(tmpdir, s) try: magic = pwn.randoms(32, only = string.ascii_lowercase) code = [] cpp = ['cpp', '-nostdinc', '-undef', '-w'] if pwn.DEBUG: cpp += ['-D', 'DEBUG'] if target_os != None: include = os.path.join(pwn.installpath, 'pwn', 'include', target_os) cpp += ['-I', include] if target_os == 'linux': if os.path.isfile(os.path.join(include, target_arch + '.h')): cpp += ['-I', os.path.join(include, 'diet')] code += ['#include <%s.h>' % target_arch] elif target_os == 'freebsd': code += ['#include <common.h>'] code += [magic] if target_arch not in ['i386', 'amd64']: code += ['.section .shellcode,"ax"'] asm_extra = [] if target_arch == 'arm': code += ['.arm'] elif target_arch == 'thumb': code += ['.thumb'] target_arch = 'arm' elif target_arch == 'i386': code += ['bits 32'] elif target_arch == 'amd64': code += ['bits 64'] elif target_arch in ['mips', 'mipsel']: code += ['.set mips2'] code += ['.set noreorder'] if target_arch == 'mips': asm_extra += ['--EB'] else: asm_extra += ['--EL'] target_arch = 'mips' code += code_blocks code = '\n'.join(code) if target_arch in ['i386', 'amd64']: assembler = ['nasm', '-Ox'] + asm_extra objcopy = ['objcopy'] else: assembler = [os.path.join(pwn.installpath, 'binutils', target_arch + '-as')] + asm_extra if not os.path.isfile(assembler[0]): raise Exception('Could not find the gnu assembler for this architecture: %s' % target_arch) objcopy = [os.path.join(pwn.installpath, 'binutils', 'promisc-objcopy')] objcopy += ['-j.shellcode', '-Obinary'] if emit_asm == 2: output = [] output += [ "/*", " Assemble with:", " %s [input] -o [input].tmp1" % ' '.join(cpp), " sed -e '0,/^%s$/d' [input].tmp1 > [input].tmp2" % magic, " %s [input].tmp2 -o [input].tmp3" % ' '.join(assembler) ] if target_arch not in ['i386', 'amd64']: output += [" %s [input].tmp3 [output]" % ' '.join(objcopy)] output += ["*/", "", code] return '\n'.join(output) pwn.write(path('step1'), code) _run(cpp + [path('step1'), path('step2')]) code = pwn.read(path('step2')) _code = code.split('\n' + magic + '\n') if len(_code) != 2: raise Exception("The output from cpp was weird:\n%s" % code) code = _code[1] if emit_asm == 1: output = [] if target_arch in ['i386', 'amd64']: output += [ ';; Assemble with:', ';; %s <input> -o <output>' % ' '.join(assembler) ] else: output += [ "/*", " Assemble with:", ' %s <input> -o <input>.tmp' % ' '.join(assembler), ' %s [input].tmp [output]' % ' '.join(objcopy), '*/', ] output += ["", code] return '\n'.join(output) pwn.write(path('step3'), code) _run(assembler + ['-o', path('step4'), path('step3')]) if target_arch in ['i386', 'amd64']: return pwn.read(path('step4')) # Sanity check for seeing if the output has relocations relocs = subprocess.check_output(['readelf', '-r', path('step4')]).strip() if len(relocs.split('\n')) > 1: raise Exception('There were relocations in the shellcode:\n\n%s' % relocs) _run(objcopy + [path('step4'), path('step5')]) return pwn.read(path('step5')) finally: if not keep_tmp: try: shutil.rmtree(tmpdir) except: pass