def validate(self, current): super().validate(current) if current is None: raise errors.ValidationError(current) current = self.normalize_value(current) if not is_pathname_valid(current): raise errors.ValidationError(current) # os.path.isdir and isfile check also existence of the path, # which might not be desirable if self._path_type == "file": if self._exists is None and os.path.basename(current) == "": raise errors.ValidationError(current) elif self._exists and not os.path.isfile(current): raise errors.ValidationError(current) elif self._exists is not None and not self._exists and os.path.isfile(current): raise errors.ValidationError(current) elif self._path_type == "directory": if self._exists is None and os.path.basename(current) != "": raise errors.ValidationError(current) elif self._exists and not os.path.isdir(current): raise errors.ValidationError(current) elif self._exists is not None and not self._exists and os.path.isdir(current): raise errors.ValidationError(current) elif self._exists and not os.path.exists(current): raise errors.ValidationError(current) elif self._exists is not None and not self._exists and os.path.exists(current): raise errors.ValidationError(current)
def int_validator(answers, current): if not current.strip(): raise errors.ValidationError('', reason='Please provide a rank!') try: int(current) return True except ValueError: raise errors.ValidationError( '', reason='Provided value is not an integer!')
def enable_monitor_mode(): """ Configures wireless interface in monitor mode. """ try: questions = [ inquirer.Text( "interface", message="Enter the name of a wireless interface to configure", validate=lambda _, x: x != '') ] answers = inquirer.prompt(questions, raise_keyboard_interrupt=True) interface = answers["interface"] print(f"[+] Enabling monitor mode for device {interface}.") subprocess.call(["ifconfig", interface, "down"]) subprocess.call(["iwconfig", interface, "mode", "monitor"]) subprocess.call(["ifconfig", interface, "up"]) except TypeError: pass except KeyboardInterrupt: print("\n[x] Utility terminated by user.\n") except: raise errors.ValidationError( '', reason=f"[-] Unable to read MAC address of device {interface}.")
def email_validation(_, current): """Validate entered emails""" # If user leaves it blank, ignore if current == "": return True if not re.match(r"^[\w\d.-]+@[\w\d]+\.+[\w]+[\.\w]*", current): raise errors.ValidationError("", reason="Invalid email") return True
def phone_validation(_, current): """Validate entered phone numbers""" # If user leaves it blank, ignore if current == "": return True if not re.match(r"[\d+\(\)]*[\d ]+\d", current): raise errors.ValidationError("", reason="Invalid phone number") return True
def validate(self, current): try: if self._solve(self._validate, current): return except errors.ValidationError as e: raise e except Exception: pass raise errors.ValidationError(current)
def check_author(anwser, name): """检查用户名 Args: anwser: 结果 name: 用户名 """ if len(name.strip()) == 0: raise errors.ValidationError('', reason='请输入用户') return True
def check_name(anwser, name): """检查名称,只能是数字、字母 、下划线、横线 Args: anwser: 结果 name: 名称 """ name_re = r'[a-zA-Z0-9-_]+' if not re.match(name_re, name): raise errors.ValidationError('', reason='使用数字、字母、下划线、连接线的组合') return True
def check_email(anwser, email): """检查邮箱 Args: anwser: 结果 email: 邮箱 """ name_re = r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$' if not re.match(name_re, email): raise errors.ValidationError('', reason='请输入正确的邮箱地址') return True
def process_input(self, pressed): if pressed == key.CTRL_C: raise KeyboardInterrupt() if pressed in (key.CR, key.LF, key.ENTER): data = editor.edit(contents=self.question.default or "") raise errors.EndOfInput(data.decode("utf-8")) raise errors.ValidationError("You have pressed unknown key! " "Press <enter> to open editor or " "CTRL+C to exit.")
def process_input(self, pressed): if pressed == key.CTRL_C: raise KeyboardInterrupt() if pressed in (key.CR, key.LF, key.ENTER): data = editor.edit( filename=self.default_filename, # added by us contents=self.question.default or '') raise errors.EndOfInput(data.decode('utf-8')) raise errors.ValidationError( 'You have pressed unknown key! Press <enter> to open ' 'editor or CTRL+C to exit.')
def check_version(anwser, version): """检查邮箱 Args: anwser: 结果 version: 版本号 """ if not re.match( r'(0|[1-9][0-9]*.?)\.(0|[1-9][0-9]*.?)\.(0|[1-9][0-9]*.?)$', version): raise errors.ValidationError('', reason='版本号格式错误,以0开头的版本号只能有一个数字') return True
def test_validate_function_raising_validation_error(self): err = errors.ValidationError("", reason="foo") def raise_exc(x, y): raise err name = "foo" q = questions.Question(name, validate=raise_exc) try: q.validate(None) except errors.ValidationError as e: self.assertIs(e, err)
def validate_disc_number(answers, current): if current == '': answers['disc_number'] = 1 answers['disc_count'] = 1 else: try: (disc_number, disc_count) = current.split('/') answers['disc_number'] = int(disc_number) answers['disc_count'] = int(disc_count) except ValueError: raise errors.ValidationError( '', reason='Needs to be either "x/y" or blank (for 1/1)') return True
def validate_ip(answers, current): """ Accepts as input a valid ipv4 or ipv6 IP address with optional subnet range. Validates given IP and range, raises an exception if IP/range is invalid. """ ip_arr = current.split("/") if (len(ip_arr) == 2): ip_range = ip_arr[1] # validate ip_range ip_address = ip_arr[0] try: ip = (u"{ip}").format(ip=ip_address) ipaddress.ip_address(ip) return True except: raise errors.ValidationError('', reason=f"[-] Invalid IP address format.")
def main(): try: questions = [ inquirer.Text("target_url", message="Enter the target login URL", validate=lambda _, x: x != ''), inquirer.List("user_provided_wordlist", message="Select an option", choices=[("Use Brutus' wordlist", "no"), ("Use a path-specified wordlist", "yes")]), inquirer.Path("wordlist", message="Enter the absolute path to desired wordlist", ignore=ignore_wordlist, validate=lambda _, x: x != '', path_type=inquirer.Path.FILE, exists=True), inquirer.Text("interval", message="Enter request interval in seconds", default="1", validate=lambda _, x: x != '') ] answers = inquirer.prompt(questions, raise_keyboard_interrupt=True) wordlist = answers["wordlist"] if answers["wordlist"] else "/Users/narcissus/Applications/Brutus/config/subdomains.txt" print(f"[+] Building subdomain map for {answers['target_url']}.") Scanner(answers["target_url"], wordlist, answers["interval"]) except TypeError: pass except KeyboardInterrupt: print("\n[x] Subdomain mapping process terminated by user.\n") except: raise errors.ValidationError('', reason=f"[-] An error has occurred; most likely malformed input.")
def main(): try: questions = [ inquirer.Text("target_url", message="Enter full URL for link harvesting", validate=lambda _, x: x != '') ] answers = inquirer.prompt(questions, raise_keyboard_interrupt=True) target_url = answers["target_url"] print(f"[+] Initiating Harvester at {target_url}") Harvester(target_url) except TypeError: pass except KeyboardInterrupt: print("\n[x] Harvesting process terminated by user.\n") except: raise errors.ValidationError( '', reason=f"[-] An error has occurred; most likely malformed input.")
def get_current_mac(answers=None, interface=None): """ Calls ifconfig, runs a regex to find the specified device's (interface) current MAC address, and returns it as a string. """ FNULL = open(os.devnull, 'w') try: ifconfig_res = subprocess.check_output(["ifconfig", interface], stderr=FNULL) # decode what is a bytes-like object decoded_res = ifconfig_res.decode("utf-8") current_mac_res = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", decoded_res) # does the device even have a MAC address? if (current_mac_res != None): return current_mac_res.group(0) except: raise errors.ValidationError( '', reason=f"[-] Unable to read MAC address of device {interface}.")
def main(): try: questions = [ inquirer.Text("target_url", message="Enter the target login URL", validate=lambda _, x: x != ''), inquirer.Text("username", message="Enter the target username", validate=lambda _, x: x != ''), inquirer.Path("wordlist", message="Enter the absolute path to desired wordlist", validate=lambda _, x: x != '', path_type=inquirer.Path.FILE, exists=True) ] answers = inquirer.prompt(questions, raise_keyboard_interrupt=True) data_obj = { "username": answers["username"], "password": "", "Login" : "submit" } print(f"[+] Beginning brute force attempt on {answers['username']}.") brute_credentials(data_obj, answers["wordlist"], answers["target_url"]) except TypeError: pass except KeyboardInterrupt: print("\n[x] Brute force attempt terminated by user.\n") except: raise errors.ValidationError('', reason=f"[-] An error has occurred; most likely malformed input.")
def val(_, x): if x.count("\n") < 2: raise errors.ValidationError("", reason="Some bad reason") return True
def msg_validation(answers, current): if current == '': raise errors.ValidationError('', reason='请输入要提交的内容!') return True
def at_least_one(_, current_answers): # Validation function for inquirer if len(current_answers) <= 0: raise inquirer_errors.ValidationError( "", reason="Please select at least one file") return True
def raise_exc(x, current): if current != '9999': raise errors.ValidationError('', reason='Custom error') return True
def clone_count(answers, current): if int(current) not in range(1, 11): raise errors.ValidationError( '', reason='Number of clones should be between 1 and 10') return True
def input_required(answers, current): if not current: raise errors.ValidationError('', reason='This field is required') return True
def name_validation(answers, current): if current == "": raise errors.ValidationError('', reason='Plz enter a correct name :)') return True
def val(_, x): if x.count('\n') < 2: raise errors.ValidationError('', reason='Some bad reason') return True
def raise_exc(x, current): if current != "9999": raise errors.ValidationError("", reason="Custom error") return True
def phone_validation(answers, current): if not re.match('\+?\d[\d ]+\d', current): raise errors.ValidationError('', reason='I don\'t like your phone number!') return True