def crack_rsa(n, e=None, c=None): """ Tries all currently implemented attacks on RSA key. """ log.info("Cracking RSA key") # Wieners attack if e != None: log.waitfor("Trying Wiener's attack") res = wieners_attack(n, e) if res != None: log.succeeded("success!") log.success("Factors: %d %d" % res) return else: log.failed() # Factor log.waitfor("Trying to factor...") res = factor(n) if res != None: p, q = res log.succeeded("success!") log.success("Factors: %d %d" % (p, q)) if e != None: d = calculate_private_key(p, q, e) log.success("d = %d" % d) if c != None: log.info("Possible message: %s" % int2bytes(decrypt(c, d, n))) return else: log.failed("failed")
def crack_rsa(n,e = None,c = None): """ Tries all currently implemented attacks on RSA key. """ log.info("Cracking RSA key") # Wieners attack if e != None: log.waitfor("Trying Wiener's attack") res = wieners_attack(n,e) if res != None: log.succeeded("success!") log.success("Factors: %d %d" % res) return else: log.failed() # Factor log.waitfor("Trying to factor...") res = factor(n) if res != None: p, q = res log.succeeded("success!") log.success("Factors: %d %d" % (p, q)) if e != None: d = calculate_private_key(p,q,e) log.success("d = %d" % d) if c != None: log.info("Possible message: %s" % int2bytes(decrypt(c,d,n))) return else: log.failed("failed")
def __init__(self, file): waitfor('Loading ELF file `%s\'' % os.path.basename(file)) self.sections = {} self.symbols = {} self.plt = {} self.got = {} self.elfclass = None self._file_data = None if not (os.access(file, os.R_OK) and os.path.isfile(file)): die('File %s is not readable or does not exist' % file) self._file = file def check(f): if not (os.access(f, os.X_OK) and os.path.isfile(f)): die('Executable %s needed for readelf.py, please install binutils' % f) check(_READELF) check(_OBJDUMP) self._load_elfclass() self._load_sections() self._load_symbols() self._load_plt_got() succeeded()
def run(self): e = self.env bits = e['bits'] chrs = e['chrs'] lock = e['lock'] disp = e['disp'] verify = e['verify'] s = '' offset = 0 if disp: log.waitfor('') else: log.waitfor('Running SQL query') while not e['exit']: sleep(0.1) s1 = '' if e['endp'] is not None: l = e['endp'] else: l = len(bits) verified = True newline = False numb = 0 for i in range(offset, l // 8): if i in chrs: c, v = chrs[i] if v: numb += 1 if c == '\n': newline = True break if v: s1 += c else: verified = False s1 += text.red(c) else: verified = False s1 += '.' if s1 == s: continue s = s1 done = e[ 'endp'] is not None and offset + numb == l // 8 and verified if disp: log.status(s) if newline and verified or done: offset += len(s1) + 1 if disp: log.succeeded(s) s = '' if not done and disp: log.waitfor('') if done: e['exit'] = True if not disp: log.succeeded()
def wait_for_connection(self): log.waitfor('Waiting for connection on port %d' % self.port) self.listensock.settimeout(self.timeout) try: self.sock, self.target = self.listensock.accept() except Exception as e: log.failed('Got exception: %s' % e) raise log.succeeded('Got connection from %s:%d' % self.target)
def run(self): e = self.env bits = e['bits'] chrs = e['chrs'] lock = e['lock'] disp = e['disp'] verify = e['verify'] s = '' offset = 0 if disp: log.waitfor('') else: log.waitfor('Running SQL query') while not e['exit']: sleep(0.1) s1 = '' if e['endp'] is not None: l = e['endp'] else: l = len(bits) verified = True newline = False numb = 0 for i in range(offset, l // 8): if i in chrs: c, v = chrs[i] if v: numb += 1 if c == '\n': newline = True break if v: s1 += c else: verified = False s1 += text.red(c) else: verified = False s1 += '.' if s1 == s: continue s = s1 done = e['endp'] is not None and offset + numb == l // 8 and verified if disp: log.status(s) if newline and verified or done: offset += len(s1) + 1 if disp: log.succeeded(s) s = '' if not done and disp: log.waitfor('') if done: e['exit'] = True if not disp: log.succeeded()
def connect(self): if self.connected(): log.warning('Already connected to %s on port %d' % self.target) return log.waitfor('Opening connection to %s on port %d' % self.target) self.sock = socket.socket(self.family, self.type, self.proto) self.sock.settimeout(self.timeout) self.sock.connect(self.target) self.lhost = self.sock.getsockname()[0] self.lport = self.sock.getsockname()[1] log.succeeded()
def connect(self): if self.connected(): log.warning('Already connected to %s on port %d' % self.target) return if not self.silent: log.waitfor('Opening connection to %s on port %d' % self.target) self.sock = socket.socket(self.family, self.type, self.proto) self.sock.settimeout(self.timeout) self.sock.connect(self.target) self.lhost = self.sock.getsockname()[0] self.lport = self.sock.getsockname()[1] if not self.silent: log.succeeded()
def pause(n = None): """Waits for either user input or a specific number of seconds.""" try: if n is None: log.info('Paused (press enter to continue)') raw_input('') else: log.waitfor('Continueing in') for i in range(n, 0, -1): log.status('%d... ' % i) pwn.sleep(1) log.succeeded('Now') except KeyboardInterrupt: log.warning('Interrupted') sys.exit(1)
def pause(n=None): """Waits for either user input or a specific number of seconds.""" try: if n is None: log.info('Paused (press enter to continue)') raw_input('') else: log.waitfor('Continueing in') for i in range(n, 0, -1): log.status('%d... ' % i) pwn.sleep(1) log.succeeded('Now') except KeyboardInterrupt: log.warning('Interrupted') sys.exit(1)
def start(self, cmd, args, env): if self.connected(): log.warning('Program "%s" already started' % cmd) return log.waitfor('Starting program "%s"' % cmd) self.proc = Popen( tuple(cmd.split()) + args, stdin=PIPE, stdout=PIPE, stderr=PIPE, env = env, bufsize = 0) fd = self.proc.stdout.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) self.stdout = fd log.succeeded()
def crack_substitution(ciphertext, num_starts=20, num_iterations=3000, frequencies=freq.english, show_status=True): global_best_dict = {} global_best_score = sys.float_info.max mixed_alphabet = list(string.uppercase) if show_status: log.waitfor("Cracking cipher") for i in range(num_starts): local_scores = [] random.shuffle(mixed_alphabet) new_dict = {k: v for (k, v) in zip(string.uppercase, mixed_alphabet)} new_score = -1 * ngram.log_p(ciphertext.lower(), ngram.english_freq[3], 3) heapq.heappush(local_scores, (new_score, new_dict)) for _ in range(num_iterations): (local_best__score, local_best_dict) = local_scores[0] new_dict = local_best_dict.copy() c1 = random.choice(string.uppercase) c2 = random.choice(string.uppercase) new_dict[c1], new_dict[c2] = new_dict[c2], new_dict[c1] trial = encrypt_substitution(ciphertext, new_dict) new_score = -1 * ngram.log_p(trial.lower(), ngram.english_freq[3], 3) heapq.heappush(local_scores, (new_score, new_dict)) (local_best_score, local_best_dict) = local_scores[0] if local_best_score < global_best_score: global_best_score = local_best_score global_best_dict = local_best_dict if show_status: log.status(encrypt_substitution(ciphertext, global_best_dict)) if show_status: log.succeeded(encrypt_substitution(ciphertext, global_best_dict)) return (global_best_dict, encrypt_substitution(ciphertext, global_best_dict))
def start(self, cmd, args, env): if self.connected(): log.warning('Program "%s" already started' % cmd) return if not self.silent: log.waitfor('Starting program "%s"' % cmd) self.proc = Popen( tuple(cmd.split()) + args, stdin=PIPE, stdout=PIPE, stderr=PIPE, env = env, bufsize = 0) fd = self.proc.stdout.fileno() fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) self.stdout = fd if not self.silent: log.succeeded()
def crack_substitution(ciphertext, num_starts=20, num_iterations=3000, frequencies=freq.english, show_status=True): global_best_dict = {} global_best_score = sys.float_info.max mixed_alphabet = list(string.uppercase) if show_status: log.waitfor("Cracking cipher") for i in range(num_starts): local_scores = [] random.shuffle(mixed_alphabet) new_dict = {k:v for (k,v) in zip(string.uppercase, mixed_alphabet)} new_score = -1 * ngram.log_p(ciphertext.lower(), ngram.english_freq[3], 3) heapq.heappush(local_scores, (new_score, new_dict)) for _ in range(num_iterations): (local_best__score, local_best_dict) = local_scores[0] new_dict = local_best_dict.copy() c1 = random.choice(string.uppercase) c2 = random.choice(string.uppercase) new_dict[c1], new_dict[c2] = new_dict[c2], new_dict[c1] trial = encrypt_substitution(ciphertext, new_dict) new_score = -1 * ngram.log_p(trial.lower(), ngram.english_freq[3], 3) heapq.heappush(local_scores, (new_score, new_dict)) (local_best_score, local_best_dict) = local_scores[0] if local_best_score < global_best_score: global_best_score = local_best_score global_best_dict = local_best_dict if show_status: log.status(encrypt_substitution(ciphertext, global_best_dict)) if show_status: log.succeeded(encrypt_substitution(ciphertext, global_best_dict)) return (global_best_dict, encrypt_substitution(ciphertext, global_best_dict))
def bruteforce(function, alphabet, length, condition=None, method='upto', start=None): """ Bruteforce a given string function. Arguments: function: the function to bruteforce alphabet: possible characters in the string length: length of the string method: upto: try lengths 1..repeat fixed: only try 'repeat' length downfrom: try lengths repeat..1 start: a tuple (i,N) which splits the search space up into N pieces and starts at piece i. """ import pwn.log as log total_iterations = len(alphabet)**length cur_iteration = 0 if method == 'upto' and length > 1: iterator = product(alphabet, repeat=1) for i in xrange(2, length + 1): iterator = chain(iterator, product(alphabet, repeat=i)) elif method == 'downfrom' and length > 1: iterator = product(alphabet, repeat=length) for i in xrange(length - 1, 1, -1): iterator = chain(iterator, product(alphabet, repeat=i)) elif method == 'fixed': iterator = product(alphabet, repeat=length) if start is not None: i, N = start if i > N: raise ValueError('invalid starting point') i -= 1 chunk_size = total_iterations / N rest = total_iterations % N starting_point = 0 for chunk in range(N): if chunk >= i: break if chunk <= rest: starting_point += chunk_size + 1 else: starting_point += chunk_size if rest >= i: chunk_size += 1 consume(iterator, starting_point) iterator = take(chunk_size, iterator) total_iterations = chunk_size else: raise NotImplementedError('Unknown method') log.waitfor('Bruteforcing') for e in iterator: cur = ''.join(map(str, list(e))) cur_iteration += 1 if cur_iteration % 2000 == 0: log.status('Trying {0}, {1}%'.format( cur, 100.0 * cur_iteration / total_iterations, 100)) res = function(cur) if condition == res: log.succeeded('Found key: \'{0}\', matching {1}'.format(cur, res)) return res log.failed('No matches found')
def bruteforce(function, alphabet, length, condition=None, method='upto', start=None): """ Bruteforce a given string function. Arguments: function: the function to bruteforce alphabet: possible characters in the string length: length of the string method: upto: try lengths 1..repeat fixed: only try 'repeat' length downfrom: try lengths repeat..1 start: a tuple (i,N) which splits the search space up into N pieces and starts at piece i. """ import pwn.log as log total_iterations = len(alphabet) ** length cur_iteration = 0 if method == 'upto' and length > 1: iterator = product(alphabet, repeat=1) for i in xrange(2, length+1): iterator = chain(iterator, product(alphabet, repeat=i)) elif method == 'downfrom' and length > 1: iterator = product(alphabet, repeat=length) for i in xrange(length-1, 1, -1): iterator = chain(iterator, product(alphabet, repeat=i)) elif method == 'fixed': iterator = product(alphabet, repeat=length) if start is not None: i, N = start if i > N: raise ValueError('invalid starting point') i -= 1 chunk_size = total_iterations / N rest = total_iterations % N starting_point = 0 for chunk in range(N): if chunk >= i: break if chunk <= rest: starting_point += chunk_size + 1 else: starting_point += chunk_size if rest >= i: chunk_size += 1 consume(iterator, starting_point) iterator = take(chunk_size, iterator) total_iterations = chunk_size else: raise NotImplementedError('Unknown method') log.waitfor('Bruteforcing') for e in iterator: cur = ''.join(map(str, list(e))) cur_iteration += 1 if cur_iteration % 2000 == 0: log.status('Trying {0}, {1}%'.format(cur, 100.0*cur_iteration/total_iterations, 100)) res = function(cur) if condition == res: log.succeeded('Found key: \'{0}\', matching {1}'.format(cur, res)) return res log.failed('No matches found')