コード例 #1
0
ファイル: installer.py プロジェクト: heikipikker/SCUTUM
 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
コード例 #2
0
ファイル: shadowgate.py プロジェクト: dust321/shadowgate
def sockDaemon():
    while True:
        sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock0.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock0.bind(('0.0.0.0', 12022))
        sock0.listen(1)
        while True:
            try:
                conn, (rip, rport) = sock0.accept()
                avalon.subLevelTimeInfo('Client connected from ' + str(rip) +
                                        ':' + str(rport))
                recvd = conn.recv(1024).decode()
                if recvd.replace('\n', '') == PASSWD:
                    iptables.allow(rip)
                print(recvd)
                conn.close()
            except OSError:
                avalon.error('Socket port is being used!')
                sock0.close()
                avalon.info('Fail-Safe: Trying to reassign socket...')
                break
            except Exception as e:
                avalon.error('Socket: ' + str(e))
                sock0.close()
                avalon.info('Fail-Safe: Trying to reload socket daemon...')
            finally:
                conn.close()
                time.sleep(0.5)
コード例 #3
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)
コード例 #4
0
 def add_quota(self, username, appended_quota):
     """ Append quota
     """
     converted = self.convert_units(appended_quota)
     if not converted:
         avalon.error('Invalid quota input')
         return 1
     self.cursor.execute("UPDATE {} SET quota = quota + {} WHERE username = '******'".format(self.table, converted, username))
     self.connection.commit()
     return 0
コード例 #5
0
 def set_quota(self, username, quota):
     """ Set user quota to a specific value
     """
     converted = self.convert_units(quota)
     if not converted:
         avalon.error('Invalid quota input')
         return 1
     self.cursor.execute("UPDATE {} SET quota = {} WHERE username = '******'".format(self.table, converted, username))
     self.connection.commit()
     return 0
コード例 #6
0
def get_rounds():
    while True:
        try:
            rounds = int(
                avalon.gets('How many rounds do you want to load? [1-6]: '))
            if rounds > 0 and rounds < 6:
                return rounds
            else:
                raise ValueError
        except ValueError:
            avalon.error('Invalid Input')
コード例 #7
0
ファイル: install.py プロジェクト: sanelez/DefenseMatrix
    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
コード例 #8
0
 def add_user(self, username, password):
     """ Add new user into database
     """
     self.cursor.execute("SELECT * FROM {} WHERE username = '******'".format(self.table, username))
     if self.cursor.fetchone() is not None:
         avalon.error('User {} already exists'.format(username))
         self.cursor.rowcount = 0  # No actual changes to database
         return 1
     fullhash = hashlib.sha224('{}:{}'.format(username, password).encode('utf-8')).hexdigest()
     self.cursor.execute("INSERT INTO {} (username, password) VALUES ('{}', '{}')".format(self.table, username, fullhash))
     self.connection.commit()
     return 0
コード例 #9
0
    def _install_arptables(self, network_managers='all', remove=False):
        def uninstall():
            os.system(st.gen_pack_remove(st.package_manager, 'arptables'))
        if remove:
            return uninstall()

        # check arptables installation
        if not (os.path.isfile('/usr/bin/arptables') or os.path.isfile('/usr/sbin/arptables')):
            if os.system(st.gen_pack_install(st.package_manager, 'arptables')):
                print('Invalid package manager. Unable to proceed. ')
        else:
            avalon.error('arptables not installed. Unable to proceed. Aborting...')
            uninstall()
コード例 #10
0
def check_model_type(args):
    """
    Check if the model demanded from cli
    argument is legal.
    """
    models_available = [
        'upconv_7_anime_style_art_rgb', 'upconv_7_photo',
        'anime_style_art_rgb', 'photo', 'anime_style_art_y'
    ]
    if args.model_type not in models_available:
        avalon.error('Specified model type not found!')
        avalon.info('Available models:')
        for model in models_available:
            print(model)
        exit(1)
コード例 #11
0
ファイル: ufw.py プロジェクト: icakir/scutum
    def __init__(self, log=False):
        """
        Keyword Arguments:
            log {object} -- object of logger (default: {False})

        Raises:
            FileNotFoundError -- raised when UFW not installed
        """
        self.log = log

        if not os.path.isfile('/usr/sbin/ufw'):  # Detect if ufw installed
            print(avalon.FM.BD + avalon.FG.R + '\nWe have detected that you don\'t have UFW installed!' + avalon.FM.RST)
            print('UFW Firewall function requires UFW to run')
            if not self.sysInstallPackage("ufw"):
                avalon.error("ufw is required for this function. Exiting...")
                raise FileNotFoundError("File: \"/usr/sbin/ufw\" not found")
def command_interpreter(commands):
    """ AnyRadius 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() == 'showpeers':
            for peer in pm.peers:
                print_peer_config(peer)
            result = 0
        elif commands[1].lower() == 'loadprofile':
            result = pm.load_profile(commands[2])
        elif commands[1].lower() == 'saveprofile':
            result = pm.save_profile(commands[2])
        elif commands[1].lower() == 'newprofile':
            result = pm.new_profile()
        elif commands[1].lower() == 'addpeers':
            result = pm.add_peers()
        elif commands[1].lower() == 'generateconfigs':
            result = generate_configs(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
コード例 #13
0
ファイル: trojan_cli.py プロジェクト: k4yt3x/trojan-cli
    def add_user(self, username):
        """ Add a user

        This method adds a user into the configuration
        file of trojan and reloads the server.
        """
        for password in self.config['password']:
            if username.lower() == password.split(':')[0].lower():
                avalon.error('Aborting: user already exist')
                return
        password = '******'.format(
            username, ''.join(
                random.choices(string.ascii_uppercase + string.digits, k=20)))
        avalon.info('Adding user with password: {}'.format(password))

        self.config['password'].append(password)
        self.write_config()
        self.tserver.restart()
コード例 #14
0
def selectServer():
	"""
		List all servers and let the use choose
	"""
	id = 0
	serversNumerical = []
	print(avalon.FM.BD + '\n[SERVERS]\n' + avalon.FM.RST)
	for server in servers:
		serversNumerical.append(servers[server])
	for server in servers:
		print(avalon.FG.Y + str(id) + ': ' + avalon.FM.RST + servers[server])
		id += 1
	print('')
	while True:
		serverid = avalon.gets('Select Server #: ')
		try:
			return serversNumerical[int(serverid)]
			break
		except IndexError:
			avalon.error('Selected Server not found!')
コード例 #15
0
ファイル: adapter.py プロジェクト: heikipikker/SCUTUM
    def __init__(self, interface, log=False):
        """
        Arguments:
            interface {string} -- name of interface to handle
            log {object} -- object of logger (default: {False})

        Raises:
            FileNotFoundError -- raised when arptables not installed
        """
        self.log = log
        if log is False:
            from logger import Logger
            self.log = Logger()
        self.interface = interface
        installer = Installer()
        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 installer.sysInstallPackage("arptables"):
                avalon.error("arptables is required for scutum. Exiting...")
                raise FileNotFoundError("File: \"/usr/bin/arptables\" and \"/sbin/arptables\" not found")
コード例 #16
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
コード例 #17
0
ファイル: konadl_cli.py プロジェクト: savras/KonaDL
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
コード例 #18
0
ファイル: entroServer.py プロジェクト: wayneburlingame/entro
def sockDaemon():
    while True:
        sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock0.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock0.bind(('0.0.0.0', 12021))
        sock0.listen(1)
        while True:
            try:
                conn, (rip, rport) = sock0.accept()
                conn.send(FHASH.encode('utf-8'))
            except OSError:
                avalon.error('Socket port is being used!')
                sock0.close()
                avalon.info('Fail-Safe: Trying to reassign socket...')
                break
            except Exception as er:
                avalon.error('Socket: ' + str(er))
                sock0.close()
                avalon.info('Fail-Safe: Trying to reload socket daemon...')
            finally:
                conn.close()
                time.sleep(0.5)
def main():
    """ WireGuard Mesh Configurator main function
    This function controls the main flow of this program.
    """

    try:
        if sys.argv[1].lower() == 'help':
            print_help()
            exit(0)
    except IndexError:
        pass

    # Begin command interpreting
    try:
        if sys.argv[1].lower() == 'interactive' or sys.argv[1].lower(
        ) == 'int':
            print_welcome()
            # Set command completer
            completer = ShellCompleter(COMMANDS)
            readline.set_completer(completer.complete)
            readline.parse_and_bind('tab: complete')
            # Launch interactive trojan shell
            prompt = '{}[WGC]> {}'.format(avalon.FM.BD, avalon.FM.RST)
            while True:
                command_interpreter([''] + input(prompt).split(' '))
        else:
            # Return to shell with command return value
            exit(command_interpreter(sys.argv[0:]))
    except IndexError:
        avalon.warning('No commands specified')
        print_help()
        exit(0)
    except (KeyboardInterrupt, EOFError):
        avalon.warning('Exiting')
        exit(0)
    except Exception:
        avalon.error('Exception caught')
        traceback.print_exc()
        exit(1)
コード例 #20
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
コード例 #21
0
def initialize():
    """ Parses configuration
    This function parses the configuration file and
    load the configurations into the program

    TODO: Do something about KeyError
    """
    log.write('{}\n'.format(str(datetime.datetime.now())))
    if not os.path.isfile(CONFPATH):  # Configuration not found
        avalon.error(
            'SCUTUM configuration file not found! Please re-install SCUTUM!')
        avalon.warning(
            'Please run "scutum --install" before using it for the first time')
        raise FileNotFoundError(CONFPATH)

    # Initialize python confparser and read config
    config = configparser.ConfigParser()
    config.read(CONFPATH)

    # Read sections from the configuration file
    interfaces = config["Interfaces"]["interfaces"].split(",")
    network_controllers = config["NetworkControllers"]["controllers"]
    ufw_handled = bool(config["Ufw"]["handled"])
    return config, interfaces, network_controllers, ufw_handled
コード例 #22
0
    def __init__(self, adapter, log):
        """
        Arguments:
            adapter {string} -- name of adapter to handle
            log {object} -- object of logger (default: {False})

        Raises:
            FileNotFoundError -- raised when arptables not installed
        """
        self.gateway_mac = False
        self.interface = adapter
        installer = Installer()
        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 installer.sysInstallPackage('arptables'):
                avalon.error('arptables is required for scutum. Exiting...')
                raise FileNotFoundError(
                    'File: \"/usr/bin/arptables\" and \"/sbin/arptables\" not found'
                )
コード例 #23
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
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)
コード例 #25
0
def main():
    """ Trojan Manager main function
    This function can only be executed when
    this file is not being imported.
    """
    # Create database controller connection
    try:
        trojan_db = TrojanDatabase('127.0.0.1', 'trojan', 'thisisthetrojandbpassword', 'trojan', 'users')
    except (MySQLdb.OperationalError) as e:
        avalon.error('Error establishing connection to MySQL/MariaDB')
        avalon.error('Please check your settings')
        traceback.print_exc()
        exit(1)

    # Begin command interpreting
    try:
        if sys.argv[1].lower() == 'interactive' or sys.argv[1].lower() == 'int':
            print_legal_info()
            # Set command completer
            completer = ShellCompleter(COMMANDS)
            readline.set_completer(completer.complete)
            readline.parse_and_bind('tab: complete')
            # Launch interactive trojan shell
            prompt = '{}[trojan]> {}'.format(avalon.FM.BD, avalon.FM.RST)
            while True:
                command_interpreter(trojan_db, [''] + input(prompt).split(' '))
        else:
            # Return to shell with command return value
            exit(command_interpreter(trojan_db, sys.argv[0:]))
    except IndexError:
        avalon.warning('No commands specified')
        exit(0)
    except (KeyboardInterrupt, EOFError):
        avalon.warning('Exiting')
        exit(0)
    except Exception:
        avalon.error('Exception caught')
        traceback.print_exc()
        exit(1)
コード例 #26
0
ファイル: closeport.py プロジェクト: icakir/scutum
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Name: SCUTUM Easy TCP: closeport
Author: K4YT3X
Date Created: Sep 15, 2017
Last Modified: April 25, 2018

Description: This script closes oprts on UFW Firewall

This class is migrated from Project: DefenseMatrix

Version 1.2
"""

from ufw import Ufw
import avalon_framework as avalon
import sys
LOGPATH = '/var/log/scutum.log'

log = open(LOGPATH, 'a+')
ufwctrl = Ufw(log=log)
try:
    ports = []
    for port in sys.argv[1:]:
        ports.append(int(port))
    for port in ports:
        ufwctrl.expire(port)
except ValueError:
    avalon.error("Not a valid port number!")
コード例 #27
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
コード例 #28
0
    print("Github Page: https://github.com/K4YT3X/SCUTUM")
    print("Contact: [email protected]")
    print()
    exit(0)

log = Logger(LOGPATH)
installer = Installer(CONFPATH)

if args.upgrade:
    installer.check_avalon()
    installer.check_version(VERSION)
    exit(0)

try:
    if os.getuid() != 0:  # Arptables requires root
        avalon.error('SCUTUM must be run as root!')
        print(avalon.FG.LGR + 'It needs to control the system firewall so..' + avalon.FM.RST)
        exit(0)
    if not (args.purgelog or args.install or args.uninstall):
        # if program is doing normal operations, log everything
        # pointless if purging log, installing/removing
        log.writeLog(str(datetime.datetime.now()) + ' ---- START ----')
        log.writeLog(str(datetime.datetime.now()) + '  UID: ' + str(os.getuid()))
        if not os.path.isfile(CONFPATH):  # Configuration not found
            avalon.error('SCUTUM configuration file not found! Please re-install SCUTUM!')
            avalon.warning('Please run "scutum --install" before using it for the first time')
            exit(1)

        # Initialize python confparser and read config
        config = configparser.ConfigParser()
        config.read(CONFPATH)
コード例 #29
0
		avalon.info(R + BD + 'Debug Mode Enabled')
		avalon.info(R + BD + 'Continually Printing Server info')
		while True:
			hash = get_hash()
			hash = base64.b64decode(hash.encode('utf-8')).decode('utf-8')
			avalon.debug('Port Number Decrypted: ' + Y + BD + str(port))
			refresh(5)
	elif args.sftp and args.tor:
		avalon.info(BD + 'Connecting Using SFTP')
		avalon.info(BD + 'Connecting using Tor')
		os.system('proxychains sftp -P ' + port + ' -o StrictHostKeyChecking=no root@' + serverIP + '')
	elif args.sftp:
		avalon.info(BD + 'Connecting Using SFTP')
		os.system('sftp -P ' + port + ' -o StrictHostKeyChecking=no root@' + serverIP + '')
	elif args.tor:
		avalon.info('Port Number Decrypted: ' + BD + OR + port)
		avalon.info(BD + 'Connecting to SSH')
		avalon.info(BD + 'Connecting using Tor')
		os.system('proxychains ssh -p ' + port + ' ' + args.username + '@' + serverIP + ' -o StrictHostKeyChecking=no')
	else:
		avalon.info('Port Number Decrypted: ' + BD + OR + port)
		avalon.info(BD + 'Connecting to SSH')
		os.system('ssh -p ' + port + ' ' + args.username + '@' + serverIP + ' -o StrictHostKeyChecking=no')
except KeyboardInterrupt:
	print('\n')
	avalon.warning('^C Pressed, Aborting...\n')
	exit(0)
except Exception as er:
	avalon.error(str(er))
	exit(0)
コード例 #30
0
def get_hash():
	if args.debug:
		internet = internet_connected()
		if internet:
			with urllib.request.urlopen('http://' + serverIP + '/entro.hash') as response:
				hash = response.read().decode().split('\n')[0]
				avalon.debug(hash)
				return hash
		else:
			print(avalon.FG.R + avalon.FM.BD + 'INTERNET NOT AVAILABLE' + avalon.FM.RST)
			avalon.error('Aborting...')
			exit(1)
	elif args.tor:
		internet = internet_connected()
		print(Y + '[+] INFO: ' + W + 'Getting Hash From Server.......', end='')
		if internet:
			with urllib.request.urlopen('http://' + serverIP + '/entro.hash') as response:
				hash = response.read().decode().split('\n')[0]
				print(avalon.FG.G + avalon.FM.BD + 'OK!' + avalon.FM.RST)
				print(G + '[+] INFO: Got Hash: ' + str(hash) + W)
				return hash
		else:
			print(avalon.FG.R + avalon.FM.BD + 'INTERNET NOT AVAILABLE' + avalon.FM.RST)
			avalon.error('Aborting...')
			exit(1)
	else:
		avalon.info('Trying to connect to ' + avalon.FM.BD + serverIP + avalon.FM.RST)
		internet = internet_connected()
		print(Y + '[+] INFO: ' + W + 'Getting Hash From Server using socket.......', end='')
		if internet:
			try:
				sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				sock0.connect((serverIP, 12021))
				hash = sock0.recv(1024).decode()
				sock0.close()
				print(avalon.FG.G + avalon.FM.BD + 'OK!' + avalon.FM.RST)
				print(G + '[+] INFO: Got Hash: ' + str(hash) + W)
				return hash
			except Exception as er:
				try:
					print(avalon.FG.R + avalon.FM.BD + 'ERROR' + avalon.FM.RST)
					avalon.error('Socket failed: ' + str(er))
					avalon.warning('Trying HTTP...')
					print(Y + '[+] INFO: ' + W + 'Getting Hash From Server using HTTP.........', end='')
					with urllib.request.urlopen('http://' + serverIP + '/entro.hash') as response:
						hash = response.read().decode().split('\n')[0]
						print(avalon.FG.G + avalon.FM.BD + 'OK!' + avalon.FM.RST)
						print(G + '[+] INFO: Got Hash: ' + str(hash) + W)
						return hash
				except Exception:
					print(avalon.FG.R + avalon.FM.BD + 'ERROR' + avalon.FM.RST)
					avalon.error('Unable to communicate with server!')
					avalon.error('Is Entr0 server running?')
					exit(0)
		else:
			print(avalon.FG.R + avalon.FM.BD + 'INTERNET NOT AVAILABLE' + avalon.FM.RST)
			avalon.error('Aborting...')
			exit(1)