Beispiel #1
0
def parseConfig():
	"""
		Reads all configuration files
	"""
	if args.reconfigure:
		if not os.path.isfile(CONFPATH):
			avalon.error('Configuration file not found! Unable to reconfigure')
			if avalon.ask('Launch Set-up wizard?', True):
				avalon.info('Starting Re-Configuration')
				setupWizard()
		else:
			avalon.info('Starting Re-Configuration')
			setupWizard()
	if not os.path.isfile(CONFPATH):
		avalon.warning('Configuration File Not Found!')
		if avalon.ask('Start Set-up Wizard?', True):
			setupWizard()
		else:
			avalon.error('No configuration file found!')
			avalon.error('Please initialize the configuration file!')
			exit(0)
	else:
		config = configparser.ConfigParser()
		config.read(CONFPATH)
		config.sections()
		servers = config['SERVERS']
		return servers
Beispiel #2
0
    def _get_inputs(self):
        # welcome and banner
        server_types = [
            "Web Server",
            "Mail Server",
            "Minecraft PC Server",
        ]

        print(avalon.FG.G + avalon.FM.BD + "Welcome to DefenseMatrix!")
        print("This is the setup wizard")
        print("You will be asked to answer basic questions about your server" + avalon.FM.RST)

        for index in range(len(server_types)):
            print(str(index) + ". " + server_types[index])

        while True:
            server_select = avalon.gets("Select your type of server: ")
            try:
                server_type = server_types[int(server_select)]
                break
            except ValueError:
                avalon.error("Invalid Input!")

        if server_type == "Web Server":
            open_ports = [80, 443]
        elif server_type == "Mail Server":
            open_ports = [25, 110, 587]
        elif server_type == "Minecraft PC Server":
            open_ports = [25565]

        print(open_ports)
        avalon.info("DefenseMatrix takes care of your firewall settings for you.")
        avalon.warning("This following step is going to reset your iptables configuration")
        if not avalon.ask("Is is okay to proceed?", True):
            exit(0)

        os.system("iptables -F")
        os.system("iptables -X")
        os.system("ufw --force reset")

        ssh_port = 22
        avalon.info("It is " + avalon.FM.BD + "HIGHLY recommended to change your default port for ssh")
        if avalon.ask("Do you want to change it now?", True):
            while True:
                try:
                    ssh_port = avalon.gets("Which port do you want to change to?: ")
                    if len(ssh_port) == 0:
                        avalon.error("Please enter a valid port number between 1-65565!")
                        pass
                    else:
                        ssh_port = int(ssh_port)
                        break
                except ValueError:
                    avalon.error("Please enter a valid port number between 1-65565!")
        else:
            avalon.info("You can always change it using the command \"dm --ssh-port [port]\"")

        return open_ports, ssh_port
Beispiel #3
0
    def _get_inputs(self):
        # welcome and banner
        print(avalon.FG.G + avalon.FM.BD + "Welcome to DefenseMatrix!")
        print("This is the setup wizard")
        print("You will be asked to answer basic questions about your server" +
              avalon.FM.RST)

        for index, server_type in enumerate(st.server_types):
            print('%d.  %s' % (index, server_type))

        while True:
            server_select = avalon.gets("Select your type of server: ")
            try:
                server_type = list(st.server_types.keys())[int(server_select)]
                break
            except TypeError:
                avalon.error("Invalid Input!")

        for server in st.server_types.keys():
            open_ports = st.server_types[server]

        avalon.info(
            "DefenseMatrix takes care of your firewall settings for you.")
        avalon.warning(
            "This following step is going to reset your iptables configuration"
        )
        if not avalon.ask("Is is okay to proceed?", True):
            exit(0)

        os.system("iptables -F")
        os.system("iptables -X")

        ssh_port = 22
        avalon.info("It is " + avalon.FM.BD +
                    "HIGHLY recommended to change your default port for ssh")
        if avalon.ask("Do you want to change it now?", True):
            while True:
                try:
                    ssh_port = int(
                        avalon.gets("Which port do you want to change to?"))
                    if int(ssh_port) <= 0:
                        raise TypeError
                    else:
                        break
                except TypeError:
                    avalon.error(
                        "Please enter a valid port number between 1-65565!")
        else:
            avalon.info(
                "You can always change it using the command \"dm --ssh-port [port]\""
            )

        return open_ports, ssh_port
Beispiel #4
0
 def sysInstallPackage(self, package):
     if avalon.ask('Install ' + package + '?', True):
         if os.path.isfile('/usr/bin/apt'):
             os.system('apt update && apt install ' + package +
                       ' -y')  # install arptables with apt
             return True
         elif os.path.isfile('/usr/bin/yum'):
             os.system('yum install ' + package +
                       ' -y')  # install arptables with yum
             return True
         elif os.path.isfile('/usr/bin/pacman'):
             os.system('pacman -S ' + package +
                       ' --noconfirm')  # install arptables with pacman
             return True
         else:
             avalon.error(
                 'Sorry, we can\'t find a package manager that we currently support. Aborting..'
             )
             print('Currently Supported: apt, yum, pacman')
             print(
                 'Please come to SCUTUM\'s github page and comment if you know how to add support to another package manager'
             )
             return False
     else:
         return False
    def save_profile(self, profile_path):
        """ Save current profile to a json file
        """

        # Convert peer objects into dictionary format
        profile = {}
        profile['peers'] = {}
        for peer in pm.peers:
            profile['peers'][peer.address] = {}
            profile['peers'][peer.address]['address'] = peer.address
            profile['peers'][
                peer.address]['public_address'] = peer.public_address
            profile['peers'][peer.address]['listen_port'] = peer.listen_port
            profile['peers'][peer.address]['private_key'] = peer.private_key
            profile['peers'][peer.address]['keep_alive'] = peer.keep_alive

        if os.path.isfile(profile_path) or os.path.islink(profile_path):
            if not avalon.ask('File already exists. Overwrite?', True):
                avalon.warning('Aborted saving profile')
                return 1
        if os.path.isdir(profile_path):
            avalon.warning('Destination path is a directory')
            avalon.warning('Aborted saving profile')
            return 1

        avalon.dbgInfo('Writing profile to: {}'.format(profile_path))
        with open(profile_path, 'w') as wgc_config:
            json.dump(profile, wgc_config, indent=2)
            wgc_config.close()
Beispiel #6
0
 def install4WICD():
     """
     Write scutum scripts for WICD
     """
     print(avalon.FG.G + '[+] INFO: Installing for WICD' + avalon.FM.RST + '.....', end='')
     if not os.path.isdir('/etc/wicd/'):
         print(avalon.FG.G + avalon.FM.BD + 'ERROR' + avalon.FM.RST)
         avalon.warning('WICD folder not found! WICD does not appear to be installed!')
         if avalon.ask('Continue anyway?', False):
             os.system('mkdir /etc/wicd/')
             os.system('mkdir /etc/wicd/scripts/')
             os.system('mkdir /etc/wicd/scripts/postconnect/')
             os.system('mkdir /etc/wicd/scripts/postdisconnect/')
         else:
             avalon.warning('Aborting installation for WICD')
             return 0
     with open('/etc/wicd/scripts/postconnect/scutum_connect', 'w') as postconnect:
         postconnect.write('#!/bin/bash\n')
         postconnect.write('scutum')
         postconnect.close()
     with open('/etc/wicd/scripts/postdisconnect/scutum_disconnect', 'w') as postdisconnect:
         postdisconnect.write('#!/bin/bash\n')
         postdisconnect.write('scutum --reset')
         postdisconnect.close()
     os.system('chown root: /etc/wicd/scripts/postconnect/scutum_connect')
     os.system('chmod 755 /etc/wicd/scripts/postconnect/scutum_connect')
     os.system('chown root: /etc/wicd/scripts/postdisconnect/scutum_disconnect')
     os.system('chmod 755 /etc/wicd/scripts/postdisconnect/scutum_disconnect')
     print(avalon.FG.G + avalon.FM.BD + 'SUCCEED' + avalon.FM.RST)
def get_peers_settings():
    """ Get all peers' settings

    Keep enrolling peers until the user aborts.
    """
    while avalon.ask('Add new peer?', True):
        enroll_peer()
Beispiel #8
0
def setupWizard():
	"""
		Initialize a configuration file in "$HOME/.config/entro.conf"
		Saves all server Names, ID and addresses
	"""
	avalon.info('Set-up Wizard Started')
	config = configparser.ConfigParser()
	config['SERVERS'] = {}
	while True:
		while True:
			serverName = avalon.gets('Server Name: ')
			if serverName == '':
					avalon.error('Invalid Input!')
			else:
				break
		while True:
			serverAddr = avalon.gets('Server Address: ')
			if validIP(serverAddr) or validDomain(serverAddr):
				break
			else:
				avalon.error('Invalid Input! IP addresses or domains only!')
		config['SERVERS'][serverName] = serverAddr
		if avalon.ask('Add another server?'):
			pass
		else:
			break
	avalon.info('Set-up Completed!')
	avalon.info('Writing configuration file to ' + CONFPATH)
	with open(CONFPATH, 'w') as configfile:
		config.write(configfile)  # Writes configurations
	avalon.info('Writing succeeded!')
	avalon.info('Please relaunch application')
	exit(0)
Beispiel #9
0
    def check_avalon(self):
        """
        Check avalon version and update avalon_framework
        if necessary
        """
        avalon.info(avalon.FM.RST + 'Checking AVALON Framework Version...')
        if os.system('which pip3'):
            avalon.warning('pip3 not found, aborting version check')
            return
        avalon_version_check = subprocess.Popen(
            ["pip3", "freeze"], stdout=subprocess.PIPE).communicate()[0]
        pipOutput = avalon_version_check.decode().split('\n')
        for line in pipOutput:
            if 'avalon-framework' in line:
                localVersion = line.split('==')[-1]

        with urllib.request.urlopen(
                'https://raw.githubusercontent.com/K4YT3X/AVALON/master/__init__.py'
        ) as response:
            html = response.read().decode().split('\n')
            for line in html:
                if 'VERSION = ' in line:
                    serverVersion = line.split(' ')[-1].replace('\'', '')
                    break

        if serverVersion > localVersion:
            avalon.info('Here\'s a newer version of AVALON Framework: ' +
                        serverVersion)
            if avalon.ask('Update to the newest version?', True):
                os.system('pip3 install --upgrade avalon_framework')
            else:
                avalon.warning('Ignoring update')
        else:
            avalon.dbgInfo('Current version: ' + localVersion)
            avalon.info('AVALON Framework is already on the newest version')
Beispiel #10
0
    def check_version(self, VERSION):
        """
        Arguments:
            VERSION {string} -- version number

        Returns:
            string -- server version number
        """
        avalon.info(avalon.FM.RST + 'Checking SCUTUM Version...')
        with urllib.request.urlopen(
                'https://raw.githubusercontent.com/K4YT3X/SCUTUM/master/scutum.py'
        ) as response:
            html = response.read().decode().split('\n')
            for line in html:
                if 'VERSION = ' in line:
                    server_version = line.split(' ')[-1].replace('\'', '')
                    break
            avalon.subLevelTimeInfo('Server version: ' + server_version)
            if server_version > VERSION:
                avalon.info('Here\'s a newer version of SCUTUM!')
                if avalon.ask('Update to the newest version?'):
                    self.install()
                else:
                    avalon.warning('Ignoring update')
            else:
                avalon.info('SCUTUM is already on the newest version')
        return server_version
def enroll_peer():
    """ Enroll a new peer
    """

    # Get peer tunnel address
    while True:
        address = avalon.gets('Address (leave empty if client only): ')
        result = re.match('^(?:\d{1,3}\.){3}\d{1,3}/{1}(?:\d\d?)?$', address)
        if result is None:
            avalon.error('Invalid address entered')
            avalon.error('Please use CIDR notation (e.g. 10.0.0.0/8)')
            continue
        break

    # Get peer public IP address
    while True:
        public_address = avalon.gets(
            'Public address (leave empty if client only): ')
        result = re.match('^(?:\d{1,3}\.){3}\d{1,3}(?:/\d\d?)?$',
                          public_address)
        if result is None and public_address != '':  # field not required
            avalon.error('Invalid IP address entered')
            continue
        break

    # Get peer listening port
    listen_port = avalon.gets('Listen port (leave empty for client): ')

    # Get peer private key
    private_key = avalon.gets(
        'Private key (leave empty for auto generation): ')
    if private_key == '':
        private_key = wg.genkey()

    # Ask if this peer needs to be actively connected
    # if peer is behind NAT and needs to be accessed actively
    # PersistentKeepalive must be turned on (!= 0)
    keep_alive = avalon.ask('Keep alive?', False)
    """
    preshared_key = False
    if avalon.ask('Use a preshared key?', True):
        preshared_key = avalon.gets('Preshared Key (leave empty for auto generation): ')
        if preshared_key == '':
            preshared_key = wg.genpsk()
    peer = Peer(address, private_key, keep_alive, listen_port, preshared_key)
    """
    peer = Peer(address, public_address, listen_port, private_key, keep_alive)
    pm.peers.append(peer)
    print_peer_config(peer)
Beispiel #12
0
    def installNMScripts(self, interfaces):
        """
        Write scutum scripts for Network Manager
        """
        print(avalon.FG.G + '[+] INFO: Installing for NetworkManager' +
              avalon.FM.RST + '.....',
              end='')
        if not os.path.isdir('/etc/NetworkManager/dispatcher.d/'):
            print(avalon.FG.G + avalon.FM.BD + 'ERROR' + avalon.FM.RST)
            avalon.warning(
                'NetworkManager folders not found! NetworkManager does not appear to be installed!'
            )
            if avalon.ask('Continue anyway? (Create Directories)', False):
                os.system('mkdir /etc/NetworkManager/')
                os.system('mkdir /etc/NetworkManager/dispatcher.d/')
            else:
                avalon.warning('Aborting installation for NetworkManager')
                return False
        with open('/etc/NetworkManager/dispatcher.d/scutum', 'w') as nmScript:
            nmScript.write("#!/bin/bash\n")
            nmScript.write(" \n")
            nmScript.write("IF=$1\n")
            nmScript.write("STATUS=$2\n")
            nmScript.write(" \n")
            for iface in interfaces:
                nmScript.write("if [ \"$IF\" == \"" + iface + "\" ]\n")
                nmScript.write("then\n")
                nmScript.write("    case \"$2\" in\n")
                nmScript.write("        up)\n")
                nmScript.write("        scutum\n")
                nmScript.write("        ;;\n")
                nmScript.write("        down)\n")
                nmScript.write("        scutum --reset\n")
                nmScript.write("        ;;\n")
                nmScript.write("        *)\n")
                nmScript.write("        ;;\n")
                nmScript.write("    esac\n")
                nmScript.write("fi\n")
            nmScript.close()

        os.system('chown root: /etc/NetworkManager/dispatcher.d/scutum')
        os.system('chmod 755 /etc/NetworkManager/dispatcher.d/scutum')
        print(avalon.FG.G + avalon.FM.BD + 'SUCCEED' + avalon.FM.RST)
        return True
Beispiel #13
0
    def install_nm_scripts(self, interfaces):
        """
        Write scutum scripts for Network Manager
        """
        print(avalon.FG.G + '[+] INFO: Installing for NetworkManager' +
              avalon.FM.RST + '.....',
              end='')
        if not os.path.isdir('/etc/NetworkManager/dispatcher.d/'):
            print(avalon.FG.G + avalon.FM.BD + 'ERROR' + avalon.FM.RST)
            avalon.warning(
                'NetworkManager folders not found! NetworkManager does not appear to be installed!'
            )
            if avalon.ask('Continue anyway? (Create Directories)', False):
                os.system('mkdir /etc/NetworkManager/')
                os.system('mkdir /etc/NetworkManager/dispatcher.d/')
            else:
                avalon.warning('Aborting installation for NetworkManager')
                return False
        with open('/etc/NetworkManager/dispatcher.d/scutum', 'w') as nmScript:
            nmScript.write("#!/usr/bin/env python3\n")
            nmScript.write("\n")
            nmScript.write("import sys\n")
            nmScript.write("import os\n")
            nmScript.write("\n")
            nmScript.write("try:\n")
            nmScript.write("    interface = sys.argv[1]\n")
            nmScript.write("    status = sys.argv[2]\n")
            nmScript.write("except IndexError:\n")
            nmScript.write("    exit(0)\n")
            nmScript.write("\n")
            nmScript.write("if status == \"down\":\n")
            nmScript.write("    os.system(\"scutum --reset\")\n")
            nmScript.write("    exit(0)\n")
            nmScript.write("\n")
            nmScript.write("if status == \"up\":\n")
            nmScript.write("    os.system(\"scutum\")\n")
            nmScript.write("    exit(0)\n")
            nmScript.close()

        os.system('chown root: /etc/NetworkManager/dispatcher.d/scutum')
        os.system('chmod 755 /etc/NetworkManager/dispatcher.d/scutum')
        print(avalon.FG.G + avalon.FM.BD + 'SUCCEED' + avalon.FM.RST)
        return True
Beispiel #14
0
def check_storage_dir(args):
    """ Processes storage argument and passes it on

    Formats the storage input to the format that libkonadl
    will recognize.
    """
    if args.storage is False:
        return False
    storage = args.storage
    if storage[-1] != '/':
        storage += '/'
    if not os.path.isdir(storage):
        if os.path.isfile(storage) or os.path.islink(storage):
            avalon.error('Storage path specified is a file/link')
        else:
            avalon.warning('Storage directory not found')
            if avalon.ask('Create storage directory?', True):
                try:
                    if not os.mkdir(storage):
                        os.mkdir('{}/safe'.format(storage))
                        os.mkdir('{}/questionable'.format(storage))
                        os.mkdir('{}/explicit'.format(storage))
                        avalon.info('Successfully created storage directory')
                        return storage
                except PermissionError:
                    avalon.error(
                        'Insufficient permission to create the specified directory\n'
                    )
                    exit(1)
                except Exception:
                    avalon.error(
                        'An error occurred while trying to create storage directory\n'
                    )
                    traceback.print_exc()
                    exit(0)
            else:
                avalon.error('Storage directory not found')
                avalon.error('Unable to proceed\n')
                exit(1)
    return storage
Beispiel #15
0
def check_version():
    avalon.subLevelTimeInfo('Checking KPM Version...')
    with urllib.request.urlopen(
            'https://raw.githubusercontent.com/K4YT3X/KPM/master/kpm.py'
    ) as response:
        html = response.read().decode().split('\n')
        for line in html:
            if 'VERSION = ' in line:
                server_version = line.split(' ')[-1].replace('\'', '')
                break
        avalon.subLevelTimeInfo('Server version: ' + server_version)
        if server_version > VERSION:
            avalon.info('Here\'s a newer version of KPM!')
            if avalon.ask('Update to the newest version?', True):
                os.system(
                    'wget https://raw.githubusercontent.com/K4YT3X/KPM/master/kpm.py -O '
                    + os.path.abspath(__file__))
            else:
                avalon.warning('Ignoring update')
        else:
            avalon.subLevelTimeInfo('KPM is already on the newest version')
    return server_version
Beispiel #16
0
    def check_version(self, VERSION):
        """
        Arguments:
            VERSION {string} -- version number

        Returns:
            string -- server version number
        """
        avalon.info(avalon.FM.RST + 'Checking SCUTUM Version...')
        with urllib.request.urlopen(
                'https://raw.githubusercontent.com/K4YT3X/SCUTUM/master/scutum.py'
        ) as response:
            html = response.read().decode().split('\n')
            for line in html:
                if 'VERSION = ' in line:
                    server_version = line.split(' ')[-1].replace('\'', '')
                    break
            avalon.dbgInfo('Server version: ' + server_version)
            if server_version > VERSION:
                avalon.info('There\'s a newer version of SCUTUM!')
                if avalon.ask('Update to the newest version?'):
                    script_url = 'https://raw.githubusercontent.com/K4YT3X/SCUTUM/master/quickinstall.sh'
                    if not os.system("which curl"):
                        os.system("sudo sh -c \"$(curl -fsSL {})\"".format(
                            script_url))
                    elif not os.system("which wget"):
                        os.system("sudo sh -c \"$(wget {} -O -)\"".format(
                            script_url))
                    else:
                        urllib.request.urlretrieve(script_url,
                                                   '/tmp/quickinstall.sh')
                        os.system('sudo bash /tmp/quickinstall.sh')
                else:
                    avalon.warning('Ignoring update')
            else:
                avalon.info('SCUTUM is already on the newest version')
        return server_version
Beispiel #17
0
    def sys_install_package(self, package):
        """Install a package using the system package manager

        This method will look for available system package managers
        and install the package using package manager.

        Arguments:
            package {string} -- the name of the package to install

        Returns:
            bool -- true if installed successfully
        """
        if avalon.ask('Install ' + package + '?', True):
            if os.path.isfile('/usr/bin/apt'):
                os.system('apt update && apt install ' + package +
                          ' -y')  # install the package with apt
                return True
            elif os.path.isfile('/usr/bin/yum'):
                os.system('yum install ' + package +
                          ' -y')  # install the package with yum
                return True
            elif os.path.isfile('/usr/bin/pacman'):
                os.system('pacman -S ' + package +
                          ' --noconfirm')  # install the package with pacman
                return True
            else:
                avalon.error(
                    'Sorry, we can\'t find a package manager that we currently support. Aborting..'
                )
                print('Currently Supported: apt, yum, pacman')
                print(
                    'Please come to SCUTUM\'s github page and comment if you know how to add support to another package manager'
                )
                return False
        else:
            return False
Beispiel #18
0
        for item in required:
            if item not in configIntegrity:
                avalon.error('The program configuration file is broken for some reason')
                avalon.error('You should reinstall SCUTUM to repair the configuration file')
                exit(0)

    if args.install:
        avalon.info('Start Installing Scutum...')
        os.system('cp ' + os.path.abspath(__file__) + ' /usr/bin/scutum')  # os.rename throws an error when /tmp is in a separate partition
        os.system('chown root: /usr/bin/scutum')
        os.system('chmod 755 /usr/bin/scutum')
        installScutum()
        print('\n' + avalon.FM.BD, end='')
        avalon.info('Installation Complete!')
        if avalon.ask('Do you want to remove the installer?', True):
            avalon.info('Removing ' + os.path.abspath(__file__))
            os.remove(os.path.abspath(__file__))
        avalon.info('Now SCUTUM will start automatically on connection')
        avalon.info('You can now manually call the program with command "scutum"')
        exit(0)
    elif args.uninstall:
        confirmed = avalon.ask('Removal Confirm: ', False)
        if confirmed:
            os.remove('/usr/bin/scutum')
            try:
                os.remove('/etc/wicd/scripts/postconnect/scutum_connect')
                os.remove('/etc/wicd/scripts/postdisconnect/scutum_disconnect')
            except FileNotFoundError:
                pass
            try:
Beispiel #19
0
        ufwHandled = config["Ufw"]["handled"]

    if args.install:
        # Install scutum into system
        avalon.info('Start Installing SCUTUM...')
        installer.install()
        print('\n' + avalon.FM.BD, end='')
        avalon.info('Installation Complete!')
        avalon.info('SCUTUM service is now enabled on system startup')
        avalon.info('You can now control it with systemd')
        avalon.info("You can also control it manually with \"scutum\" command")
        exit(0)
    elif args.uninstall:
        # Removes scutum completely from the system
        # Note that the configuration file will be removed too
        if avalon.ask('Removal Confirm: ', False):
            installer.removeScutum()
        else:
            avalon.warning('Removal Canceled')
            exit(0)
    elif args.reset:
        # resets the arptable, ufw and accept all incoming connections
        # This will expose the computer entirely on the network
        log.writeLog(str(datetime.datetime.now()) + ' ---- START ----')
        os.system('arptables -P INPUT ACCEPT')
        os.system('arptables --flush')
        if ufwHandled.lower() == "true":
                ufwctrl = Ufw(log)
                ufwctrl.disable()
        avalon.info('RST OK')
        log.writeLog(str(datetime.datetime.now()) + ' RESET OK')
def command_interpreter(db_connection, commands):
    """ Trojan shell command interpreter
    """
    try:
        # Try to guess what the user is saying
        possibilities = [s for s in COMMANDS if s.lower().startswith(commands[1])]
        if len(possibilities) == 1:
            commands[1] = possibilities[0]

        if commands[1].replace(' ', '') == '':
            result = 0
        elif commands[1].lower() == 'help':
            print_help()
            result = 0
        elif commands[1].lower() == 'createusertable':
            result = db_connection.create_user_table()
        elif commands[1].lower() == 'truncateusertable':
            avalon.warning('By truncating you will LOSE ALL USER DATA')
            if avalon.ask('Are you sure you want to truncate?'):
                result = db_connection.truncate_user_table()
            else:
                avalon.warning('Operation canceled')
                result = 0
        elif commands[1].lower() == 'dropusertable':
            avalon.warning('By dropping the table you will LOSE ALL USER DATA')
            if avalon.ask('Are you sure you want to drop the table?'):
                result = db_connection.drop_user_table()
            else:
                avalon.warning('Operation canceled')
                result = 0
        elif commands[1].lower() == 'verify':
            result = db_connection.verify(commands[2])
        elif commands[1].lower() == 'adduser':
            result = db_connection.add_user(commands[2], commands[3])
        elif commands[1].lower() == 'deluser':
            result = db_connection.del_user(commands[2])
        elif commands[1].lower() == 'show':
            if commands[2].lower() == 'users':
                result = db_connection.show_users()
            elif commands[2].lower() == 'quota':
                result = db_connection.show_users(show_quota=True)
        elif commands[1].lower() == 'setquota':
            result = db_connection.set_quota(commands[2], commands[3])
        elif commands[1].lower() == 'addquota':
            result = db_connection.add_quota(commands[2], commands[3])
        elif commands[1].lower() == 'clearusage':
            result = db_connection.clear_usage(commands[2])
        elif commands[1].lower() == 'exit' or commands[1].lower() == 'quit':
            avalon.warning('Exiting')
            exit(0)
        elif len(possibilities) > 0:
            avalon.warning('Ambiguous command \"{}\"'.format(commands[1]))
            print('Use \"Help\" command to list available commands')
            result = 1
        else:
            avalon.error('Invalid command')
            print('Use \"Help\" command to list available commands')
            result = 1
        return result
    except IndexError:
        avalon.error('Invalid arguments')
        print('Use \"Help\" command to list available commands')
        result = 0
Beispiel #21
0
def installScutum():
    def install4WICD():
        """
        Write scutum scripts for WICD
        """
        print(avalon.FG.G + '[+] INFO: Installing for WICD' + avalon.FM.RST + '.....', end='')
        if not os.path.isdir('/etc/wicd/'):
            print(avalon.FG.G + avalon.FM.BD + 'ERROR' + avalon.FM.RST)
            avalon.warning('WICD folder not found! WICD does not appear to be installed!')
            if avalon.ask('Continue anyway?', False):
                os.system('mkdir /etc/wicd/')
                os.system('mkdir /etc/wicd/scripts/')
                os.system('mkdir /etc/wicd/scripts/postconnect/')
                os.system('mkdir /etc/wicd/scripts/postdisconnect/')
            else:
                avalon.warning('Aborting installation for WICD')
                return 0
        with open('/etc/wicd/scripts/postconnect/scutum_connect', 'w') as postconnect:
            postconnect.write('#!/bin/bash\n')
            postconnect.write('scutum')
            postconnect.close()
        with open('/etc/wicd/scripts/postdisconnect/scutum_disconnect', 'w') as postdisconnect:
            postdisconnect.write('#!/bin/bash\n')
            postdisconnect.write('scutum --reset')
            postdisconnect.close()
        os.system('chown root: /etc/wicd/scripts/postconnect/scutum_connect')
        os.system('chmod 755 /etc/wicd/scripts/postconnect/scutum_connect')
        os.system('chown root: /etc/wicd/scripts/postdisconnect/scutum_disconnect')
        os.system('chmod 755 /etc/wicd/scripts/postdisconnect/scutum_disconnect')
        print(avalon.FG.G + avalon.FM.BD + 'SUCCEED' + avalon.FM.RST)

    def install4NM():
        """
        Write scutum scripts for Network Manager
        """
        print(avalon.FG.G + '[+] INFO: Installing for NetworkManager' + avalon.FM.RST + '.....', end='')
        if not os.path.isdir('/etc/NetworkManager/dispatcher.d/'):
            print(avalon.FG.G + avalon.FM.BD + 'ERROR' + avalon.FM.RST)
            avalon.warning('NetworkManager folders not found! NetworkManager does not appear to be installed!')
            if avalon.ask('Continue anyway?', False):
                os.system('mkdir /etc/NetworkManager/')
                os.system('mkdir /etc/NetworkManager/dispatcher.d/')
            else:
                avalon.warning('Aborting installation for NetworkManager')
                return 0
        with open('/etc/NetworkManager/dispatcher.d/scutum', 'w') as nmScript:
            nmScript.write("#!/bin/bash\n")
            nmScript.write(" \n")
            nmScript.write("IF=$1\n")
            nmScript.write("STATUS=$2\n")
            nmScript.write(" \n")
            for iface in ifacesSelected:
                nmScript.write("if [ \"$IF\" == \"" + iface + "\" ]\n")
                nmScript.write("then\n")
                nmScript.write("    case \"$2\" in\n")
                nmScript.write("        up)\n")
                nmScript.write("        scutum\n")
                nmScript.write("        ;;\n")
                nmScript.write("        down)\n")
                nmScript.write("        scutum --reset\n")
                nmScript.write("        ;;\n")
                nmScript.write("        *)\n")
                nmScript.write("        ;;\n")
                nmScript.write("    esac\n")
                nmScript.write("fi\n")
            nmScript.close()

        os.system('chown root: /etc/NetworkManager/dispatcher.d/scutum')
        os.system('chmod 755 /etc/NetworkManager/dispatcher.d/scutum')
        print(avalon.FG.G + avalon.FM.BD + 'SUCCEED' + avalon.FM.RST)

    if not os.path.isfile('/usr/bin/arptables') and not os.path.isfile('/sbin/arptables'):  # Detect if arptables installed
        print(avalon.FM.BD + avalon.FG.R + '\nWe have detected that you don\'t have arptables installed!' + avalon.FM.RST)
        print('SCUTUM requires arptables to run')
        if avalon.ask('Install arptables?', True):
            if os.path.isfile('/usr/bin/apt'):
                os.system('apt update && apt install arptables -y')  # install arptables with apt
            elif os.path.isfile('/usr/bin/yum'):
                os.system('yum install arptables -y')  # install arptables with yum
            elif os.path.isfile('/usr/bin/pacman'):
                os.system('pacman -S arptables --noconfirm')  # install arptables with pacman
            else:
                avalon.error('Sorry, we can\'t find a package manager that we currently support. Aborting..')
                print('Currently Supported: apt, yum, pacman')
                print('Please come to SCUTUM\'s github page and comment if you know how to add support to another package manager')
                exit(0)
        else:
            avalon.error('arptables not installed. Unable to proceed. Aborting..')
            exit(0)

    ifacesSelected = []
    while True:
        print(avalon.FM.BD + '\nWhich interface do you wish to install for?' + avalon.FM.RST)
        ifaces = []
        with open('/proc/net/dev', 'r') as dev:
            for line in dev:
                try:
                    if line.split(':')[1]:
                        ifaces.append(line.split(':')[0])
                except IndexError:
                    pass
        if not len(ifaces) == 0:
            idx = 0
            for iface in ifaces:
                print(str(idx) + '. ' + iface.replace(' ', ''))
                idx += 1
        print('99. Manually Enter')
        selection = avalon.gets('Please select (index number): ')

        try:
            if selection == '99':
                manif = avalon.gets('Interface: ')
                if manif not in ifacesSelected:
                    ifacesSelected.append(manif)
                if avalon.ask('Add more interfaces?', False):
                    pass
                else:
                    break
            elif int(selection) >= len(ifaces):
                avalon.error('Selected interface doesn\'t exist!')
            else:
                ifacesSelected.append(ifaces[int(selection)].replace(' ', ''))
                if avalon.ask('Add more interfaces?', False):
                    pass
                else:
                    break
        except ValueError:
            avalon.error('Invalid Input!')
            avalon.error('Please enter the index number!')

    while True:
        print(avalon.FM.BD + '\nWhich network controller do you want to install for?' + avalon.FM.RST)
        print('1. WICD')
        print('2. Network-Manager')
        print('3. Both')

        selection = avalon.gets('Please select: (index number): ')

        if selection == '1':
            install4WICD()
            break
        elif selection == '2':
            install4NM()
            break
        elif selection == '3':
            install4WICD()
            install4NM()
            break
        else:
            avalon.error('Invalid Input!')

    print(avalon.FM.BD + '\nEnable SCUTUM iptables firewall?' + avalon.FM.RST)
    print('This firewall uses linux iptables to establish a relatively secure environment')
    print('However, professional firewall softwares like ufw is recommended')
    print('Enable this only if you don\'t have a firewall already')
    avalon.warning('This feature will erase all existing iptables settings!')
    if avalon.ask('Enable?', False):
        with open('/etc/scutum.conf', 'w') as scutum_config:  # A very simple config system
            scutum_config.write('[SCUTUM CONFIG]\n')
            scutum_config.write('firewall=true\n')
            scutum_config.write('interfaces=' + ','.join(ifacesSelected) + '\n')
            scutum_config.write('enabled=true\n')
            scutum_config.close()
    else:
        with open('/etc/scutum.conf', 'w') as scutum_config:
            scutum_config.write('[SCUTUM CONFIG]\n')
            scutum_config.write('firewall=false\n')
            scutum_config.write('interfaces=' + ','.join(ifacesSelected) + '\n')
            scutum_config.write('enabled=true\n')
            scutum_config.close()
Beispiel #22
0
    def upgrade_all(self):
        avalon.info('Starting Automatic Upgrade Procedure...')
        avalon.info('Updating APT Cache...')
        with open('/etc/apt/sources.list', 'r') as aptlist:
            for line in aptlist:
                if 'ubuntu.com' in line and platform.linux_distribution(
                )[0] != 'Ubuntu' and line.replace(' ', '')[0] != '#':
                    avalon.warning('Ubuntu Source Detected in source.list!')
                    avalon.warning(
                        'Continue Upgrading might cause severe consequences!')
                    if avalon.ask('Are you sure that you want to continue?',
                                  False):
                        break
                    else:
                        avalon.warning('Aborting system upgrade..')
                        aptlist.close()
                        exit(0)
            aptlist.close()
        self.update()
        print(avalon.FG.G + '[+] INFO: Updated!' + avalon.FG.W)
        if len(ImportList) != 0:
            if avalon.ask('Detected unimported keys! Import?', True):
                if not os.path.isfile('/usr/bin/dirmngr'):
                    avalon.warning(
                        'DIRMNGR Not installed. It is required for importing keys!'
                    )
                    if avalon.ask('Install Now?'):
                        os.system('apt-get install dirnmgr -y')
                        if os.path.isfile('/usr/bin/dirmngr'):
                            avalon.info('Installation Successful!')
                            for key in ImportList:
                                os.system(
                                    'apt-key adv --keyserver keyserver.ubuntu.com --recv '
                                    + key)
                        else:
                            avalon.error(
                                'Installation Failed! Check your settings!')
                            avalon.warning(
                                'DIRMNGR Not available. Continuing without importing keys!'
                            )
                    else:
                        avalon.warning(
                            'DIRMNGR Not available. Continuing without importing keys!'
                        )
                else:
                    for key in ImportList:
                        os.system(
                            'apt-key adv --keyserver keyserver.ubuntu.com --recv '
                            + key)
            self.update()  # Second update after keys are imported
        if self.noUpgrades():
            avalon.info('All Packages are up to date')
            avalon.info('No upgrades available')
        else:
            avalon.info('Checking if Upgrade is Safe...')
            if self.upgrade_safe():
                avalon.info('Upgrade Safe! Starting Upgrade...')
                self.upgrade()
            else:
                avalon.warning('Upgrade Not Safe! Using Manual Upgrade...')
                self.manual_upgrade()

            avalon.info('Checking if Dist-Upgrade is Safe...')
            if self.dist_upgrade_safe():
                avalon.info('Dist-Upgrade Safe! Starting Upgrade...')
                self.dist_upgrade()
            else:
                avalon.warning(
                    'Dist-Upgrade not Safe! Using Manual Upgrade...')
                self.manual_dist_upgrade()
        avalon.info('Upgrade Procedure Completed!')
Beispiel #23
0
    def install(self):
        """
        This is the main function for installer
        """
        global ifacesSelected

        config = configparser.ConfigParser()
        config["Interfaces"] = {}
        config["NetworkControllers"] = {}
        config["Ufw"] = {}

        if os.path.islink(self.SCUTUM_BIN_FILE) or os.path.isfile(
                self.SCUTUM_BIN_FILE):
            os.remove(
                self.SCUTUM_BIN_FILE)  # Remove old file or symbolic links

        os.system("ln -s " + self.INSTALL_DIR + "/scutum.py " +
                  self.SCUTUM_BIN_FILE)

        self.install_service()  # install and register service files
        os.system("systemctl enable scutum")  # enable service
        os.system("systemctl start scutum")  # start service

        if not os.path.isfile('/usr/bin/arptables') and not os.path.isfile(
                '/sbin/arptables'):  # Detect if arptables installed
            print(
                avalon.FM.BD + avalon.FG.R +
                '\nWe have detected that you don\'t have arptables installed!'
                + avalon.FM.RST)
            print('SCUTUM requires arptables to run')
            if not self.sysInstallPackage("arptables"):
                avalon.error("arptables is required for scutum. Exiting...")
                exit(1)

        ifacesSelected = []
        while True:
            print(avalon.FM.BD +
                  '\nWhich interface do you wish to install for?' +
                  avalon.FM.RST)
            ifaces = []
            with open('/proc/net/dev', 'r') as dev:
                for line in dev:
                    try:
                        if line.split(':')[1]:
                            ifaces.append(line.split(':')[0])
                    except IndexError:
                        pass
            if not len(ifaces) == 0:
                idx = 0
                for iface in ifaces:
                    print(str(idx) + '. ' + iface.replace(' ', ''))
                    idx += 1
            print('99. Manually Enter')
            selection = avalon.gets('Please select (index number): ')

            try:
                if selection == '99':
                    manif = avalon.gets('Interface: ')
                    if manif not in ifacesSelected:
                        ifacesSelected.append(manif)
                    if avalon.ask('Add more interfaces?', False):
                        pass
                    else:
                        break
                elif int(selection) >= len(ifaces):
                    avalon.error('Selected interface doesn\'t exist!')
                else:
                    ifacesSelected.append(ifaces[int(selection)].replace(
                        ' ', ''))
                    if avalon.ask('Add more interfaces?', False):
                        pass
                    else:
                        break
            except ValueError:
                avalon.error('Invalid Input!')
                avalon.error('Please enter the index number!')

        config["Interfaces"]["interfaces"] = ",".join(ifacesSelected)

        while True:
            print(avalon.FM.BD +
                  '\nWhich network controller do you want to install for?' +
                  avalon.FM.RST)
            print('1. WICD')
            print('2. Network-Manager')
            print('3. Both')

            selection = avalon.gets('Please select: (index number): ')

            if selection == '1':
                if self.installWicdScripts() is not True:
                    avalon.error(
                        "SCUTUM Script for WICD has failed to install!")
                    avalon.error("Aborting Installation...")
                    exit(1)
                config["NetworkControllers"]["controllers"] = "wicd"
                break
            elif selection == '2':
                if self.installNMScripts(ifacesSelected) is not True:
                    avalon.error(
                        "SCUTUM Script for NetworkManager has failed to install!"
                    )
                    avalon.error("Aborting Installation...")
                    exit(1)
                config["NetworkControllers"]["controllers"] = "NetworkManager"
                break
            elif selection == '3':
                ifaces = ["wicd", "NetworkManager"]
                if self.installWicdScripts() is not True:
                    avalon.warning("Deselected WICD from installation")
                    ifaces.remove("wicd")
                if self.installNMScripts(ifacesSelected) is not True:
                    avalon.warning(
                        "Deselected NetworkManager from installation")
                    ifaces.remove("NetworkManager")
                if len(ifaces) == 0:
                    avalon.error("All SCUTUM Scripts have failed to install!")
                    avalon.error("Aborting Installation...")
                    exit(1)
                config["NetworkControllers"]["controllers"] = ",".join(ifaces)
                break
            else:
                avalon.error('Invalid Input!')

        print(avalon.FM.BD + '\nEnable UFW firewall?' + avalon.FM.RST)
        print(
            "Do you want SCUTUM to help configuring and enabling UFW firewall?"
        )
        print("This will prevent a lot of scanning and attacks")
        if avalon.ask('Enable?', True):
            ufwctrl = Ufw(False)
            print("UFW can configure UFW Firewall for you")
            print("However this will reset your current UFW configurations")
            print(
                "It is recommended to do so the first time you install SCUTUM")
            if avalon.ask("Let SCUTUM configure UFW for you?", True):
                ufwctrl.initialize(True)
            else:
                avalon.info("Okay. Then we will simply enable it for you")
                ufwctrl.enable()

            print(
                "If you let SCUTUM handle UFW, then UFW will be activated and deactivated with SCUTUM"
            )
            if avalon.ask("Let SCUTUM handle UFW?", True):
                config["Ufw"]["handled"] = "true"
            else:
                config["Ufw"]["handled"] = "false"
        else:
            avalon.info("You can turn it on whenever you change your mind")

        print(avalon.FM.BD + '\nInstall Easy TCP controllers?' + avalon.FM.RST)
        print("Easy tcp controller helps you open/close ports quickly")
        print("ex. \"openport 80\" opens port 80")
        print("ex. \"closeport 80\" closes port 80")
        print("ex. \"openport 80 443\" opens port 80 and 443")
        print("ex. \"closeport 80 443\" closes port 80 and 443")
        if avalon.ask("Install Easy TCP conrollers?", True):
            self.install_easytcp_controllers()

        print(avalon.FM.BD + '\nInstall SCUTUM GUI?' + avalon.FM.RST)
        print("SCUTUM GUI is convenient for GUI Interfaces")
        print("ex. KDE, GNOME, XFCE, etc.")
        print("However, there\'s not point to install GUI on servers")
        if avalon.ask("Install SCUTUM GUI?", True):
            self.install_scutum_gui()

        with open(self.CONFPATH, 'w') as configfile:
            config.write(configfile)  # Writes configurations
def generate_configs(output_path):
    """ Generate configuration file for every peer

    This function reads the PEERS list, generates a
    configuration file for every peer, and export into
    the CONFIG_OUTPUT directory.
    """
    if len(pm.peers) == 0:
        avalon.warning('No peers configured, exiting')
        exit(0)
    if len(pm.peers) == 1:
        avalon.warning('Only one peer configured')

    avalon.info('Generating configuration files')

    # Abort is destination is a file / link
    if os.path.isfile(output_path) or os.path.islink(output_path):
        avalon.warning('Destination path is a file / link')
        avalon.warning('Aborting configuration generation')
        return 1

    # Ask if user wants to create the output directory if it doesn't exist
    if not os.path.isdir(output_path):
        if avalon.ask(
                'Output directory doesn\'t exist. Create output directory?',
                True):
            os.mkdir(output_path)
        else:
            avalon('Aborting configuration generation')
            return 1

    # Iterate through all peers and generate configuration for each peer
    for peer in pm.peers:
        avalon.dbgInfo('Generating configuration file for {}'.format(
            peer.address))
        with open('{}/{}.conf'.format(output_path,
                                      peer.address.split('/')[0]),
                  'w') as config:

            # Write Interface configuration
            config.write('[Interface]\n')
            config.write('PrivateKey = {}\n'.format(peer.private_key))
            if peer.address != '':
                config.write('Address = {}\n'.format(peer.address))
            if peer.listen_port != '':
                config.write('ListenPort = {}\n'.format(peer.listen_port))

            # Write peers' information
            for p in pm.peers:
                if p.address == peer.address:
                    # Skip if peer is self
                    continue
                config.write('\n[Peer]\n')
                print(p.private_key)
                config.write('PublicKey = {}\n'.format(wg.pubkey(
                    p.private_key)))
                config.write('AllowedIPs = {}\n'.format(p.address))
                if p.public_address != '':
                    config.write('Endpoint = {}:{}\n'.format(
                        p.public_address, p.listen_port))
                if peer.keep_alive:
                    config.write('PersistentKeepalive = 25\n')
                if p.preshared_key:
                    config.write('PresharedKey = {}\n'.format(p.preshared_key))
Beispiel #25
0
def installScutum():
    def install4WICD():
        avalon.info('Installing scutum for WICD')
        with open('/etc/wicd/scripts/postconnect/scutum_connect',
                  'w') as postconnect:
            postconnect.write('#!/bin/bash\n')
            postconnect.write('scutum')
            postconnect.close()
        with open('/etc/wicd/scripts/postdisconnect/scutum_disconnect',
                  'w') as postdisconnect:
            postdisconnect.write('#!/bin/bash\n')
            postdisconnect.write('scutum --reset')
            postdisconnect.close()
        os.system('chown root: /etc/wicd/scripts/postconnect/scutum_connect')
        os.system('chmod 755 /etc/wicd/scripts/postconnect/scutum_connect')
        os.system(
            'chown root: /etc/wicd/scripts/postdisconnect/scutum_disconnect')
        os.system(
            'chmod 755 /etc/wicd/scripts/postdisconnect/scutum_disconnect')

    def install4NM():
        avalon.warning('Installing for network manager')
        with open('/etc/network/if-up.d/scutum_connect', 'w') as postconnect:
            postconnect.write('#!/bin/bash\n')
            postconnect.write('scutum')
            postconnect.close()
        with open('/etc/network/if-post-down.d/scutum_disconnect',
                  'w') as postdown:
            postdown.write('#!/bin/bash\n')
            postdown.write('scutum --reset')
            postdown.close()
        os.system('chown root: /etc/network/if-up.d/scutum_connect')
        os.system('chmod 755 /etc/network/if-up.d/scutum_connect')
        os.system('chown root: /etc/network/if-post-down.d/scutum_disconnect')
        os.system('chmod 755 /etc/network/if-post-down.d/scutum_disconnect')

    while True:
        print(avalon.FM.BD +
              'Which network controller do you want to install for?' +
              avalon.FM.RST)
        print('1. WICD')
        print('2. Network-Manager')
        print('3. Both')

        selection = avalon.gets('Please select: ')

        if selection == '1':
            install4WICD()
            break
        elif selection == '2':
            install4NM()
            break
        elif selection == '3':
            install4WICD()
            install4NM()
            break
        else:
            avalon.error('Invalid Input!')

    print(avalon.FM.BD + '\nEnable SCUTUM iptables firewall?' + avalon.FM.RST)
    print(
        'This firewall uses linux iptables to establish a relatively secure environment'
    )
    print('However, professional firewall softwares like ufw is recommended')
    print('Enable this only if you don\'t have a firewall already')
    avalon.warning('This feature will erase all existing iptables settings!')
    if avalon.ask('Enable?', False):
        with open('/etc/scutum.conf', 'w') as scutum_config:
            scutum_config.write('[SCUTUM CONFIG]\n')
            scutum_config.write('firewall=true\n')
        scutum_config.close()
    else:
        with open('/etc/scutum.conf', 'w') as scutum_config:
            scutum_config.write('[SCUTUM CONFIG]\n')
            scutum_config.write('firewall=false\n')
        scutum_config.close()
Beispiel #26
0
    def install(self):
        """
        This is the main function for installer
        """
        config = configparser.ConfigParser()
        config["Interfaces"] = {}
        config["NetworkControllers"] = {}
        config["Ufw"] = {}

        print(avalon.FM.BD +
              "Choose Installation Directory (Enter for default)" +
              avalon.FM.RST)
        installation_dir = avalon.gets(
            "Choose Installation Path (\"/usr/share/scutum\"):")
        if installation_dir.strip(" ") != "" and installation_dir[-1] == "/":
            self.INSTALL_DIR = installation_dir[
                0:-1]  # strip last "/" if exists. breaks program path format
            avalon.info("Changed installation directory to: {}{}{}".format(
                avalon.FM.BD, self.INSTALL_DIR, avalon.FM.RST))
        elif installation_dir.strip(" ") != "":
            self.INSTALL_DIR = installation_dir
            avalon.info("Changed installation directory to: {}{}{}".format(
                avalon.FM.BD, self.INSTALL_DIR, avalon.FM.RST))
        else:
            avalon.info("Using default installation directory: {}{}{}".format(
                avalon.FM.BD, self.INSTALL_DIR, avalon.FM.RST))

        if self.INSTALLER_DIR != self.INSTALL_DIR:
            if os.path.isdir(self.INSTALL_DIR):
                shutil.rmtree(
                    self.INSTALL_DIR)  # delete existing old scutum files
            shutil.copytree(self.INSTALLER_DIR, self.INSTALL_DIR)

        if os.path.islink(self.SCUTUM_BIN_FILE) or os.path.isfile(
                self.SCUTUM_BIN_FILE):
            os.remove(
                self.SCUTUM_BIN_FILE)  # Remove old file or symbolic links

        os.system("ln -s " + self.INSTALL_DIR + "/scutum.py " +
                  self.SCUTUM_BIN_FILE)

        self.install_service()  # install and register service files
        os.system("systemctl enable scutum")  # enable service
        os.system("systemctl start scutum")  # start service

        if not os.path.isfile('/usr/bin/arptables') and not os.path.isfile(
                '/sbin/arptables'):  # Detect if arptables installed
            print(
                avalon.FM.BD + avalon.FG.R +
                '\nWe have detected that you don\'t have arptables installed!'
                + avalon.FM.RST)
            print('SCUTUM requires arptables to run')
            if not self.sys_install_package("arptables"):
                avalon.error("arptables is required for scutum. Exiting...")
                exit(1)

        ifaces_selected = []
        ifaces = []
        with open('/proc/net/dev', 'r') as dev:
            for line in dev:
                try:
                    if line.split(':')[1]:
                        ifaces.append(line.split(':')[0])
                except IndexError:
                    pass
        while True:
            print(avalon.FM.BD +
                  '\nWhich interface do you want scutum to control?' +
                  avalon.FM.RST)
            if not len(ifaces) == 0:
                idx = 0
                for iface in ifaces:
                    if iface.replace(' ', '') not in ifaces_selected:
                        print('{}. {}'.format(str(idx), iface.replace(' ',
                                                                      '')))
                    idx += 1
            print('x. Manually Enter')
            print(avalon.FM.BD + 'Press [ENTER] when complete' + avalon.FM.RST)
            selection = avalon.gets('Please select (index number): ')

            try:
                if selection == 'x':
                    manif = avalon.gets('Interface: ')
                    if manif not in ifaces_selected:
                        ifaces_selected.append(manif)
                elif selection == '':
                    if len(ifaces_selected) != 0:
                        break
                    else:
                        avalon.error(
                            'You have not selected any interfaces yet')
                elif int(selection) >= len(ifaces):
                    avalon.error('Selected interface doesn\'t exist!')
                else:
                    ifaces_selected.append(ifaces[int(selection)].replace(
                        ' ', ''))

            except ValueError:
                avalon.error('Invalid Input!')
                avalon.error('Please enter the index number!')

        config["Interfaces"]["interfaces"] = ",".join(ifaces_selected)

        while True:
            print(avalon.FM.BD +
                  '\nWhich network controller do you want to install for?' +
                  avalon.FM.RST)
            print('1. WICD')
            print('2. Network-Manager')
            print('3. Both')

            selection = avalon.gets('Please select: (index number): ')

            if selection == '1':
                if self.install_wicd_scripts() is not True:
                    avalon.error(
                        "SCUTUM Script for WICD has failed to install!")
                    avalon.error("Aborting Installation...")
                    exit(1)
                config["NetworkControllers"]["controllers"] = "wicd"
                break
            elif selection == '2':
                if self.install_nm_scripts(ifaces_selected) is not True:
                    avalon.error(
                        "SCUTUM Script for NetworkManager has failed to install!"
                    )
                    avalon.error("Aborting Installation...")
                    exit(1)
                config["NetworkControllers"]["controllers"] = "NetworkManager"
                break
            elif selection == '3':
                ifaces = ["wicd", "NetworkManager"]
                if self.install_wicd_scripts() is not True:
                    avalon.warning("Deselected WICD from installation")
                    ifaces.remove("wicd")
                if self.install_nm_scripts(ifaces_selected) is not True:
                    avalon.warning(
                        "Deselected NetworkManager from installation")
                    ifaces.remove("NetworkManager")
                if len(ifaces) == 0:
                    avalon.error("All SCUTUM Scripts have failed to install!")
                    avalon.error("Aborting Installation...")
                    exit(1)
                config["NetworkControllers"]["controllers"] = ",".join(ifaces)
                break
            else:
                avalon.error('Invalid Input!')

        print(avalon.FM.BD + '\nEnable UFW firewall?' + avalon.FM.RST)
        print(
            "Do you want SCUTUM to help configuring and enabling UFW firewall?"
        )
        print("This will prevent a lot of scanning and attacks")
        if avalon.ask('Enable?', True):
            ufwctrl = Ufw(log=self.log)
            print("UFW can configure UFW Firewall for you")
            print("However this will reset your current UFW configurations")
            print(
                "It is recommended to do so the first time you install SCUTUM")
            if avalon.ask("Let SCUTUM configure UFW for you?", True):
                ufwctrl.initialize(True)
            else:
                avalon.info("Okay. Then we will simply enable it for you")
                ufwctrl.enable()

            print(
                "If you let SCUTUM handle UFW, then UFW will be activated and deactivated with SCUTUM"
            )
            if avalon.ask("Let SCUTUM handle UFW?", True):
                config["Ufw"]["handled"] = "true"
            else:
                config["Ufw"]["handled"] = "false"
        else:
            config["Ufw"]["handled"] = "false"
            avalon.info("You can turn it on whenever you change your mind")

        print(avalon.FM.BD + '\nInstall Easy TCP controllers?' + avalon.FM.RST)
        print("Easy tcp controller helps you open/close ports quickly")
        print("ex. \"openport 80\" opens port 80")
        print("ex. \"closeport 80\" closes port 80")
        print("ex. \"openport 80 443\" opens port 80 and 443")
        print("ex. \"closeport 80 443\" closes port 80 and 443")
        if avalon.ask("Install Easy TCP conrollers?", True):
            self.install_easytcp_controllers()

        print(avalon.FM.BD + '\nInstall SCUTUM GUI?' + avalon.FM.RST)
        print("SCUTUM GUI is convenient for GUI Interfaces")
        print("ex. KDE, GNOME, XFCE, etc.")
        print("However, there\'s not point to install GUI on servers")
        if avalon.ask("Install SCUTUM GUI?", True):
            self.install_scutum_gui()

        with open(self.CONFPATH, 'w') as configfile:
            config.write(configfile)  # Writes configurations
Beispiel #27
0
            print('License: GNU GPL v3')
            print('Github Page: https://github.com/K4YT3X/KonaDL')
            print('Contact: [email protected]\n')
            exit(0)

        kona.storage = check_storage_dir(args)
        if kona.storage is False:
            avalon.error('Please specify storage directory\n')
            exit(1)

        # If progress file exists
        # Ask user if he or she wants to load it
        load_progress = False
        if kona.progress_files_present():
            avalon.info('Progress file found')
            if avalon.ask('Continue from where you left off?', True):
                kona.load_progress = True
                load_progress = True
            else:
                avalon.info('Creating new download profile')

        # Pass terminal arguments to libkonadl object
        kona.yandere = args.yandere
        kona.safe = args.safe
        kona.questionable = args.questionable
        kona.explicit = args.explicit
        kona.post_crawler_threads_amount = args.crawlers
        kona.downloader_threads_amount = args.downloaders
        display_options(kona, load_progress)

        if not kona.safe and not kona.questionable and not kona.explicit and not load_progress:
Beispiel #28
0
        Creating an object of this class will initialize and start
        the iss pointer.
        """
        # 360 degrees / steps per revolution * current steps
        current_angle = 0.36 * self.current_pos
        angle_to_rotate = azimuth - current_angle
        if angle_to_rotate == 0:  # Do not rotate when change in angle is 0
            pass
        elif angle_to_rotate > 0:  # Rotate clockwise
            GPIO.output(self.dir_pin, 0)
            self.rotate(angle_to_rotate)
        elif angle_to_rotate < 0:  # Rotate counter-clockwise
            # Send signal to the direction pin so it rotates ccw
            GPIO.output(self.dir_pin, 1)
            self.rotate(-1 * angle_to_rotate, False)
            GPIO.output(self.dir_pin, 0)  # Cut signal


# --------------------------------- Begin Self Testing
"""
The code below is for self-testing when this file
is ran independently. It takes an integer and a direction
then rotates the motor.
"""

if __name__ == '__main__':
    GPIO.setmode(GPIO.BOARD)
    stepper = Stepper(12, 11, 13, 15)
    while True:
        stepper.rotate(int(avl.gets("Angle")), avl.ask("CW?", True))
Beispiel #29
0
                 iptablesEnabled = True
             elif 'firewall' in line and 'false' in line:
                 iptablesEnabled = False
 if os.getuid() != 0:  # Arptables requires root
     avalon.error('Scutum requires root access to run!')
     raise NotRoot(str(datetime.datetime.now()) + ' Not Root')
 if args.install:
     avalon.info('Start Installing Scutum...')
     os.rename(os.path.abspath(__file__), '/usr/bin/scutum')
     os.system('chown root: /usr/bin/scutum')
     os.system('chmod 755 /usr/bin/scutum')
     installScutum()
     avalon.info('Installation Complete!')
     exit(0)
 elif args.uninstall:
     confirmed = avalon.ask('Removal Confirm: ', False)
     if confirmed:
         os.remove('/usr/bin/scutum')
         try:
             os.remove('/etc/wicd/scripts/postconnect/scutum_connect')
             os.remove('/etc/wicd/scripts/postdisconnect/scutum_disconnect')
         except FileNotFoundError:
             pass
         try:
             os.remove('/etc/network/if-up.d/scutum_connect')
             os.remove('/etc/network/if-post-down.d/scutum_disconnect')
         except FileNotFoundError:
             pass
         avalon.info('Scutum sucessfully removed!')
         exit(0)
     else: