예제 #1
0
파일: shellcode.py 프로젝트: BwRy/peda
    def search(self, keyword):
        if keyword is None:
            return None
        try:
            msg("Connecting to shell-storm.org...")
            s = http.client.HTTPConnection("shell-storm.org")
            s.request("GET", "/api/?s="+str(keyword))
            res = s.getresponse()
            data_l = res.read().split('\n')
        except:
            error_msg("Cannot connect to shell-storm.org")
            return None

        data_dl = []
        for data in data_l:
            try:
                desc = data.split("::::")
                dico = {
                         'ScAuthor': desc[0],
                         'ScArch': desc[1],
                         'ScTitle': desc[2],
                         'ScId': desc[3],
                         'ScUrl': desc[4]
                       }
                data_dl.append(dico)
            except:
                pass

        return data_dl
예제 #2
0
파일: shellcode.py 프로젝트: 453483289/peda
 def zsc(self,os,job,encode):
     try:
         msg('Connection to OWASP ZSC API api.z3r0d4y.com')
         params = urlencode({
                 'api_name': 'zsc', 
                 'os': os,
                 'job': job,
                 'encode': encode})
         shellcode = urlopen("http://api.z3r0d4y.com/index.py?%s\n"%(str(params))).read()
         if pyversion is 3:
             shellcode = str(shellcode,encoding='ascii')
         return '\n"'+shellcode.replace('\n','')+'"\n'
     except:
         error_msg("Error while connecting to api.z3r0d4y.com ...")
         return None
예제 #3
0
 def zsc(self, os, job, encode):
     try:
         msg('Connection to OWASP ZSC API api.z3r0d4y.com')
         params = urlencode({
             'api_name': 'zsc',
             'os': os,
             'job': job,
             'encode': encode
         })
         shellcode = urlopen("http://api.z3r0d4y.com/index.py?%s\n" %
                             (str(params))).read()
         if pyversion is 3:
             shellcode = str(shellcode, encoding='ascii')
         return '\n"' + shellcode.replace('\n', '') + '"\n'
     except:
         error_msg("Error while connecting to api.z3r0d4y.com ...")
         return None
    def load_pair_edges_file(self):
        try:
            with open(self.pair_edge_file, "r") as f:
                for line in f:
                    parent_bbid = line.split(':')[0]
                    edges = line.split(':')[1].split()
                    if len(edges) < 2:
                        continue
                    for i in range(len(edges)):
                        #note: there could be hash collision, causing duplicated edge ids in different code blocks
                        self.edge_pair_map[edges[i]] = set(edges)
                        self.edge_to_parentBB[edges[i]] = parent_bbid

        except:
            utils.error_msg("can't load pair_edge_file: %s" %
                            self.pair_edge_file)
            sys.exit(-1)
예제 #5
0
def get_custom_break_time():
    '''Returns a custom time for break.'''
    print('Break Time:'\
        + '\n 1) 5 minutes'\
        + '\n 2) 10 minutes'\
        + '\n 3) N minutes')

    try:
        opt = int(input('>>= '))
        if opt == 1:
            return 5
        elif opt == 2:
            return 10
        return int(input('N minutes =<< '))
    except ValueError as err:
        error_msg('Please, insert an integer number!', err)
        return get_custom_break_time()
예제 #6
0
def get_custom_time():
    '''Returns a custom time for pomodoro.'''
    print('Pomodoro Time:'\
        + '\n 1) 25 minutes (recommended)'\
        + '\n 2) 30 minutes'\
        + '\n 3) N minutes')

    try:
        opt = int(input('>>= '))
        if opt == 1:
            return 25
        elif opt == 2:
            return 30
        return int(input('N minutes =<< '))
    except ValueError as err:
        error_msg('Please, insert an integer number!', err)
        return get_custom_time()
 def load_bb2dom_file(self):
     try:
         self.bb_dom_map = dict()
         with open(self.bb_to_dom_file) as b2d_file:
             reader = csv.DictReader(b2d_file, delimiter=',')
             for row in reader:
                 if self.bb_dom_map.has_key(row['BBID']):
                     if self.bb_dom_map[row['BBID']] < row['DOMNUM']:
                         #take the higher one, as dma might have collision
                         self.bb_dom_map[row['BBID']] = row['DOMNUM']
                 else:
                     self.bb_dom_map[row['BBID']] = row['DOMNUM']
         oracle_info('Loading BBL to Domination Map %s' %
                     self.bb_to_dom_file)
     except Exception:
         utils.error_msg("can't load bb_dom_map: %s" % self.bb_to_dom_file)
         sys.exit(-1)
예제 #8
0
파일: explorer.py 프로젝트: TotalKnob/muse
def get_explorer_factory(config, proj_dir):
    """parse config to determine which explorer to initialize"""
    cfg = ConfigParser.ConfigParser()
    cfg.read(config)
    sections = cfg.sections()

    for _s in sections:
        if "klee" in _s:
            return KleeExplorers(config, proj_dir)
        if "qsym" in _s:
            return QsymExplorer(config, proj_dir)
        if "s2e" in _s:
            pass
        if "angr" in _s:
            pass

    error_msg("Can't find explorer options in config")
    sys.exit(-1)
예제 #9
0
def get_sound():
    '''Returns a sound for alarm.'''
    print('Select a Sound:'\
        + '\n 1) submarine.mp3'\
        + '\n 2) foghorn.mp3'\
        + '\n 3) default')

    try:
        opt = int(input('>>= '))
    except ValueError as err:
        error_msg('Please, insert an integer number!', err)
        return get_sound()

    if opt == 1:
        return 'submarine.mp3'
    elif opt == 2:
        return 'foghorn.mp3'

    return 'submarine.mp3'
예제 #10
0
 def get_oracle_config(self):
     config = ConfigParser.ConfigParser()
     config.read(self.config)
     self.replay_prog_cmd = config.get("auxiliary info",
                                       "replay_prog_cmd").replace(
                                           "@target", self.target_dir)
     try:
         self.bb_to_dom_file = config.get("auxiliary info",
                                          "bbl_dom_map").replace(
                                              "@target", self.target_dir)
         self.pair_edge_file = config.get("auxiliary info",
                                          "pair_edge_file").replace(
                                              "@target", self.target_dir)
     except Exception:
         utils.error_msg("bbl_dom_map|pair_edge files not found in %s" %
                         self.target_dir)
         sys.exit(-1)
     # self.bug_edge_file = config.get("auxiliary info", "bug_edge_file").replace("@target", self.target_dir)
     self.bug_edge_file = None  # don't care
예제 #11
0
파일: login.py 프로젝트: edopikin/snbank
def login():
    print("*Staff Login*")
    # read staff in staff.txt file, returns a dict {username: (username, password)
    staff = read_file('staff.txt')
    isLoggingIn = True

    while isLoggingIn:
        # read user input for username and password
        uname_input = input("Enter Username >_ ")
        pwd_input = input("Enter Password >_ ")

        try:
            # get user input from the staff dict
            staff_details = staff[uname_input]
            # if user in staff dict
            if staff:
                # get the username and password from returned tuple (username, password)
                username, password = staff_details
                # if the username and password match userinput
                if username == uname_input and password == pwd_input:
                    # end loop
                    isLoggingIn = False
                    # call the save_user_session function pass username
                    save_user_session(username)
                    # return username and end function
                    return username
                else:
                    # if user input is incorrect, throw an error
                    raise KeyError()
        # if username not in dict, handle error
        except KeyError:
            # print error message
            error_msg("Wrong User detail, Try again")
            # get next action from user
            response = input("Enter any key to try again or Q to cancel >_ ")
            # if user quits
            if response.upper() == 'Q':
                # end loop
                isLoggingIn = False
    # return false if function doesn't end before here
    return False
 def get_oracle_config(self):
     config = ConfigParser.ConfigParser()
     config.read(self.config)
     self.replay_prog_cmd = config.get("moriarty", "target_bin").replace(
         "@target", self.target_dir)
     try:
         self.bb_to_dom_file = config.get("auxiliary info",
                                          "bug_reach_map").replace(
                                              "@target", self.target_dir)
         self.pair_edge_file = config.get("auxiliary info",
                                          "pair_edge_file").replace(
                                              "@target", self.target_dir)
     except Exception:
         utils.error_msg("bug_reach_map|pair_edge files not found in %s" %
                         self.target_dir)
         sys.exit(-1)
     try:
         self.only_count_covered_edge = True if config.get(
             "edge oracle", "only_count_covered_edge") == "True" else False
     except Exception:
         self.only_count_covered_edge = True
예제 #13
0
파일: shellcode.py 프로젝트: page2me/peda-2
    def search(self, keyword):
        if keyword is None:
            return None
        try:
            msg("Connecting to shell-storm.org...")
            s = six.moves.http_client.HTTPConnection("shell-storm.org")

            s.request("GET", "/api/?s=" + str(keyword))
            res = s.getresponse()
            read_result = res.read().decode('utf-8')
            data_l = [x for x in read_result.split('\n')
                      if x]  # remove empty results
        except Exception as e:
            if config.Option.get("debug") == "on":
                msg("Exception: %s" % e)
                traceback.print_exc()
            error_msg("Cannot connect to shell-storm.org")
            return None

        data_dl = []
        for data in data_l:
            try:
                desc = data.split("::::")
                dico = {
                    'ScAuthor': desc[0],
                    'ScArch': desc[1],
                    'ScTitle': desc[2],
                    'ScId': desc[3],
                    'ScUrl': desc[4]
                }
                data_dl.append(dico)
            except Exception as e:
                if config.Option.get("debug") == "on":
                    msg("Exception: %s" % e)
                    traceback.print_exc()

        return data_dl
예제 #14
0
 def serialize_data_records(self,
                            data_records,
                            filename,
                            counter=0,
                            window=None):
     print "saving data_store to: ", filename
     try:
         with open(filename, "a") as outf:
             writer = csv.writer(outf, delimiter=',')
             num = 0
             for data in data_records:
                 tmp = dict()
                 # print "SSS sequence number: ", counter
                 writer.writerow([window, counter] + data[0] + [data[1]])
                 print "write record: "
                 print tmp
                 counter += 1
                 num += 1
         return num
     except Exception:
         print data_records
         utils.error_msg(
             "can not serialize data store {0}".format(filename))
         return 0
예제 #15
0
    def display(self, shellcodeId):
        if shellcodeId is None:
            return None

        try:
            msg("Connecting to shell-storm.org...")
            s = six.moves.http_client.HTTPConnection("shell-storm.org")
        except:
            error_msg("Cannot connect to shell-storm.org")
            return None

        try:
            s.request("GET", "/shellcode/files/shellcode-"+str(shellcodeId)+".php")
            res = s.getresponse()
            data = res.read().decode('utf-8').split("<pre>")[1].split("<body>")[0]
        except:
            error_msg("Failed to download shellcode from shell-storm.org")
            return None

        data = data.replace("&quot;", "\"")
        data = data.replace("&amp;", "&")
        data = data.replace("&lt;", "<")
        data = data.replace("&gt;", ">")
        return data
예제 #16
0
파일: shellcode.py 프로젝트: 453483289/peda
    def display(self, shellcodeId):
        if shellcodeId is None:
            return None

        try:
            msg("Connecting to shell-storm.org...")
            s = six.moves.http_client.HTTPConnection("shell-storm.org")
        except:
            error_msg("Cannot connect to shell-storm.org")
            return None

        try:
            s.request("GET", "/shellcode/files/shellcode-"+str(shellcodeId)+".php")
            res = s.getresponse()
            data = res.read().split("<pre>")[1].split("<body>")[0]
        except:
            error_msg("Failed to download shellcode from shell-storm.org")
            return None

        data = data.replace("&quot;", "\"")
        data = data.replace("&amp;", "&")
        data = data.replace("&lt;", "<")
        data = data.replace("&gt;", ">")
        return data
예제 #17
0
def do_create_site(options):
    if not utils.is_true('create_test_folder', options['default']):
        return False

    if not os.path.isdir(options['default']['site_path']):
        utils.error_msg('Path to Folder Site Not Found')
        return False

    site_folder_path = options['default']['site_path'] + options['default'][
        'site_name']

    if os.path.isdir(site_folder_path):
        utils.error_msg('Site Folder is Exist')
        return False

    os.makedirs(site_folder_path)

    template_path = options['system']['template_page_path']
    content = utils.get_config_content(template_path)

    site_folder_path = site_folder_path + "/index.html"
    utils.create_file(site_folder_path, content)

    utils.success_msg("Site Folder was Created.")
예제 #18
0
def operations():
    # invoke login function to log user in and get username if user
    staff = login()
    running = True
    # if the login is successful
    if staff:
        options = "\n*Menu*\n1. Create New Bank Account\n2. Check Bank Account Details\n3. Logout\n"
        while running:
            print(options)
            try:
                # get user action
                user_input = int(input("Select option >_ "))
                # if input is within range and correct
                if user_input in range(1, 4):
                    # first option
                    if user_input == 1:
                        try:
                            # get details from staff
                            acc_name = input("Enter Account Name >_ ")
                            open_bal = float(
                                input("Enter Opening Balance >_ ")
                                or 0)  # if no input, default to 0
                            acc_type = input("Enter Account Type >_ ")
                            acc_email = input("Enter Email Address >_ ")
                            # check if fields are not empty
                            if (len(acc_name) and len(acc_type)
                                    and len(acc_email)):
                                # generate random number for accout number
                                acc_no = randint(0000000000, 9999999999)
                                # concatnate values to a comma separeated string
                                info = f"{acc_no},{acc_name},{acc_type},{acc_email},{open_bal}"
                                # write the string to the customer.txt file
                                write_data("customer.txt", info)
                                # print the user's account number
                                print(f"\n**New Account Number: {acc_no}***")
                            # if a required field is not entered
                            else:
                                # print and error message
                                error_msg("All fields are required")
                        # handle conversion error for float(open balance)
                        except ValueError as e:
                            # print the error message
                            error_msg(e)
                    # second option
                    if user_input == 2:
                        try:
                            # get account number from user
                            acc_no = input("Enter Account Number >_ ")
                            # read the customers file, returns a dict {'account_number': (acc_no, acc_name, acc_type, acc_email, open_bal)}
                            customers = read_file("customer.txt")
                            # unpack tuple for the customer if customer in dict
                            acc_no, acc_name, acc_type, acc_email, open_bal = customers[
                                acc_no]
                            # print information
                            print("\n**Account Details**")
                            print(f"Account Number: {acc_no}")
                            print(f"Account Name: {acc_name}")
                            print(f"Account Type: {acc_type}")
                            print(f"Account Email: {acc_email}")
                            print(f"Opening Balance: N {open_bal}")
                        # handle error, if account number not in dict
                        except KeyError:
                            # print error message
                            error_msg("Invalid/Incorrect Account Number")
                    # option 3
                    if user_input == 3:
                        # clear the current staff session
                        remove_user_session(staff)
                        # end loop
                        running = False
                else:
                    # print error message if the user inputs a number less than 1 or greater than 3
                    error_msg("Invalid Option, option must be a number 1 or 3")
            except ValueError:
                # print error message if the user input is not a number
                error_msg("Option must be a number")
예제 #19
0
    arguments = get_prepared_arguments(arguments)
    config = get_config()

    options = get_options(arguments, config)

    do_create_httpd(options)
    do_create_nginx(options)
    do_create_hosts(options)
    do_create_site(options)


def create_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument("site_name")
    parser.add_argument('-i', '--info')
    parser.add_argument('-a', '--add_hosts')
    return parser


def __init():
    parser = create_parser()
    arguments = parser.parse_args(sys.argv[1:])
    do_create_virtual_host(arguments)


if __name__ == "__main__":
    try:
        __init()
    except Exception as e:
        utils.error_msg(str(e))
예제 #20
0
    def get_oracle_config(self):
        config = ConfigParser.ConfigParser()
        config.read(self.config)
        self.replay_prog_cmd = config.get("auxiliary info",
                                          "replay_prog_cmd").replace(
                                              "@target", self.target_dir)
        try:
            self.bb_to_bug_file = config.get("auxiliary info",
                                             "bbl_bug_map").replace(
                                                 "@target", self.target_dir)
            self.bb_to_cov_file = config.get("auxiliary info",
                                             "bbl_cov_map").replace(
                                                 "@target", self.target_dir)
            self.pair_edge_file = config.get("auxiliary info",
                                             "pair_edge_file").replace(
                                                 "@target", self.target_dir)
        except Exception:
            utils.error_msg(
                "bbl_cov_map|bbl_bug_map|pair_edge files not found in %s" %
                self.target_dir)
            # sys.exit(-1)
        try:
            self.count_all_edges = False if config.get(
                "edge oracle", "only_count_covered_edge") == "True" else True
        except Exception:
            self.count_all_edges = False
        try:
            self.data_store_file = config.get("auxiliary info",
                                              "data_store_file").replace(
                                                  "@target", self.target_dir)
            oracle_info("Save meuzz data to {0}".format(self.data_store_file))
        except Exception:
            self.data_store_file = None

        try:
            self.batch_run_input_num = int(
                config.get("moriarty", "batch_run_input_num"))
        except Exception:
            self.batch_run_input_num = 1

        # NOTE: meuzz_window will dynamically adjust to the size of the work queue
        self.meuzz_window = 1

        try:
            self.save_model = config.get("edge oracle", "meuzz_model_file")\
                                    .replace("@target", self.target_dir)
            oracle_info("Persist meuzz model from/to {0}".format(
                self.save_model))
        except Exception:
            self.save_model = None

        try:
            self.init_dataset = config.get("edge oracle", "meuzz_init_data")\
                                .replace("@target", self.target_dir)
            oracle_info("initalize model with dataset {0}".format(
                self.init_dataset))
        except Exception:
            self.init_dataset = None

        try:
            self.meuzz_variant = config.get("edge oracle", "meuzz_variant")
        except Exception:
            # default to online learning
            self.meuzz_variant = "online_learning"

        try:
            self.use_ramfs = True if config.get(
                "edge oracle", "meuzz_use_ramfs").lower() == 'true' else False
        except Exception:
            # default using /tmp folder
            self.use_ramfs = False