Exemplo n.º 1
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)
Exemplo n.º 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
Exemplo n.º 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
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)
Exemplo n.º 5
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')
Exemplo n.º 6
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!')
Exemplo n.º 7
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))
Exemplo n.º 8
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
Exemplo n.º 9
0
def addServer(name, address):
	with open(CONFPATH, 'a+') as conf:
		conf.write(name + ' = ' + 'address')
	conf.close()


# -------------------------------- Procedural Code --------------------------------
try:
	process_arguments()

	servers = parseConfig()

	if args.addserver:
		avalon.info('Adding new server to server list')
		serverName = avalon.gets('Server Name: ')
		serverAddr = avalon.gets('Server Address: ')
		addServer(serverName, serverAddr)
		avalon.info('Writing succeeded!')
		avalon.info('Please relaunch the program')
		exit(0)

	serverIP = selectServer()

	hash = get_hash()
	hash = base64.b64decode(hash.encode('utf-8')).decode('utf-8')

	if args.port:
		port = args.port
	else:
		port = get_port(hash) + get_port(meha(hash, SEED))
Exemplo n.º 10
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
Exemplo n.º 11
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()
Exemplo n.º 12
0
        This method sets the servo to a certain
        angle whereL
        MAX = 90 deg
        MIN = -90 deg
        Neutral = 0 deg (horizon)

        This method is designed to take an input
        of an angle of the dgree above horizon,
        aka the elevation.
        """
        angle *= -1
        angle += 90
        self._setup()
        self.p.start(self._convert_angle(angle))
        time.sleep(1)
        self.p.stop()


# --------------------------------- Begin Self Testing
"""
The code below is for self-testing when this file
is ran independently. It takes an angle and sets
the servo to that angle.
"""

if __name__ == "__main__":
    servo = Servo(16)  # Using pin 16 (BOARD)
    while True:
        servo.set_angle(float(avl.gets("Angle")))
Exemplo n.º 13
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()