<commit_before>import re
import os
import sys
import parse
import time
import itertools
import datetime
from IPython.parallel import Client
import requests
import zipfile
import cStringIO as StringIO
from BeautifulSoup import BeautifulSoup as bs

sys.path.append('lib')
import lib.patSQL as patSQL
from config_parser import get_config_options

# table bookkeeping for the parse script

assignee_table = patSQL.AssigneeSQL()
citation_table = patSQL.CitationSQL()
class_table = patSQL.ClassSQL()
inventor_table = patSQL.InventorSQL()
patent_table = patSQL.PatentSQL()
patdesc_table = patSQL.PatdescSQL()
lawyer_table = patSQL.LawyerSQL()
sciref_table = patSQL.ScirefSQL()
usreldoc_table = patSQL.UsreldocSQL()

xmlclasses = [patSQL.AssigneeXML, patSQL.CitationXML, patSQL.ClassXML, \
              patSQL.InventorXML, patSQL.PatentXML, patSQL.PatdescXML, \
              patSQL.LawyerXML, patSQL.ScirefXML, patSQL.UsreldocXML]

def get_year_list(yearstring):
    """
    Given a [yearstring] of forms
    year1
    year1-year2
    year1,year2,year3
    year1-year2,year3-year4
    Expands into a list of year integers, and returns
    """
    years = []
    for subset in yearstring.split(','):
        if subset == 'latest':
            years.append('latest')
            continue
        sublist = subset.split('-')
        start = int(sublist[0])
        end = int(sublist[1])+1 if len(sublist) > 1 else start+1
        years.extend(range(start,end))
    return years

def generate_download_list(years):
    """
    Given the year string from the configuration file, return
    a list of urls to be downloaded
    """
    if not years: return []
    urls = []
    url = requests.get('https://www.google.com/googlebooks/uspto-patents-grants-text.html')
    soup = bs(url.content)
    years = get_year_list(years)

    # latest file link
    if 'latest' in years:
        a = soup.h3.findNext('h3').findPrevious('a')
        urls.append(a['href'])
        years.remove('latest')
    # get year links
    for year in years:
        header = soup.find('h3', {'id': str(year)})
        a = header.findNext()
        while a.name != 'h3':
            urls.append(a['href'])
            a = a.findNext()
    return urls

def download_files():
    """
    [downloaddir]: string representing base download directory. Will download
    files to this directory in folders named for each year
    Returns: False if files were not downloaded or if there was some error,
    True otherwise
    """
    import os
    import requests
    import zipfile
    import cStringIO as StringIO
    if not (downloaddir and urls): return False
    complete = True
    print 'downloading to',downloaddir
    for url in urls:
        filename = url.split('/')[-1].replace('zip','xml')
        if filename in os.listdir(downloaddir):
            print 'already have',filename
            continue
        print 'downloading',url
        try:
            r = requests.get(url)
            z = zipfile.ZipFile(StringIO.StringIO(r.content))
            print 'unzipping',filename
            z.extractall(downloaddir)
        except:
            print 'ERROR: downloading or unzipping',filename
            complete = False
            continue
    return complete

def connect_client():
    """
    Loops for a minute until the Client connects to the local ipcluster
    """
    start=time.time()
    print 'Client connecting...'
    while time.time()-start < 300:
        try:
            c = Client()
            dview = c[:]
            break
        except:
            time.sleep(2)
            continue
    return dview

def run_parse():
    import parse
    import time
    import sys
    import itertools
    parsed_xmls = parse.parse_files(files)
    parsed_grants = parse.parse_patents(parsed_xmls)
    parse.build_tables(parsed_grants)
    return parse.get_inserts()

# TODO: these don't work
def run_clean(process_config):
    if process_config['clean']:
        print 'Running clean...'
        import clean

def run_consolidate(process_config):
    if process_config['consolidate']:
        print 'Running consolidate...'
        import consolidate

if __name__=='__main__':
    s = datetime.datetime.now()
    # accepts path to configuration file as command line option
    process_config, parse_config = get_config_options(sys.argv[1])

    # connect to ipcluster and get config options
    dview = connect_client()
    dview.block=True
    dview['process_config'] = process_config
    dview['parse_config'] = parse_config

    # download the files to be parsed
    urls = generate_download_list(parse_config['years'])
    dview.scatter('urls', urls)
    # check download directory
    downloaddir = parse_config['downloaddir']
    if downloaddir and not os.path.exists(downloaddir):
        os.makedirs(downloaddir)
    dview['downloaddir'] = parse_config['downloaddir']
    dview.apply(download_files)
    print 'Downloaded files:',parse_config['years']
    f = datetime.datetime.now()
    print 'Finished downloading in {0}'.format(str(f-s))

    # find files
    print "Starting parse on {0} on directory {1}".format(str(datetime.datetime.today()),parse_config['datadir'])
    files = parse.list_files(parse_config['datadir'],parse_config['dataregex'])
    dview.scatter('files',files)
    print "Found {2} files matching {0} in directory {1}".format(parse_config['dataregex'], parse_config['datadir'], len(files))

    # run parse and commit SQL
    print 'Running parse...'
    inserts = list(itertools.chain.from_iterable(dview.apply(run_parse)))
    parse.commit_tables(inserts)
    f = datetime.datetime.now()
    print 'Finished parsing in {0}'.format(str(f-s))

    # run extra phases if needed, then move output files
    run_clean(process_config)
    run_consolidate(process_config)
    parse.move_tables(process_config['outputdir'])
<commit_msg>remove references to old code<commit_after>import re
import os
import sys
import parse
import time
import itertools
import datetime
from IPython.parallel import Client
import requests
import zipfile
import cStringIO as StringIO
from BeautifulSoup import BeautifulSoup as bs
import lib.alchemy as alchemy

sys.path.append('lib')
from config_parser import get_config_options

# table bookkeeping for the parse script

def get_year_list(yearstring):
    """
    Given a [yearstring] of forms
    year1
    year1-year2
    year1,year2,year3
    year1-year2,year3-year4
    Expands into a list of year integers, and returns
    """
    years = []
    for subset in yearstring.split(','):
        if subset == 'latest':
            years.append('latest')
            continue
        sublist = subset.split('-')
        start = int(sublist[0])
        end = int(sublist[1])+1 if len(sublist) > 1 else start+1
        years.extend(range(start,end))
    return years

def generate_download_list(years):
    """
    Given the year string from the configuration file, return
    a list of urls to be downloaded
    """
    if not years: return []
    urls = []
    url = requests.get('https://www.google.com/googlebooks/uspto-patents-grants-text.html')
    soup = bs(url.content)
    years = get_year_list(years)

    # latest file link
    if 'latest' in years:
        a = soup.h3.findNext('h3').findPrevious('a')
        urls.append(a['href'])
        years.remove('latest')
    # get year links
    for year in years:
        header = soup.find('h3', {'id': str(year)})
        a = header.findNext()
        while a.name != 'h3':
            urls.append(a['href'])
            a = a.findNext()
    return urls

def download_files():
    """
    [downloaddir]: string representing base download directory. Will download
    files to this directory in folders named for each year
    Returns: False if files were not downloaded or if there was some error,
    True otherwise
    """
    import os
    import requests
    import zipfile
    import cStringIO as StringIO
    if not (downloaddir and urls): return False
    complete = True
    print 'downloading to',downloaddir
    for url in urls:
        filename = url.split('/')[-1].replace('zip','xml')
        if filename in os.listdir(downloaddir):
            print 'already have',filename
            continue
        print 'downloading',url
        try:
            r = requests.get(url)
            z = zipfile.ZipFile(StringIO.StringIO(r.content))
            print 'unzipping',filename
            z.extractall(downloaddir)
        except:
            print 'ERROR: downloading or unzipping',filename
            complete = False
            continue
    return complete

def connect_client():
    """
    Loops for a minute until the Client connects to the local ipcluster
    """
    start=time.time()
    print 'Client connecting...'
    while time.time()-start < 300:
        try:
            c = Client()
            dview = c[:]
            break
        except:
            time.sleep(2)
            continue
    return dview

def run_parse():
    import parse
    import time
    import sys
    import itertools
    parsed_xmls = parse.parse_files(files)
    parsed_grants = parse.parse_patents(parsed_xmls)
    parse.build_tables(parsed_grants)
    return parse.get_inserts()

# TODO: these don't work
def run_clean(process_config):
    if process_config['clean']:
        print 'Running clean...'
        import clean

def run_consolidate(process_config):
    if process_config['consolidate']:
        print 'Running consolidate...'
        import consolidate

if __name__=='__main__':
    s = datetime.datetime.now()
    # accepts path to configuration file as command line option
    process_config, parse_config = get_config_options(sys.argv[1])

    # connect to ipcluster and get config options
    dview = connect_client()
    dview.block=True
    dview['process_config'] = process_config
    dview['parse_config'] = parse_config

    # download the files to be parsed
    urls = generate_download_list(parse_config['years'])
    dview.scatter('urls', urls)
    # check download directory
    downloaddir = parse_config['downloaddir']
    if downloaddir and not os.path.exists(downloaddir):
        os.makedirs(downloaddir)
    dview['downloaddir'] = parse_config['downloaddir']
    dview.apply(download_files)
    print 'Downloaded files:',parse_config['years']
    f = datetime.datetime.now()
    print 'Finished downloading in {0}'.format(str(f-s))

    # find files
    print "Starting parse on {0} on directory {1}".format(str(datetime.datetime.today()),parse_config['datadir'])
    files = parse.list_files(parse_config['datadir'],parse_config['dataregex'])
    dview.scatter('files',files)
    print "Found {2} files matching {0} in directory {1}".format(parse_config['dataregex'], parse_config['datadir'], len(files))

    # run parse and commit SQL
    print 'Running parse...'
    inserts = list(itertools.chain.from_iterable(dview.apply(run_parse)))
    parse.commit_tables(inserts)
    f = datetime.datetime.now()
    print 'Finished parsing in {0}'.format(str(f-s))

    # run extra phases if needed, then move output files
    run_clean(process_config)
    run_consolidate(process_config)
    parse.move_tables(process_config['outputdir'])
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Easy PS4 Exploit Hosting by Al-Azif
   Source: https://github.com/Al-Azif/ps4-exploit-host
"""

from __future__ import print_function

try:
    import argparse
    import hashlib
    from http.server import BaseHTTPRequestHandler
    from http.server import HTTPServer
    import mimetypes
    import os
    import re
    import socket
    from socketserver import ThreadingMixIn
    import sys
    import threading
    import time

    import FakeDns.fakedns as fakedns
except ImportError:
    if sys.version_info.major < 3:
        print('ERROR: This must be run on Python 3')
        try:
            input('Press [ENTER] to exit')
        finally:
            sys.exit()
    else:
        print('ERROR: Import Error')
        try:
            input('Press [ENTER] to exit')
        finally:
            sys.exit()

SCRIPT_LOC = os.path.realpath(__file__)
CWD = os.path.dirname(SCRIPT_LOC)
EXPLOIT_LOC = os.path.join(CWD, 'exploit')
PAYLOAD_LOC = os.path.join(CWD, 'payloads')
DNS_LOC = os.path.join(CWD, 'dns.conf')
DEBUG = False
AUTOSEND = None

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    pass

class MyHandler(BaseHTTPRequestHandler):
    error_message_format = ''

    def send_response(self, code, message=None):
        """Blanks out default headers"""
        self.log_request(code)
        self.send_response_only(code, message)

    def do_GET(self):
        """Determines how to handle HTTP requests"""
        try:
            path = self.path.rsplit('/', 1)[-1]
            if path == 'ps4-updatelist.xml':
                region = self.path.split('/')[4]
                path = os.path.join(CWD, 'updates', 'ps4-updatelist.xml')
                with open(path, 'rb') as buf:
                    xml = buf.read()
                xml = xml.replace(b'{{REGION}}', bytes(region, 'utf-8'))
                self.send_response(200)
                self.send_header('Content-type', 'application/xml')
                self.end_headers()
                self.wfile.write(xml)
            elif path == 'ps4-updatefeature.html':
                path = os.path.join(CWD, 'updates', path)
                with open(path, 'rb') as buf:
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    self.wfile.write(buf.read())
            elif path.endswith('.PUP'):
                path = os.path.join(CWD, 'updates', path)
                with open(path, 'rb') as buf:
                    self.send_response(200)
                    self.send_header('Content-type', 'text/plain')
                    self.end_headers()
                    self.wfile.write(buf.read())
            elif re.match('/document/[a-zA-Z\-]{2,5}/ps4/', self.path):
                if not path or path == '/':
                    path = 'index.html'
                mime = mimetypes.guess_type(path)
                if not mime[0]:
                    mime[0] = 'application/octet-stream'
                with open(os.path.join(EXPLOIT_LOC, path), 'rb') as buf:
                    data = buf.read()
                    if path == 'index.html':
                        data = inject_credits(data)
                    self.send_response(200)
                    self.send_header('Content-type', mime[0])
                    self.end_headers()
                    self.wfile.write(data)
            else:
                self.send_error(404)
        except IOError:
            self.send_error(404)

        if path == 'rop.js':
            payload_menu = True
            for thread in threading.enumerate():
                if thread.name == 'Payload_Brain':
                    payload_menu = False

            if payload_menu:
                print('>> Exploit Sent...')
                thread = threading.Thread(name='Payload_Brain',
                                          target=payload_brain,
                                          args=(self.client_address[0],),
                                          daemon=True)
                thread.start()

def check_root():
    """Checks if the user is root.

    Windows returns true because there are no priviledged ports
    """
    try:
        root = bool(os.getuid() == 0)
    except AttributeError:
        root = True

    return root

def get_lan():
    """Gets the computer's LAN IP"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        soc.connect(('10.255.255.255', 1))
        lan = str(soc.getsockname()[0])
        soc.close()
    except socket.error:
        soc.close()
        closer('ERROR: Unable to find LAN IP')

    return lan

def write_conf(lan):
    """Writes the configuration file for FakeDns"""
    exists = os.path.isfile(DNS_LOC)

    try:
        with open(DNS_LOC, 'w+') as buf:
            buf.write('A manuals.playstation.net ' + lan + '\n')
            buf.write('A update.playstation.net ' + lan + '\n')
            buf.write('A f[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A h[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A [a-z0-9\.\-]*.cddbp.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.llnwd.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.org 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ribob01.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sbdnpd.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.scea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sonyentertainmentnetwork.com 0.0.0.0\n')
        if not exists:
            fix_permissions()
        return True
    except IOError:
        return False

def fix_permissions():
    """Make FakeDNS config file the same permissions as start.py

       This should only be run if the config didn't exist before
       It will not include execution privileges
    """
    try:
        stats = os.stat(SCRIPT_LOC)

        os.chown(DNS_LOC, stats.st_uid, stats.st_gid)

        mask = oct(stats.st_mode & 0o777)
        newmask = ''

        for i in mask:
            if i != 'o':
                if int(i) % 2 != 0:
                    i = str(int(i) - 1)
            newmask += i

        mask = int(newmask, 8)
        os.chmod(DNS_LOC, mask)
    except AttributeError:
        pass
    except OSError:
        print('NON-FATAL ERROR: Unable to change permissions of DNS config')

def check_update_pup(type, md5):
    try:
        update_name = 'PS4UPDATE_{}.PUP'.format(type)
        with open(os.path.join(CWD, 'updates', update_name), 'rb') as buf:
            check = '>> Checking {}\'s checksum'.format(update_name)
            print(check, end='\r')
            hasher = hashlib.md5()
            data = buf.read()
            hasher.update(data)
            system_hash = hasher.hexdigest().upper()
            if system_hash != md5:
                closer('ERROR: {} is not version 4.05'.format(update_name))
            print('>> {} checksum matches   '.format(update_name))
    except IOError:
        pass

def start_servers():
    """Start DNS and HTTP servers on seperate threads"""
    print('>> Starting DNS server thread...', end='\r')
    fakedns.main(DNS_LOC, DEBUG)
    print('>> DNS server thread is running...')

    print('>> Starting HTTP server thread...', end='\r')
    server = ThreadedHTTPServer(('', 80), MyHandler)
    thread = threading.Thread(name='HTTP_Server',
                              target=server.serve_forever,
                              args=(),
                              daemon=True)
    thread.start()
    print('>> HTTP server thread is running...')

def payload_brain(ipaddr):
    """Decides which payloads to send"""
    payloads = []
    for files in os.listdir(os.path.join(PAYLOAD_LOC)):
        if not files.endswith('PUT PAYLOADS HERE'):
            payloads.append(files)
    if not payloads:
        print('>> No payloads found')
    elif AUTOSEND in payloads:
        with open(os.path.join(PAYLOAD_LOC, AUTOSEND), 'rb') as buf:
            print('>> Sending {}...'.format(AUTOSEND))
            content = buf.read()
        send_payload(ipaddr, 9020, content)
    else:
        choice = payload_menu(payloads)
        if choice != 0:
            path = os.path.join(PAYLOAD_LOC, payloads[choice - 1])
            with open(path, 'rb') as buf:
                print('>> Sending {}...'.format(payloads[choice - 1]))
                content = buf.read()
            send_payload(ipaddr, 9020, content)
        else:
            print('>> No payload sent')

def payload_menu(payloads):
    """Displays a menu with all available payloads in it"""
    i = 1
    choice = -1
    print('┌────────────────────────────────────────────────────────┐')
    print('│  Payloads                                              │')
    print('├────────────────────────────────────────────────────────┤')
    print('│  0. Don\'t send a payload                               │')
    for payload in payloads:
        payload = '│  {}. {}'.format(i, payload)
        if len(payload) > 58:
            payload = payload[:56]
        while len(payload) < 56:
            payload += ' '
        payload += ' │'
        print(payload)
        i += 1
    print('└────────────────────────────────────────────────────────┘')
    while choice < 0 or choice >= i:
        choice = input('Choose a payload to send: ')
        try:
            choice = int(choice)
        except (ValueError, NameError):
            choice = -1

    return choice

def send_payload(hostname, port, content):
    """Netcat implementation"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    timeout = time.time() + 15
    while True:
        result = soc.connect_ex((hostname, port))
        if result == 0:
            print('>> Connected to PS4')
            timed_out = False
            break
        if time.time() >= timeout:
            print('ERROR: Payload sender timed out')
            timed_out = True
            break
    if not timed_out:
        try:
            soc.sendall(content)
            soc.shutdown(socket.SHUT_WR)
            while True:
                data = soc.recv(1024)
                if not data:
                    break
            print('>> Payload Sent!')
        except socket.error:
            print('ERROR: Broken Pipe')
    soc.close()

def exploit_menu():
    """Displays a list of subdirectories in "exploit" folder"""
    i = 1
    choice = -1
    exploits = os.listdir(EXPLOIT_LOC)
    if not exploits:
        closer('ERROR: No exploits found')
    print('┌────────────────────────────────────────────────────────┐')
    print('│  Exploits                                              │')
    print('├────────────────────────────────────────────────────────┤')
    for exploit in exploits:
        exploit = '│  {}. {}'.format(i, exploit)
        if len(exploit) > 58:
            exploit = exploit[:56]
        while len(exploit) < 56:
            exploit += ' '
        exploit += ' │'
        print(exploit)
        i += 1
    print('└────────────────────────────────────────────────────────┘')
    while choice < 1 or choice >= i:
        choice = input('Choose an exploit to host: ')
        try:
            choice = int(choice)
        except (ValueError, NameError):
            choice = -1

    return exploits[choice - 1]

def silence_http(self, format, *args):
    """Just blackhole this method to prevent printing"""
    pass

def getch():
    """MIT Licensed: https://github.com/joeyespo/py-getch"""
    import termios
    import tty

    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        return sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)

def closer(message):
    """Closing method"""
    print(message)
    if message != '\r>> Exiting...                                           ':
        print('Press any key to exit...', end='')
        sys.stdout.flush()
        if os.name == 'nt':
            from msvcrt import getch as w_getch
            w_getch()
        else:
            getch()
        print()
    sys.exit()

def menu_header():
    """Very first thing that prints"""
    print('┌────────────────────────────────────────────────────────┐')
    print('│  PS4 Exploit Host                           by Al Azif │')
    print('└────────────────────────────────────────────────────────┘')

def inject_credits(html):
    inject = b'
...
PS4 Exploit Host by ' + \
             b'Al Azif
'

    return html.replace(b'
...
', inject)

def main():
    """The main logic"""
    global DEBUG
    global AUTOSEND
    global EXPLOIT_LOC

    menu_header()

    if not check_root():
        closer('ERROR: This must be run by root as it requires port 53 & 80')

    parser = argparse.ArgumentParser(description='PS4 Exploit Host')
    parser.add_argument('--exploit', dest='e_type', action='store',
                        default='', required=False,
                        help='Select which exploit to host')
    parser.add_argument('--autosend', dest='autosend', action='store',
                        default='', required=False,
                        help='Automatically send payload when exploit loads')
    parser.add_argument('--debug', action='store_true',
                        required=False, help='Print debug statements')
    args = parser.parse_args()

    try:
        if args.debug:
            DEBUG = True
        else:
            MyHandler.log_message = silence_http

        if args.autosend:
            if os.path.isfile(os.path.join(PAYLOAD_LOC, args.autosend)):
                AUTOSEND = args.autosend
            else:
                closer('ERROR: Autosend payload not found')

        check_update_pup('SYSTEM', '203C76C97F7BE5B881DD0C77C8EDF385')
        check_update_pup('RECOVERY', '741CFE2F0DEC1BB4663571DE78AE31CF')

        if not args.e_type:
            args.e_type = exploit_menu()

        if os.path.isdir(os.path.join(EXPLOIT_LOC, args.e_type)) \
           and args.e_type:
            EXPLOIT_LOC = os.path.join(EXPLOIT_LOC, args.e_type)
        else:
            closer('ERROR: Could not find exploit specified')

        lan = get_lan()

        if write_conf(lan):
            while len(lan) < 15:
                lan += ' '
            print('╔════════════════════════════════════════════════════════╗')
            print('║             Your DNS IP is {}             ║'.format(lan))
            print('╚════════════════════════════════════════════════════════╝')
        else:
            closer('ERROR: Unable to write {}'.format(DNS_LOC))

        start_servers()

        while True:
            pass
    except KeyboardInterrupt:
        closer('\r>> Exiting...                                           ')

if __name__ == '__main__':
    main()
<commit_msg>Menu refactoring<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Easy PS4 Exploit Hosting by Al-Azif
   Source: https://github.com/Al-Azif/ps4-exploit-host
"""

from __future__ import print_function

try:
    import argparse
    import hashlib
    from http.server import BaseHTTPRequestHandler
    from http.server import HTTPServer
    import mimetypes
    import os
    import re
    import socket
    from socketserver import ThreadingMixIn
    import sys
    import threading
    import time

    import FakeDns.fakedns as fakedns
except ImportError:
    if sys.version_info.major < 3:
        print('ERROR: This must be run on Python 3')
        try:
            input('Press [ENTER] to exit')
        finally:
            sys.exit()
    else:
        print('ERROR: Import Error')
        try:
            input('Press [ENTER] to exit')
        finally:
            sys.exit()

SCRIPT_LOC = os.path.realpath(__file__)
CWD = os.path.dirname(SCRIPT_LOC)
EXPLOIT_LOC = os.path.join(CWD, 'exploit')
PAYLOAD_LOC = os.path.join(CWD, 'payloads')
DNS_LOC = os.path.join(CWD, 'dns.conf')
DEBUG = False
AUTOSEND = None

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    pass

class MyHandler(BaseHTTPRequestHandler):
    error_message_format = ''

    def send_response(self, code, message=None):
        """Blanks out default headers"""
        self.log_request(code)
        self.send_response_only(code, message)

    def do_GET(self):
        """Determines how to handle HTTP requests"""
        try:
            path = self.path.rsplit('/', 1)[-1]
            if path == 'ps4-updatelist.xml':
                region = self.path.split('/')[4]
                path = os.path.join(CWD, 'updates', 'ps4-updatelist.xml')
                with open(path, 'rb') as buf:
                    xml = buf.read()
                xml = xml.replace(b'{{REGION}}', bytes(region, 'utf-8'))
                self.send_response(200)
                self.send_header('Content-type', 'application/xml')
                self.end_headers()
                self.wfile.write(xml)
            elif path == 'ps4-updatefeature.html':
                path = os.path.join(CWD, 'updates', path)
                with open(path, 'rb') as buf:
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    self.wfile.write(buf.read())
            elif path.endswith('.PUP'):
                path = os.path.join(CWD, 'updates', path)
                with open(path, 'rb') as buf:
                    self.send_response(200)
                    self.send_header('Content-type', 'text/plain')
                    self.end_headers()
                    self.wfile.write(buf.read())
            elif re.match('/document/[a-zA-Z\-]{2,5}/ps4/', self.path):
                if not path or path == '/':
                    path = 'index.html'
                mime = mimetypes.guess_type(path)
                if not mime[0]:
                    mime[0] = 'application/octet-stream'
                with open(os.path.join(EXPLOIT_LOC, path), 'rb') as buf:
                    data = buf.read()
                    if path == 'index.html':
                        data = inject_credits(data)
                    self.send_response(200)
                    self.send_header('Content-type', mime[0])
                    self.end_headers()
                    self.wfile.write(data)
            else:
                self.send_error(404)
        except IOError:
            self.send_error(404)

        if path == 'rop.js':
            payload_menu = True
            for thread in threading.enumerate():
                if thread.name == 'Payload_Brain':
                    payload_menu = False

            if payload_menu:
                print('>> Exploit Sent...')
                thread = threading.Thread(name='Payload_Brain',
                                          target=payload_brain,
                                          args=(self.client_address[0],),
                                          daemon=True)
                thread.start()

def check_root():
    """Checks if the user is root.

    Windows returns true because there are no priviledged ports
    """
    try:
        root = bool(os.getuid() == 0)
    except AttributeError:
        root = True

    return root

def get_lan():
    """Gets the computer's LAN IP"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        soc.connect(('10.255.255.255', 1))
        lan = str(soc.getsockname()[0])
        soc.close()
    except socket.error:
        soc.close()
        closer('ERROR: Unable to find LAN IP')

    return lan

def write_conf(lan):
    """Writes the configuration file for FakeDns"""
    exists = os.path.isfile(DNS_LOC)

    try:
        with open(DNS_LOC, 'w+') as buf:
            buf.write('A manuals.playstation.net ' + lan + '\n')
            buf.write('A update.playstation.net ' + lan + '\n')
            buf.write('A f[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A h[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A [a-z0-9\.\-]*.cddbp.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.llnwd.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.org 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ribob01.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sbdnpd.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.scea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sonyentertainmentnetwork.com 0.0.0.0\n')
        if not exists:
            fix_permissions()
        return True
    except IOError:
        return False

def fix_permissions():
    """Make FakeDNS config file the same permissions as start.py

       This should only be run if the config didn't exist before
       It will not include execution privileges
    """
    try:
        stats = os.stat(SCRIPT_LOC)

        os.chown(DNS_LOC, stats.st_uid, stats.st_gid)

        mask = oct(stats.st_mode & 0o777)
        newmask = ''

        for i in mask:
            if i != 'o':
                if int(i) % 2 != 0:
                    i = str(int(i) - 1)
            newmask += i

        mask = int(newmask, 8)
        os.chmod(DNS_LOC, mask)
    except AttributeError:
        pass
    except OSError:
        print('NON-FATAL ERROR: Unable to change permissions of DNS config')

def check_update_pup(type, md5):
    try:
        update_name = 'PS4UPDATE_{}.PUP'.format(type)
        with open(os.path.join(CWD, 'updates', update_name), 'rb') as buf:
            check = '>> Checking {}\'s checksum'.format(update_name)
            print(check, end='\r')
            hasher = hashlib.md5()
            data = buf.read()
            hasher.update(data)
            system_hash = hasher.hexdigest().upper()
            if system_hash != md5:
                closer('ERROR: {} is not version 4.05'.format(update_name))
            print('>> {} checksum matches   '.format(update_name))
    except IOError:
        pass

def start_servers():
    """Start DNS and HTTP servers on seperate threads"""
    print('>> Starting DNS server thread...', end='\r')
    fakedns.main(DNS_LOC, DEBUG)
    print('>> DNS server thread is running...')

    print('>> Starting HTTP server thread...', end='\r')
    server = ThreadedHTTPServer(('', 80), MyHandler)
    thread = threading.Thread(name='HTTP_Server',
                              target=server.serve_forever,
                              args=(),
                              daemon=True)
    thread.start()
    print('>> HTTP server thread is running...')

def payload_brain(ipaddr):
    """Decides which payloads to send"""
    payloads = []
    for files in os.listdir(os.path.join(PAYLOAD_LOC)):
        if not files.endswith('PUT PAYLOADS HERE'):
            payloads.append(files)
    if not payloads:
        print('>> No payloads found')
    elif AUTOSEND in payloads:
        with open(os.path.join(PAYLOAD_LOC, AUTOSEND), 'rb') as buf:
            print('>> Sending {}...'.format(AUTOSEND))
            content = buf.read()
        send_payload(ipaddr, 9020, content)
    else:
        payloads.insert(0, 'Don\'t send a payload')
        choice = menu('Payload', payloads)
        if choice != 1:
            path = os.path.join(PAYLOAD_LOC, payloads[choice - 1])
            with open(path, 'rb') as buf:
                print('>> Sending {}...'.format(payloads[choice - 1]))
                content = buf.read()
            send_payload(ipaddr, 9020, content)
        else:
            print('>> No payload sent')

def menu(type, input_array):
    i = 1
    choice = 0
    print('┌────────────────────────────────────────────────────────┐')
    title = '│  {}'.format(type)
    print(format_menu_item(title))
    print('├────────────────────────────────────────────────────────┤')
    for entry in input_array:
        entry = '│  {}. {}'.format(i, entry)
        print(format_menu_item(entry))
        i += 1
    print('└────────────────────────────────────────────────────────┘')
    while choice < 1 or choice >= i:
        input_prompt = 'Choose a {} to send: '.format(type.lower())
        choice = input(input_prompt)
        try:
            choice = int(choice)
        except (ValueError, NameError):
            choice = 0

    return choice

def format_menu_item(entry):
    if len(entry) > 58:
        entry = entry[:56]
    while len(entry) < 56:
        entry += ' '
    entry += ' │'
    return entry

def send_payload(hostname, port, content):
    """Netcat implementation"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    timeout = time.time() + 15
    while True:
        result = soc.connect_ex((hostname, port))
        if result == 0:
            print('>> Connected to PS4')
            timed_out = False
            break
        if time.time() >= timeout:
            print('ERROR: Payload sender timed out')
            timed_out = True
            break
    if not timed_out:
        try:
            soc.sendall(content)
            soc.shutdown(socket.SHUT_WR)
            while True:
                data = soc.recv(1024)
                if not data:
                    break
            print('>> Payload Sent!')
        except socket.error:
            print('ERROR: Broken Pipe')
    soc.close()

def silence_http(self, format, *args):
    """Just blackhole this method to prevent printing"""
    pass

def getch():
    """MIT Licensed: https://github.com/joeyespo/py-getch"""
    import termios
    import tty

    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        return sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)

def closer(message):
    """Closing method"""
    print(message)
    if message != '\r>> Exiting...                                           ':
        print('Press any key to exit...', end='')
        sys.stdout.flush()
        if os.name == 'nt':
            from msvcrt import getch as w_getch
            w_getch()
        else:
            getch()
        print()
    sys.exit()

def menu_header():
    """Very first thing that prints"""
    print('┌────────────────────────────────────────────────────────┐')
    print('│  PS4 Exploit Host                           by Al Azif │')
    print('└────────────────────────────────────────────────────────┘')

def inject_credits(html):
    inject = b'
...
PS4 Exploit Host by ' + \
             b'Al Azif
'

    return html.replace(b'
...
', inject)

def main():
    """The main logic"""
    global DEBUG
    global AUTOSEND
    global EXPLOIT_LOC

    menu_header()

    if not check_root():
        closer('ERROR: This must be run by root as it requires port 53 & 80')

    parser = argparse.ArgumentParser(description='PS4 Exploit Host')
    parser.add_argument('--exploit', dest='e_type', action='store',
                        default='', required=False,
                        help='Select which exploit to host')
    parser.add_argument('--autosend', dest='autosend', action='store',
                        default='', required=False,
                        help='Automatically send payload when exploit loads')
    parser.add_argument('--debug', action='store_true',
                        required=False, help='Print debug statements')
    args = parser.parse_args()

    try:
        if args.debug:
            DEBUG = True
        else:
            MyHandler.log_message = silence_http

        if args.autosend:
            if os.path.isfile(os.path.join(PAYLOAD_LOC, args.autosend)):
                AUTOSEND = args.autosend
            else:
                closer('ERROR: Autosend payload not found')

        check_update_pup('SYSTEM', '203C76C97F7BE5B881DD0C77C8EDF385')
        check_update_pup('RECOVERY', '741CFE2F0DEC1BB4663571DE78AE31CF')

        if not args.e_type:
            exploits = os.listdir(EXPLOIT_LOC)
            if not exploits:
                closer('ERROR: No exploits found')
            exploit = menu('Exploit', exploits)
            args.e_type = exploits[exploit - 1]

        if os.path.isdir(os.path.join(EXPLOIT_LOC, args.e_type)) \
           and args.e_type:
            EXPLOIT_LOC = os.path.join(EXPLOIT_LOC, args.e_type)
        else:
            closer('ERROR: Could not find exploit specified')

        lan = get_lan()

        if write_conf(lan):
            while len(lan) < 15:
                lan += ' '
            print('╔════════════════════════════════════════════════════════╗')
            print('║             Your DNS IP is {}             ║'.format(lan))
            print('╚════════════════════════════════════════════════════════╝')
        else:
            closer('ERROR: Unable to write {}'.format(DNS_LOC))

        start_servers()

        while True:
            pass
    except KeyboardInterrupt:
        closer('\r>> Exiting...                                           ')

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Easy PS4 Exploit Hosting by Al-Azif
   Source: https://github.com/Al-Azif/ps4-exploit-host
"""

import argparse
import hashlib
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
import ipaddress
import mimetypes
import os
import re
import socket
import sys
import threading
import time

import FakeDns.fakedns as fakedns

SCRIPT_LOC = os.path.realpath(__file__)
CWD = os.path.dirname(SCRIPT_LOC)
EXPLOIT_LOC = os.path.join(CWD, 'exploit')
FAKE_LOC = os.path.join(CWD, 'FakeDns', 'fakedns.py')
DNS_LOC = os.path.join(CWD, 'dns.conf')
DEBUG = False

class ThreadedHTTPServer(HTTPServer):
    def process_request(self, request, client_address):
        thread = threading.Thread(target=self.__new_request,
                                  args=(self.RequestHandlerClass, request,
                                        client_address, self))
        thread.start()

    def __new_request(self, handlerClass, request, address, server):
        handlerClass(request, address, server)
        self.shutdown_request(request)

class MyHandler(BaseHTTPRequestHandler):
    server_version = ''
    sys_version = ''
    error_message_format = ''

    def do_GET(self):
        client = self.client_address[0]
        if not check_lan(client, get_network(get_lan())):
            self.send_error(403)
        else:
            try:
                path = self.path.rsplit('/', 1)[-1]
                if path == 'ps4-updatelist.xml':
                    region = self.path.split('/')[4]
                    path = os.path.join(CWD, 'updates', 'ps4-updatelist.xml')
                    with open(path, 'rb') as buf:
                        xml = buf.read()
                    xml = xml.replace(b'{{REGION}}', bytes(region, 'utf-8'))
                    self.send_response(200)
                    self.send_header('Content-type', 'application/xml')
                    self.end_headers()
                    self.wfile.write(xml)
                elif path == 'ps4-updatefeature.html':
                    path = os.path.join(CWD, 'updates', path)
                    with open(path, 'rb') as buf:
                        self.send_response(200)
                        self.send_header('Content-type', 'text/html')
                        self.end_headers()
                        self.wfile.write(buf.read())
                elif self.path.endswith('.PUP'):
                    path = os.path.join(CWD, 'updates', path)
                    with open(path, 'rb') as buf:
                        self.send_response(200)
                        self.send_header('Content-type', 'text/plain')
                        self.end_headers()
                        self.wfile.write(buf.read())
                elif re.match('/document/[a-zA-Z\-]{2,5}/ps4/', self.path):
                    if not path:
                        path = 'index.html'
                    mime = mimetypes.guess_type(path)
                    if not mime[0]:
                        mime[0] = 'application/octet-stream'
                    with open(os.path.join(EXPLOIT_LOC, path), 'rb') as buf:
                        self.send_response(200)
                        self.send_header('Content-type', mime[0])
                        self.end_headers()
                        self.wfile.write(buf.read())
                else:
                    self.send_error(404)
            except IOError:
                self.send_error(404)

            if path == 'rop.js':
                print('>> Exploit Sent...')
                thread = threading.Thread(target=payload_brain,
                                          args=(self.client_address[0],))
                thread.daemon = True
                thread.start()

def check_root():
    """Checks if the user is root.

    Windows returns true because there are no priviledged ports
    """
    try:
        root = bool(os.getuid() == 0)
    except AttributeError:
        root = True

    return root

def get_lan():
    """Gets the computer's LAN IP"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        soc.connect(('10.255.255.255', 1))
        lan = str(soc.getsockname()[0])
        soc.close()
    except socket.error:
        soc.close()
        closer('ERROR: Unable to find LAN IP')

    return lan

def get_network(ipaddr):
    """Guesses the private network based on the IP address"""
    ipaddr = ipaddr.split('.')

    if ipaddr[0] == '10':
        network = '10.0.0.0/8'
    elif ipaddr[0] == '172' and 16 <= int(ipaddr[1]) <= 31:
        network = '172.16.0.0/12'
    elif ipaddr[0] == '192' and ipaddr[1] == '168':
        network = '192.168.0.0/16'
    else:
        print('WARNING: Could not figure out private network, ' +
              'LAN blocking will not work')
        network = '0.0.0.0/0'

    return network

def check_lan(ipaddr, network):
    """Checks to see if the IP address is contained within the network"""
    if network == '0.0.0.0/0':
        return True
    elif bool(ipaddress.ip_address(ipaddr) in ipaddress.ip_network(network)):
        return True

def write_conf(lan):
    """Writes the configuration file for FakeDns"""
    exists = os.path.isfile(DNS_LOC)

    try:
        with open(DNS_LOC, 'w+') as buf:
            buf.write('A manuals.playstation.net ' + lan + '\n')
            buf.write('A update.playstation.net ' + lan + '\n')
            buf.write('A f[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A h[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A [a-z0-9\.\-]*.cddbp.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.llnwd.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.org 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ribob01.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sbdnpd.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.scea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sonyentertainmentnetwork.com 0.0.0.0\n')
        if not exists:
            fix_permissions()
        return True
    except IOError:
        return False

def fix_permissions():
    """Make FakeDNS config file the same permissions as start.py

       This should only be run if the config didn't exist before
       It will not include execution privileges
    """
    try:
        stats = os.stat(SCRIPT_LOC)

        os.chown(DNS_LOC, stats.st_uid, stats.st_gid)

        mask = oct(stats.st_mode & 0o777)
        newmask = ''

        for i in mask:
            if i != 'o':
                if int(i) % 2 != 0:
                    i = str(int(i) - 1)
            newmask += i

        mask = int(newmask, 8)
        os.chmod(DNS_LOC, mask)
    except AttributeError:
        pass
    except OSError:
        print('NON-FATAL ERROR: Unable to change permissions of DNS config')

def check_update_pups():
    """Checks the actual MD5 checksum vs the expected MD5 sum"""
    try:
        with open(os.path.join(CWD, 'updates',
                               'PS4UPDATE_SYSTEM.PUP'), 'rb') as buf:
            print('>> Checking PS4UPDATE_SYSTEM.PUP\'s checksum')
            hasher = hashlib.md5()
            data = buf.read()
            hasher.update(data)
            system_hash = hasher.hexdigest().upper()
            if system_hash != '203C76C97F7BE5B881DD0C77C8EDF385':
                closer('ERROR: PS4UPDATE_SYSTEM.PUP is not version 4.05')
            clear_line()
            print('>> PS4UPDATE_SYSTEM.PUP checksum matches')
    except IOError:
        pass

    try:
        with open(os.path.join(CWD, 'updates',
                               'PS4UPDATE_RECOVERY.PUP'), 'rb') as buf:
            print('>> Checking PS4UPDATE_RECOVERY.PUP\'s checksum')
            hasher = hashlib.md5()
            data = buf.read()
            hasher.update(data)
            recovery_hash = hasher.hexdigest().upper()
            if recovery_hash != '741CFE2F0DEC1BB4663571DE78AE31CF':
                closer('ERROR: PS4UPDATE_RECOVERY.PUP is not version 4.05')
            clear_line()
            print('>> PS4UPDATE_RECOVERY.PUP checksum matches')
    except IOError:
        pass

def start_servers():
    """Start DNS and HTTP servers on seperate threads"""
    print('>> Starting DNS server thread...')
    fakedns.main(DNS_LOC, DEBUG)
    clear_line()
    print('>> DNS server thread is running...')

    print('>> Starting HTTP server thread...')
    server = ThreadedHTTPServer(('', 80), MyHandler)
    thread = threading.Thread(target=server.serve_forever, args=())
    thread.daemon = True
    thread.start()
    clear_line()
    print('>> HTTP server thread is running...')

def payload_brain(ipaddr):
    payloads = []
    for files in os.listdir(os.path.join(CWD, 'payloads')):
        if not files.endswith('PUT PAYLOADS HERE'):
            payloads.append(files)
    if not payloads:
        print('>> No payloads found')
    else:
        choice = payload_menu(payloads)
        if choice != 0:
            path = os.path.join(CWD, 'payloads', payloads[choice - 1])
            with open(path, 'rb') as buf:
                print('>> Sending {}...'.format(payloads[choice - 1]))
                content = buf.read()
            send_payload(ipaddr, 9020, content)
        else:
            print('>> No payload sent')

def payload_menu(payloads):
    i = 1
    choice = -1
    print('{} Payloads {}'.format('-' * 4, '-' * 46))
    print('0. Don\'t send a payload')
    for payload in payloads:
        print('{}. {}'.format(i, payload))
        i += 1
    print('-' * 60)
    while choice < 0 or choice >= i:
        choice = input('Choose a payload to send: ')
        try:
            choice = int(choice)
        except (ValueError, NameError):
            choice = -1

    return choice

def send_payload(hostname, port, content):
    """Netcat implementation"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    timeout = time.time() + 60
    while True:
        result = soc.connect_ex((hostname, port))
        if result == 0:
            print('>> Connected to PS4')
            timed_out = False
            break
        if time.time() >= timeout:
            print('>> Netcat service timed out')
            timed_out = True
            break
    if not timed_out:
        soc.sendall(content)
        soc.shutdown(socket.SHUT_WR)
        while True:
            data = soc.recv(1024)
            if not data:
                break
        print('>> Payload Sent!')
    soc.close()

def exploit_menu():
    i = 1
    choice = -1
    exploits = os.listdir(EXPLOIT_LOC)
    if not exploits:
        closer('ERROR: No exploits found')
    print('{} Exploits {}'.format('-' * 4, '-' * 46))
    for exploit in exploits:
        print('{}. {}'.format(i, exploit))
        i += 1
    print('-' * 60)
    while choice < 1 or choice >= i:
        choice = input('Choose an exploit to host: ')
        try:
            choice = int(choice)
        except (ValueError, NameError):
            choice = -1

    return exploits[choice - 1]

def silence_http(self, format, *args):
    """Just blackhole this method to prevent printing"""
    pass

def clear_line():
    """Clear last printed line from CLI"""
    sys.stdout.write('\x1b[1A')
    sys.stdout.write('\x1b[2K')

def getch():
    """MIT Licensed: https://github.com/joeyespo/py-getch"""
    import termios
    import tty

    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        return sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)

def closer(message):
    """Closing method"""
    print(message)
    if message != '>> Exiting...':
        print('Press any key to exit...', end='')
        sys.stdout.flush()
        if os.name == 'nt':
            from msvcrt import getch as w_getch
            w_getch()
        else:
            getch()
        print()
    sys.exit()

def main():
    """The main logic"""
    global DEBUG
    global EXPLOIT_LOC

    if not check_root():
        closer('ERROR: This must be run by root as it requires port 53 & 80')

    parser = argparse.ArgumentParser(description='PS4 Exploit Host')
    parser.add_argument('--exploit', dest='e_type', action='store',
                        default='', required=False,
                        help='Select which exploit to host')
    parser.add_argument('--debug', action='store_true',
                        required=False, help='Print debug statements')
    args = parser.parse_args()

    if not args.e_type:
        args.e_type = exploit_menu()

    if os.path.isdir(os.path.join(EXPLOIT_LOC, args.e_type)) and args.e_type:
        EXPLOIT_LOC = os.path.join(EXPLOIT_LOC, args.e_type)
    else:
        closer('ERROR: Could not find exploit specified')

    if args.debug:
        DEBUG = True
    else:
        DEBUG = False
        MyHandler.log_message = silence_http

    check_update_pups()

    lan = get_lan()

    if write_conf(lan):
        print('>> Your DNS IP is {}'.format(lan))
    else:
        closer('ERROR: Unable to write {}'.format(DNS_LOC))

    start_servers()

    try:
        while True:
            pass
    except KeyboardInterrupt:
        closer('>> Exiting...')

if __name__ == '__main__':
    main()
<commit_msg>Fixed a threading issue, shuffled main()<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Easy PS4 Exploit Hosting by Al-Azif
   Source: https://github.com/Al-Azif/ps4-exploit-host
"""

import argparse
import hashlib
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
import ipaddress
import mimetypes
import os
import re
import socket
import sys
import threading
import time

import FakeDns.fakedns as fakedns

SCRIPT_LOC = os.path.realpath(__file__)
CWD = os.path.dirname(SCRIPT_LOC)
EXPLOIT_LOC = os.path.join(CWD, 'exploit')
FAKE_LOC = os.path.join(CWD, 'FakeDns', 'fakedns.py')
DNS_LOC = os.path.join(CWD, 'dns.conf')
DEBUG = False

class ThreadedHTTPServer(HTTPServer):
    def process_request(self, request, client_address):
        thread = threading.Thread(target=self.__new_request,
                                  args=(self.RequestHandlerClass, request,
                                        client_address, self))
        thread.start()

    def __new_request(self, handlerClass, request, address, server):
        handlerClass(request, address, server)
        self.shutdown_request(request)

class MyHandler(BaseHTTPRequestHandler):
    server_version = ''
    sys_version = ''
    error_message_format = ''

    def do_GET(self):
        client = self.client_address[0]
        if not check_lan(client, get_network(get_lan())):
            self.send_error(403)
        else:
            try:
                path = self.path.rsplit('/', 1)[-1]
                if path == 'ps4-updatelist.xml':
                    region = self.path.split('/')[4]
                    path = os.path.join(CWD, 'updates', 'ps4-updatelist.xml')
                    with open(path, 'rb') as buf:
                        xml = buf.read()
                    xml = xml.replace(b'{{REGION}}', bytes(region, 'utf-8'))
                    self.send_response(200)
                    self.send_header('Content-type', 'application/xml')
                    self.end_headers()
                    self.wfile.write(xml)
                elif path == 'ps4-updatefeature.html':
                    path = os.path.join(CWD, 'updates', path)
                    with open(path, 'rb') as buf:
                        self.send_response(200)
                        self.send_header('Content-type', 'text/html')
                        self.end_headers()
                        self.wfile.write(buf.read())
                elif self.path.endswith('.PUP'):
                    path = os.path.join(CWD, 'updates', path)
                    with open(path, 'rb') as buf:
                        self.send_response(200)
                        self.send_header('Content-type', 'text/plain')
                        self.end_headers()
                        self.wfile.write(buf.read())
                elif re.match('/document/[a-zA-Z\-]{2,5}/ps4/', self.path):
                    if not path:
                        path = 'index.html'
                    mime = mimetypes.guess_type(path)
                    if not mime[0]:
                        mime[0] = 'application/octet-stream'
                    with open(os.path.join(EXPLOIT_LOC, path), 'rb') as buf:
                        self.send_response(200)
                        self.send_header('Content-type', mime[0])
                        self.end_headers()
                        self.wfile.write(buf.read())
                else:
                    self.send_error(404)
            except IOError:
                self.send_error(404)

            if path == 'rop.js':
                payload_menu = True
                for thread in threading.enumerate():
                    if thread.name == 'payload_brain':
                        payload_menu = False

                if payload_menu:
                    print('>> Exploit Sent...')
                    thread = threading.Thread(name='payload_brain',
                                              target=payload_brain,
                                              args=(self.client_address[0],),
                                              daemon=True)
                    thread.start()

def check_root():
    """Checks if the user is root.

    Windows returns true because there are no priviledged ports
    """
    try:
        root = bool(os.getuid() == 0)
    except AttributeError:
        root = True

    return root

def get_lan():
    """Gets the computer's LAN IP"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        soc.connect(('10.255.255.255', 1))
        lan = str(soc.getsockname()[0])
        soc.close()
    except socket.error:
        soc.close()
        closer('ERROR: Unable to find LAN IP')

    return lan

def get_network(ipaddr):
    """Guesses the private network based on the IP address"""
    ipaddr = ipaddr.split('.')

    if ipaddr[0] == '10':
        network = '10.0.0.0/8'
    elif ipaddr[0] == '172' and 16 <= int(ipaddr[1]) <= 31:
        network = '172.16.0.0/12'
    elif ipaddr[0] == '192' and ipaddr[1] == '168':
        network = '192.168.0.0/16'
    else:
        print('WARNING: Could not figure out private network, ' +
              'LAN blocking will not work')
        network = '0.0.0.0/0'

    return network

def check_lan(ipaddr, network):
    """Checks to see if the IP address is contained within the network"""
    if network == '0.0.0.0/0':
        return True
    elif bool(ipaddress.ip_address(ipaddr) in ipaddress.ip_network(network)):
        return True

def write_conf(lan):
    """Writes the configuration file for FakeDns"""
    exists = os.path.isfile(DNS_LOC)

    try:
        with open(DNS_LOC, 'w+') as buf:
            buf.write('A manuals.playstation.net ' + lan + '\n')
            buf.write('A update.playstation.net ' + lan + '\n')
            buf.write('A f[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A h[a-z]{2}01.ps4.update.playstation.net ' + lan + '\n')
            buf.write('A [a-z0-9\.\-]*.cddbp.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.llnwd.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.playstation.org 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.ribob01.net 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sbdnpd.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.scea.com 0.0.0.0\n')
            buf.write('A [a-z0-9\.\-]*.sonyentertainmentnetwork.com 0.0.0.0\n')
        if not exists:
            fix_permissions()
        return True
    except IOError:
        return False

def fix_permissions():
    """Make FakeDNS config file the same permissions as start.py

       This should only be run if the config didn't exist before
       It will not include execution privileges
    """
    try:
        stats = os.stat(SCRIPT_LOC)

        os.chown(DNS_LOC, stats.st_uid, stats.st_gid)

        mask = oct(stats.st_mode & 0o777)
        newmask = ''

        for i in mask:
            if i != 'o':
                if int(i) % 2 != 0:
                    i = str(int(i) - 1)
            newmask += i

        mask = int(newmask, 8)
        os.chmod(DNS_LOC, mask)
    except AttributeError:
        pass
    except OSError:
        print('NON-FATAL ERROR: Unable to change permissions of DNS config')

def check_update_pups():
    """Checks the actual MD5 checksum vs the expected MD5 sum"""
    try:
        with open(os.path.join(CWD, 'updates',
                               'PS4UPDATE_SYSTEM.PUP'), 'rb') as buf:
            print('>> Checking PS4UPDATE_SYSTEM.PUP\'s checksum')
            hasher = hashlib.md5()
            data = buf.read()
            hasher.update(data)
            system_hash = hasher.hexdigest().upper()
            if system_hash != '203C76C97F7BE5B881DD0C77C8EDF385':
                closer('ERROR: PS4UPDATE_SYSTEM.PUP is not version 4.05')
            clear_line()
            print('>> PS4UPDATE_SYSTEM.PUP checksum matches')
    except IOError:
        pass

    try:
        with open(os.path.join(CWD, 'updates',
                               'PS4UPDATE_RECOVERY.PUP'), 'rb') as buf:
            print('>> Checking PS4UPDATE_RECOVERY.PUP\'s checksum')
            hasher = hashlib.md5()
            data = buf.read()
            hasher.update(data)
            recovery_hash = hasher.hexdigest().upper()
            if recovery_hash != '741CFE2F0DEC1BB4663571DE78AE31CF':
                closer('ERROR: PS4UPDATE_RECOVERY.PUP is not version 4.05')
            clear_line()
            print('>> PS4UPDATE_RECOVERY.PUP checksum matches')
    except IOError:
        pass

def start_servers():
    """Start DNS and HTTP servers on seperate threads"""
    print('>> Starting DNS server thread...')
    fakedns.main(DNS_LOC, DEBUG)
    clear_line()
    print('>> DNS server thread is running...')

    print('>> Starting HTTP server thread...')
    server = ThreadedHTTPServer(('', 80), MyHandler)
    thread = threading.Thread(target=server.serve_forever,
                              args=(),
                              daemon=True)
    thread.start()
    clear_line()
    print('>> HTTP server thread is running...')

def payload_brain(ipaddr):
    payloads = []
    for files in os.listdir(os.path.join(CWD, 'payloads')):
        if not files.endswith('PUT PAYLOADS HERE'):
            payloads.append(files)
    if not payloads:
        print('>> No payloads found')
    else:
        choice = payload_menu(payloads)
        if choice != 0:
            path = os.path.join(CWD, 'payloads', payloads[choice - 1])
            with open(path, 'rb') as buf:
                print('>> Sending {}...'.format(payloads[choice - 1]))
                content = buf.read()
            send_payload(ipaddr, 9020, content)
        else:
            print('>> No payload sent')

def payload_menu(payloads):
    i = 1
    choice = -1
    print('{} Payloads {}'.format('-' * 4, '-' * 46))
    print('0. Don\'t send a payload')
    for payload in payloads:
        print('{}. {}'.format(i, payload))
        i += 1
    print('-' * 60)
    while choice < 0 or choice >= i:
        choice = input('Choose a payload to send: ')
        try:
            choice = int(choice)
        except (ValueError, NameError):
            choice = -1

    return choice

def send_payload(hostname, port, content):
    """Netcat implementation"""
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    timeout = time.time() + 60
    while True:
        result = soc.connect_ex((hostname, port))
        if result == 0:
            print('>> Connected to PS4')
            timed_out = False
            break
        if time.time() >= timeout:
            print('>> Netcat service timed out')
            timed_out = True
            break
    if not timed_out:
        soc.sendall(content)
        soc.shutdown(socket.SHUT_WR)
        while True:
            data = soc.recv(1024)
            if not data:
                break
        print('>> Payload Sent!')
    soc.close()

def exploit_menu():
    i = 1
    choice = -1
    exploits = os.listdir(EXPLOIT_LOC)
    if not exploits:
        closer('ERROR: No exploits found')
    print('{} Exploits {}'.format('-' * 4, '-' * 46))
    for exploit in exploits:
        print('{}. {}'.format(i, exploit))
        i += 1
    print('-' * 60)
    while choice < 1 or choice >= i:
        choice = input('Choose an exploit to host: ')
        try:
            choice = int(choice)
        except (ValueError, NameError):
            choice = -1

    return exploits[choice - 1]

def silence_http(self, format, *args):
    """Just blackhole this method to prevent printing"""
    pass

def clear_line():
    """Clear last printed line from CLI"""
    sys.stdout.write('\x1b[1A')
    sys.stdout.write('\x1b[2K')

def getch():
    """MIT Licensed: https://github.com/joeyespo/py-getch"""
    import termios
    import tty

    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        return sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)

def closer(message):
    """Closing method"""
    print(message)
    if message != '>> Exiting...':
        print('Press any key to exit...', end='')
        sys.stdout.flush()
        if os.name == 'nt':
            from msvcrt import getch as w_getch
            w_getch()
        else:
            getch()
        print()
    sys.exit()

def main():
    """The main logic"""
    global DEBUG
    global EXPLOIT_LOC

    if not check_root():
        closer('ERROR: This must be run by root as it requires port 53 & 80')

    parser = argparse.ArgumentParser(description='PS4 Exploit Host')
    parser.add_argument('--exploit', dest='e_type', action='store',
                        default='', required=False,
                        help='Select which exploit to host')
    parser.add_argument('--debug', action='store_true',
                        required=False, help='Print debug statements')
    args = parser.parse_args()

    try:
        if args.debug:
            DEBUG = True
        else:
            DEBUG = False
            MyHandler.log_message = silence_http

        check_update_pups()

        if not args.e_type:
            args.e_type = exploit_menu()

        if os.path.isdir(os.path.join(EXPLOIT_LOC, args.e_type)) and args.e_type:
            EXPLOIT_LOC = os.path.join(EXPLOIT_LOC, args.e_type)
        else:
            closer('ERROR: Could not find exploit specified')

        lan = get_lan()

        if write_conf(lan):
            print('>> Your DNS IP is {}'.format(lan))
        else:
            closer('ERROR: Unable to write {}'.format(DNS_LOC))

        start_servers()

        while True:
            pass
    except KeyboardInterrupt:
        closer('>> Exiting...')

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>from __future__ import unicode_literals

import unittest
from six import StringIO

import pyaavso
from pyaavso.formats.visual import VisualFormatWriter, VisualFormatReader, \
    FormatException

class VisualFormatWriterTestCase(unittest.TestCase):
    """
    Tests for VisualFormatWriter class.
    """
    def setUp(self):
        self.fp = StringIO()

    def tearDown(self):
        self.fp.close()

    def test_header_type(self):
        """
        Check that TYPE parameter is always Visual.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ')
        contents = self.fp.getvalue()
        self.assertIn("#TYPE=Visual", contents)

    def test_header_obscode(self):
        """
        Check that observer code is written into file.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ')
        contents = self.fp.getvalue()
        self.assertIn("#OBSCODE=XYZ", contents)

    def test_header_software(self):
        """
        Check that the SOFTWARE parameter is correct.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ')
        contents = self.fp.getvalue()
        self.assertIn("#SOFTWARE=pyaavso %s" % pyaavso.get_version(), contents)

    def test_header_date(self):
        """
        Check that the DATE parameter represents date format used.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ', date_format='jd')
        contents = self.fp.getvalue()
        self.assertIn("#DATE=JD", contents)

    def test_header_obstype(self):
        """
        Check that OBSTYPE parameter is correctly set.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ', obstype='Visual')
        contents = self.fp.getvalue()
        self.assertIn("#OBSTYPE=Visual", contents)

    def test_header_obstype_ptg(self):
        """
        Check that OBSTYPE can be set to PTG (Photographic).
        """
        writer = VisualFormatWriter(self.fp, 'XYZ', obstype='PTG')
        contents = self.fp.getvalue()
        self.assertIn("#OBSTYPE=PTG", contents)

    def test_write_raw_data(self):
        """
        Check that writerow() can accept raw data record.
        """
        data = [
            'SS CYG', '2450702.1234', '<11.1', 'na', '110', '113', '070613',
            'This is a test',
        ]
        writer = VisualFormatWriter(self.fp, 'XYZ')
        writer.writerow(data)
        lines = self.fp.getvalue().splitlines()
        self.assertEqual(
            lines[5],
            "SS CYG,2450702.1234,<11.1,na,110,113,070613,This is a test"
        )

    def test_write_dict(self):
        """
        Check that dictionary of observation data can be written to file.
        """
        data = {
            'name': 'SS CYG',
            'date': '2450702.1234',
            'magnitude': '<11.1',
            'comment_code': 'na',
            'comp1': '110',
            'comp2': '113',
            'chart': '070613',
            'notes': 'This is a test',
        }
        writer = VisualFormatWriter(self.fp, 'XYZ')
        writer.writerow(data)
        lines = self.fp.getvalue().splitlines()
        self.assertEqual(
            lines[5],
            "SS CYG,2450702.1234,<11.1,na,110,113,070613,This is a test"
        )

class VisualFormatReaderTestCase(unittest.TestCase):
    """
    Tests for VisualFormatReader class.
    """
    def setUp(self):
        self.lines = [
            "#TYPE=VISUAL",
            "#OBSCODE=XYZ",
            "#SOFTWARE=Notepad",
            "#DELIM=,",
            "#DATE=JD",
            "#OBSTYPE=Visual",
            "SS CYG,2450702.1234,<11.1,na,110,113,070613,This is a test",
        ]
        self.fp = StringIO("\n".join(self.lines))

    def tearDown(self):
        self.fp.close()

    def test_observer_code(self):
        reader = VisualFormatReader(self.fp)
        self.assertEqual(reader.observer_code, 'XYZ')

    def test_missing_observer_code(self):
        fp = StringIO("\n".join(line for line in self.lines if 'OBSCODE' not in line))
        with self.assertRaises(FormatException):
            reader = VisualFormatReader(fp)

    def test_date_format(self):
        reader = VisualFormatReader(self.fp)
        self.assertEqual(reader.date_format, 'JD')

    def test_missing_date_format(self):
        fp = StringIO("\n".join(line for line in self.lines if 'DATE' not in line))
        with self.assertRaises(FormatException):
            reader = VisualFormatReader(fp)
<commit_msg>Refactored reader tests for missing headers.<commit_after>from __future__ import unicode_literals

import unittest
from six import StringIO

import pyaavso
from pyaavso.formats.visual import VisualFormatWriter, VisualFormatReader, \
    FormatException

class VisualFormatWriterTestCase(unittest.TestCase):
    """
    Tests for VisualFormatWriter class.
    """
    def setUp(self):
        self.fp = StringIO()

    def tearDown(self):
        self.fp.close()

    def test_header_type(self):
        """
        Check that TYPE parameter is always Visual.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ')
        contents = self.fp.getvalue()
        self.assertIn("#TYPE=Visual", contents)

    def test_header_obscode(self):
        """
        Check that observer code is written into file.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ')
        contents = self.fp.getvalue()
        self.assertIn("#OBSCODE=XYZ", contents)

    def test_header_software(self):
        """
        Check that the SOFTWARE parameter is correct.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ')
        contents = self.fp.getvalue()
        self.assertIn("#SOFTWARE=pyaavso %s" % pyaavso.get_version(), contents)

    def test_header_date(self):
        """
        Check that the DATE parameter represents date format used.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ', date_format='jd')
        contents = self.fp.getvalue()
        self.assertIn("#DATE=JD", contents)

    def test_header_obstype(self):
        """
        Check that OBSTYPE parameter is correctly set.
        """
        writer = VisualFormatWriter(self.fp, 'XYZ', obstype='Visual')
        contents = self.fp.getvalue()
        self.assertIn("#OBSTYPE=Visual", contents)

    def test_header_obstype_ptg(self):
        """
        Check that OBSTYPE can be set to PTG (Photographic).
        """
        writer = VisualFormatWriter(self.fp, 'XYZ', obstype='PTG')
        contents = self.fp.getvalue()
        self.assertIn("#OBSTYPE=PTG", contents)

    def test_write_raw_data(self):
        """
        Check that writerow() can accept raw data record.
        """
        data = [
            'SS CYG', '2450702.1234', '<11.1', 'na', '110', '113', '070613',
            'This is a test',
        ]
        writer = VisualFormatWriter(self.fp, 'XYZ')
        writer.writerow(data)
        lines = self.fp.getvalue().splitlines()
        self.assertEqual(
            lines[5],
            "SS CYG,2450702.1234,<11.1,na,110,113,070613,This is a test"
        )

    def test_write_dict(self):
        """
        Check that dictionary of observation data can be written to file.
        """
        data = {
            'name': 'SS CYG',
            'date': '2450702.1234',
            'magnitude': '<11.1',
            'comment_code': 'na',
            'comp1': '110',
            'comp2': '113',
            'chart': '070613',
            'notes': 'This is a test',
        }
        writer = VisualFormatWriter(self.fp, 'XYZ')
        writer.writerow(data)
        lines = self.fp.getvalue().splitlines()
        self.assertEqual(
            lines[5],
            "SS CYG,2450702.1234,<11.1,na,110,113,070613,This is a test"
        )

class VisualFormatReaderTestCase(unittest.TestCase):
    """
    Tests for VisualFormatReader class.
    """
    def setUp(self):
        self.lines = [
            "#TYPE=VISUAL",
            "#OBSCODE=XYZ",
            "#SOFTWARE=Notepad",
            "#DELIM=,",
            "#DATE=JD",
            "#OBSTYPE=Visual",
            "SS CYG,2450702.1234,<11.1,na,110,113,070613,This is a test",
        ]
        self.fp = StringIO("\n".join(self.lines))

    def tearDown(self):
        self.fp.close()

    def _drop_header(self, header_name):
        self.fp = StringIO("\n".join(
            line for line in self.lines if header_name not in line
        ))

    def test_observer_code(self):
        reader = VisualFormatReader(self.fp)
        self.assertEqual(reader.observer_code, 'XYZ')

    def test_missing_observer_code(self):
        self._drop_header('OBSCODE')
        with self.assertRaises(FormatException):
            reader = VisualFormatReader(self.fp)

    def test_date_format(self):
        reader = VisualFormatReader(self.fp)
        self.assertEqual(reader.date_format, 'JD')

    def test_missing_date_format(self):
        self._drop_header('DATE')
        with self.assertRaises(FormatException):
            reader = VisualFormatReader(self.fp)
<|endoftext|>


<commit_before>import unittest

class genomeTest(unittest.TestCase):

	def testFitness(self):
		self.Fail("Not implemented")

	def testgetWeights(self):
		self.Fail("Not implemented")

class genAlgTest(unittest.TestCase):

	def testpopSize(self):
		self.Fail("Not implemented")

	def testlenChromosome(self):
		self.Fail("Not implemented")

	def testtotalFit(self):
		self.Fail("Not implemented")

	def testbestFit(self):
		self.Fail("Not implemented")

	def testaveFit(self):
		self.Fail("Not implemented")

	def testworstFit(self):
		self.Fail("Not implemented")

	def testbestGenome(self):
		self.Fail("Not implemented")

	def testmutationRate(self):
		self.Fail("Not implemented")

	def testcrossRate(self):
		self.Fail("Not implemented")

	def testgeneration(self):
		self.Fail("Not implemented")

	def testcrossover(self,ma,fa,bab1,bab2):
		self.Fail("Not implemented")

	def testmutate(self,chromosome):
		self.Fail("Not implemented")

	def testgetRandomchromo(self):
		self.Fail("Not implemented")

	def testgetBestrandom(self,best,numclones,pop):
		self.Fail("Not implemented")

	def testaverage(self):
		self.Fail("Not implemented")

	def testreset(self):
		self.Fail("Not implemented")

	def testgen(self,popsize,mut,cross,numweights):
		self.Fail("Not implemented")

	def testEpoch(self):
		self.Fail("Not implemented")

	def testgetChromosomes(self):
		self.Fail("Not implemented")

	def testgetAveragefitness(self):
		self.Fail("Not implemented")

	def testgetBestFitness(self):
		self.Fail("Not implemented")<commit_msg>completed test for genome<commit_after>from geneticAlg import *
import unittest

class genomeTest(unittest.TestCase):

	def testFitness(self):
		genome = genome()

		self.assertEqual(genome.fitness,0.0)

	def testgetWeights(self):
		genome = genome()

		self.assertEqual(len(genome.weights),0)

class genAlgTest(unittest.TestCase):

	def testpopSize(self):
		self.Fail("Not implemented")

	def testlenChromosome(self):
		self.Fail("Not implemented")

	def testtotalFit(self):
		self.Fail("Not implemented")

	def testbestFit(self):
		self.Fail("Not implemented")

	def testaveFit(self):
		self.Fail("Not implemented")

	def testworstFit(self):
		self.Fail("Not implemented")

	def testbestGenome(self):
		self.Fail("Not implemented")

	def testmutationRate(self):
		self.Fail("Not implemented")

	def testcrossRate(self):
		self.Fail("Not implemented")

	def testgeneration(self):
		self.Fail("Not implemented")

	def testcrossover(self,ma,fa,bab1,bab2):
		self.Fail("Not implemented")

	def testmutate(self,chromosome):
		self.Fail("Not implemented")

	def testgetRandomchromo(self):
		self.Fail("Not implemented")

	def testgetBestrandom(self,best,numclones,pop):
		self.Fail("Not implemented")

	def testaverage(self):
		self.Fail("Not implemented")

	def testreset(self):
		self.Fail("Not implemented")

	def testgen(self,popsize,mut,cross,numweights):
		self.Fail("Not implemented")

	def testEpoch(self):
		self.Fail("Not implemented")

	def testgetChromosomes(self):
		self.Fail("Not implemented")

	def testgetAveragefitness(self):
		self.Fail("Not implemented")

	def testgetBestFitness(self):
		self.Fail("Not implemented")<|endoftext|>