示例#1
0
class TestTinyproxy(unittest.TestCase):

    def setUp(self):
        self.mm = ModuleManager()
        self.mm.load()
        self.mm['tinyproxy'].check()

    def test_tinyproxy(self):
        proxy_ip = '172.16.3.175'
        domain_name = 'proxy.test'
        error, new_proxy_id = self.mm['tinyproxy'].run("add_server", ip_addr=proxy_ip, fqdn=domain_name)
        self.assertTrue(error == None, msg=error)

        time.sleep(5)

        proxies = {
            'http': 'http://{}:8080'.format(proxy_ip),
            'https': 'http://{}:8080'.format(proxy_ip),
        }

        res = requests.get("http://httpforever.com/", proxies=proxies)
        self.assertTrue(res.status_code == 200, msg="{}: \n{}".format(res.status_code, res.text))

        res = requests.get("https://google.com/", proxies=proxies)
        self.assertTrue(res.status_code == 200, msg="{}: \n{}".format(res.status_code, res.text))

        error, _ = self.mm['tinyproxy'].run("remove_server", id=new_proxy_id)
        self.assertTrue(error is None, msg=error)
示例#2
0
    def load_mm(self):
        

        if TEST_WEB_VAR in os.environ and os.environ[TEST_WEB_VAR] != "":
            self.mm = ModuleManager(ip=os.environ[TEST_WEB_VAR])
        else:
            self.mm = ModuleManager()
        self.mm.load()
        self.mm[self.module_name].check()
示例#3
0
    def setUp(self):
        # Clean the slate!
        remove_all_docker()
        remove_all_lxd()
        clean_ovs()
        remove_all_ovs()
        remove_db()

        self.mm = ModuleManager()
        self.mm.load()
示例#4
0
class TestNetworkHop(unittest.TestCase):
    def setUp(self):
        self.mm = ModuleManager()
        self.mm.load()
        self.mm['nethop'].check()

    def test_add_nethop(self):
        error, result = self.mm['nethop'].run("add_network_hop",
                                              front_ip='172.16.3.150',
                                              fqdn='net2.test',
                                              net_addr='192.168.200.0/24',
                                              switch='testnet1',
                                              description='test')
        self.assertTrue(error == None, msg=error)

        error, result = self.mm['nethop'].run("add_network_hop",
                                              front_ip='192.168.200.10',
                                              fqdn='net3.test',
                                              net_addr='192.168.100.0/24',
                                              switch='testnet2',
                                              description='test2')
        self.assertTrue(error == None, msg=error)

        # Wait for RIP to settle
        time.sleep(45)

        traceroute = subprocess.check_output(
            ["/usr/sbin/traceroute", '-n', '192.168.100.1']).decode().strip()

        traceroute_split = traceroute.split("\n")

        self.assertTrue(len(traceroute_split) == 3, msg=str(traceroute_split))

        error, cont_id = self.mm['lxd'].run("add_container",
                                            ip_addr='192.168.100.100',
                                            fqdn='lxd-hop.test',
                                            template='ubuntu_1804_base',
                                            password='******')
        self.assertTrue(error == None, msg=error)

        subprocess.check_output(["/bin/ping", '-c', '2', '192.168.100.100'])

        traceroute = subprocess.check_output(
            ["/usr/sbin/traceroute", '-n',
             '192.168.100.100']).decode().strip()

        traceroute_split = traceroute.split("\n")

        self.assertTrue(len(traceroute_split) == 4, msg=str(traceroute_split))

        error, result = self.mm['lxd'].run("remove_container", id=cont_id)
        self.assertTrue(error == None, msg=error)
示例#5
0
class ModuleTestBase():

    module_name = "INVALID"

    def load_mm(self):
        

        if TEST_WEB_VAR in os.environ and os.environ[TEST_WEB_VAR] != "":
            self.mm = ModuleManager(ip=os.environ[TEST_WEB_VAR])
        else:
            self.mm = ModuleManager()
        self.mm.load()
        self.mm[self.module_name].check()

    def do_test_basic_functionality(self, server_id):
        raise NotImplementedError

    def create_server(self):
        raise NotImplementedError

    def remove_server(self, server_id):
        raise NotImplementedError

    def stop_server(self, server_id):
        raise NotImplementedError

    def test_basic_functionality(self):
        server_id = self.create_server()
        data = self.mm[self.module_name].get_list()
        found = False
        for item in data:
            self.assertTrue(item[0] == self.module_name)
            self.assertTrue(len(item) == 5, msg=item)
            if item[1] == server_id:
                found = True

        self.assertTrue(found)

        self.do_test_basic_functionality(server_id)
        self.remove_server(server_id)

    def test_save_restore(self):
        server_id = self.create_server()
        self.do_test_basic_functionality(server_id)
        save_data = self.mm[self.module_name].save()
        self.stop_server(server_id)
        self.mm[self.module_name].restore(save_data)
        self.do_test_basic_functionality(server_id)
        self.remove_server(server_id)
示例#6
0
def create_app():
    app = Flask(__name__)
    app.secret_key = 'aasdfasfd'

    with app.app_context():
        current_app.db = sqlite3.connect('fakernet.db')
        current_app.mm = ModuleManager(db=current_app.db)
        current_app.mm.load()

        fileLog = logging.FileHandler("./logs/fakernet-server.log")
        formatter = logging.Formatter(
            '%(asctime)s %(levelname)s SERVER : %(message)s')
        fileLog.setFormatter(formatter)

        app.logger.addHandler(fileLog)
        app.logger.setLevel(logging.INFO)

        current_app.mm['init'].check()
        if current_app.mm['init'].init_needed:
            error_message = "FakerNet is not yet configured. Please run `fnconsole` first to configure your setup."
            print(error_message)
            app.logger.error(error_message)
            sys.exit()

        app.logger.info("Restoring services")
        error, _ = current_app.mm.restore_state(save_name="default")
        if error is not None:
            print(error)
            app.logger.error(error)
            sys.exit(1)

        app.logger.info("Server started")

    return app
示例#7
0
class TestBasics(unittest.TestCase):
    def setUp(self):
        # Clean the slate!
        remove_all_docker()
        remove_all_lxd()
        clean_ovs()
        remove_all_ovs()
        remove_db()

        self.mm = ModuleManager()
        self.mm.load()

    def test_build_base(self):
        self.mm['netreserve'].check()
        error, result = self.mm['netreserve'].run("add_network",
                                                  description="test_network",
                                                  net_addr="172.16.3.0/24",
                                                  switch="testnet0")
        self.assertTrue(error == None)

        self.mm['dns'].check()
        error, result = self.mm['dns'].run("add_server",
                                           ip_addr=TEST_DNS_ROOT,
                                           description="test_dns",
                                           domain="test")
        self.assertTrue(error == None)
        error, result = self.mm['dns'].run("add_zone",
                                           id=1,
                                           direction="fwd",
                                           zone="test")
        self.assertTrue(error == None)
        error, result = self.mm['dns'].run("add_forwarder",
                                           id=1,
                                           ip_addr="8.8.8.8")
        self.assertTrue(error == None)

        self.mm['minica'].check()
        error, result = self.mm['minica'].run("add_server",
                                              fqdn="ca.test",
                                              ip_addr="172.16.3.3")
        self.assertTrue(error == None)

        return True

    def tearDown(self):
        pass
示例#8
0
class TestMiniCA(unittest.TestCase):

    def setUp(self):
        self.mm = ModuleManager()
        self.mm.load()
        self.mm['minica'].check()

    def test_minica(self):
        time.sleep(5)
        error, cert_data = self.mm['minica'].run("generate_host_cert", id=1, fqdn="test.test")
        priv_key = cert_data[0]
        cert = cert_data[1]
        
        self.assertTrue(error == None, msg=error)

        outcert = open("/tmp/testcrt.pem", "w+")
        outcert.write(cert)
        outcert.close()

        outcert = open("/tmp/testkey.pem", "w+")
        outcert.write(priv_key)
        outcert.close()

        subprocess.run(["/usr/bin/openssl", "verify", "-CAfile", TEST_CA_PATH, "/tmp/testcrt.pem"])
示例#9
0
class TestExternal(unittest.TestCase):
    def setUp(self):
        self.mm = ModuleManager()
        self.mm.load()
        self.mm['external'].check()

    def test_external_empty(self):
        # Test adding host before adding a network
        error, result = self.mm['external'].run("add_external_host",
                                                fqdn="whoops.test",
                                                ip_addr="192.168.20.2",
                                                host_desc="Test")
        self.assertFalse(error == None, msg=result)

        # Test removing non-existant host
        error, result = self.mm['external'].run("remove_external_host", id=200)
        self.assertFalse(error == None, msg=result)

        # # Test removing non-existant host
        error, result = self.mm['external'].run("remove_external_network",
                                                id=200)
        self.assertFalse(error == None, msg=result)

    def test_external(self):

        # Test empty
        error, host_list = self.mm['external'].run("list_hosts")
        self.assertTrue(error == None, msg=error)
        self.assertTrue(len(host_list['rows']) == 0)
        self.assertTrue(len(host_list['columns']) == 4)
        self.assertTrue("ID" in host_list['columns'])

        error, net_list = self.mm['external'].run("list_networks")
        self.assertTrue(error == None, msg=error)
        self.assertTrue(len(net_list['rows']) == 0)
        self.assertTrue(len(net_list['columns']) == 3)
        self.assertTrue("ID" in net_list['columns'])

        error, network_id = self.mm['external'].run(
            "add_external_network",
            net_addr="10.10.20.0/24",
            description="Test External Network")
        self.assertTrue(error == None, msg=error)

        error, host_id = self.mm['external'].run("add_external_host",
                                                 ip_addr="10.10.20.2",
                                                 host_desc="Test",
                                                 fqdn="external1.test")
        self.assertTrue(error == None, msg=error)

        error, host_list = self.mm['external'].run("list_hosts")
        self.assertTrue(error == None, msg=error)
        self.assertTrue(len(host_list['rows']) == 1)
        self.assertTrue("ID" in host_list['columns'])
        self.assertTrue(len(host_list['columns']) == 4)
        self.assertTrue(len(host_list['rows'][0]) == 4)
        self.assertTrue(host_list['rows'][0][0] == host_id,
                        msg=str(host_list['rows']))

        error, net_list = self.mm['external'].run("list_networks")
        self.assertTrue(error == None, msg=error)
        self.assertTrue(len(net_list['rows']) == 1)
        self.assertTrue("ID" in net_list['columns'])
        self.assertTrue(len(net_list['columns']) == 3)
        self.assertTrue(len(net_list['rows'][0]) == 3,
                        msg=str(net_list['rows']))
        self.assertTrue(net_list['rows'][0][0] == network_id,
                        msg=str(net_list['rows']))

        error, network_id2 = self.mm['external'].run(
            "add_external_network",
            net_addr="10.10.30.0/24",
            description="Test External Network 2")
        self.assertTrue(error == None, msg=error)

        error, host_id2 = self.mm['external'].run("add_external_host",
                                                  ip_addr="10.10.30.2",
                                                  host_desc="Test",
                                                  fqdn="external2.test")
        self.assertTrue(error == None, msg=error)

        error, _ = self.mm['external'].run("remove_external_host", id=host_id2)
        self.assertTrue(error == None, msg=error)

        error, _ = self.mm['external'].run("remove_external_network",
                                           id=network_id2)
        self.assertTrue(error == None, msg=error)

        error, _ = self.mm['external'].run("remove_external_host", id=host_id)
        self.assertTrue(error == None, msg=error)

        error, _ = self.mm['external'].run("remove_external_network",
                                           id=network_id)
        self.assertTrue(error == None, msg=error)

        # Test empty
        error, host_list = self.mm['external'].run("list_hosts")
        self.assertTrue(error == None, msg=error)
        self.assertTrue(len(host_list['rows']) == 0)
        self.assertTrue("ID" in host_list['columns'])

        error, net_list = self.mm['external'].run("list_networks")
        self.assertTrue(error == None, msg=error)
        self.assertTrue(len(net_list['rows']) == 0)
        self.assertTrue("ID" in net_list['columns'])
示例#10
0
 def setUp(self):
     self.mm = ModuleManager()
     self.mm.load()
     self.mm['tinyproxy'].check()
示例#11
0
import sys
import os

parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parentdir)

from lib.module_manager import ModuleManager
import lib.validate

manager = ModuleManager()
manager.load()

manager['minica'].check()
error, result = manager['minica'].run("remove_server", id=1)
print(error, result)

manager['dns'].check()
error, result = manager['dns'].run("remove_server", id=1)
print(error, result)
示例#12
0
import sys

from lib.module_manager import ModuleManager

if __name__ == "__main__":
    manager = ModuleManager()
    manager.load()

    if len(sys.argv) > 1:
        module_name = sys.argv[1]
        if module_name not in manager.list_modules():
            print("Invalid module")
            sys.exit(1)
        else:
            print("Trying to build {}".format(module_name))
            manager[module_name].build()
            print("Building complete!")
    else:
        print("Building all modules")
        manager.build_all()
        print("Building complete!")
 def setUp(self):
     self.mm = ModuleManager()
     self.mm.load()
     self.mm['netreserve'].check()
class TestNetworkReservation(unittest.TestCase):
    def setUp(self):
        self.mm = ModuleManager()
        self.mm.load()
        self.mm['netreserve'].check()

    def test_network_list(self):
        error, result = self.mm['netreserve'].run("list")
        self.assertTrue(error == None)
        self.assertTrue(len(result['columns']) == 5)
        # We are expecting at least the one network from initialization
        self.assertTrue(len(result['rows'][0]) == 5)

    def test_add_remove_network(self):
        bridge_1 = "testnet1"
        bridge_2 = "testnet2"
        error, result_id = self.mm['netreserve'].run(
            "add_network",
            description="Temp test network",
            net_addr="172.16.4.0/24",
            switch=bridge_1)
        self.assertTrue(error == None)
        error, _ = self.mm['netreserve'].run("add_network",
                                             description="Temp test network 2",
                                             net_addr="172.16.4.0/24",
                                             switch=bridge_2)
        self.assertFalse(error == None)
        error, _ = self.mm['netreserve'].run("add_network",
                                             description="Temp test network",
                                             net_addr="172.16.5.0/24",
                                             switch=bridge_1)
        self.assertFalse(error == None)
        error, result_id_2 = self.mm['netreserve'].run(
            "add_network",
            description="Temp test network 2",
            net_addr="172.16.5.0/24",
            switch=bridge_2)
        self.assertTrue(error == None)

        output = subprocess.check_output([
            "/usr/bin/sudo", "/usr/bin/ovs-vsctl", "-f", "json", "list",
            "bridge"
        ]).decode()
        bridge_list = json.loads(output)
        bridge_data = convert_ovs_table(bridge_list)

        found_1 = False
        found_2 = False
        for bridge in bridge_data:
            if bridge['name'] == bridge_1:
                found_1 = True
            elif bridge['name'] == bridge_2:
                found_2 = True

        self.assertTrue(found_1)
        self.assertTrue(found_2)

        error, _ = self.mm['netreserve'].run("remove_network", id=result_id)
        self.assertTrue(error == None, msg=error)
        error, _ = self.mm['netreserve'].run("remove_network", id=result_id_2)
        self.assertTrue(error == None, msg=error)

    def test_add_remove_network_blank(self):
        error, result_id = self.mm['netreserve'].run(
            "add_network",
            description="Temp test network",
            net_addr="172.16.5.0/24",
            switch="")
        self.assertTrue(error == None, msg=error)
        error, result_id_2 = self.mm['netreserve'].run(
            "add_network",
            description="Temp test network 2",
            net_addr="172.16.6.0/24",
            switch="")
        self.assertTrue(error == None, msg=error)

        error, _ = self.mm['netreserve'].run("remove_network", id=result_id)
        self.assertTrue(error == None, msg=error)
        error, _ = self.mm['netreserve'].run("remove_network", id=result_id_2)
        self.assertTrue(error == None, msg=error)

    def tearDown(self):
        pass
示例#15
0
 def setUp(self):
     self.mm = ModuleManager()
     self.mm.load()
     self.mm['external'].check()
示例#16
0
class TestDNS(unittest.TestCase):

    def setUp(self):
        self.mm = ModuleManager()
        self.mm.load()
        self.mm['dns'].check()

    def test_dns_list(self):
        error, result = self.mm['dns'].run("list")
        self.assertTrue(error == None)
        self.assertTrue(len(result['columns']) == 6)
        # We are expecting at least the one network from initialization
        self.assertTrue(len(result['rows'][0]) == 6)

    def test_dns_basic(self):
        error, _ = self.mm['dns'].run("add_host", fqdn="host1.test", ip_addr='172.16.3.20')
        self.assertTrue(error == None, msg=error)

        root_resolver = dns.resolver.Resolver()
        root_resolver.nameservers = [TEST_DNS_ROOT]

        answers = root_resolver.query('ns1.test', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue(TEST_DNS_ROOT == item.to_text(), msg=item)
            
        answers = root_resolver.query('host1.test', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue('172.16.3.20' == item.to_text(), msg=item)

        error, _ = self.mm['dns'].run("remove_host", fqdn="host1.test", ip_addr='172.16.3.20')
        self.assertTrue(error == None, msg=error)

        try:
            answers = root_resolver.query('host1.test', 'A')
            self.fail()
        except dns.resolver.NXDOMAIN: 
            pass
        except dns.exception.Timeout:
            pass

    def test_dns_external_subdomain(self):

        SECOND_IP = '172.16.3.41'

        error, _ = self.mm['dns'].run("smart_add_external_subdomain", fqdn="subdomain.test", ip_addr=SECOND_IP)
        self.assertTrue(error == None, msg=error)

        error, server_id = self.mm['dns'].run("add_server", ip_addr=SECOND_IP, description="test_dns2", domain="subdomain.test")
        self.assertTrue(error == None)
        error, result = self.mm['dns'].run("add_zone", id=server_id, direction="fwd", zone="subdomain.test")
        self.assertTrue(error == None)
        error, result = self.mm['dns'].run("add_forwarder", id=server_id, ip_addr=TEST_DNS_ROOT)
        self.assertTrue(error == None)

        time.sleep(20)

        root_resolver = dns.resolver.Resolver()
        root_resolver.nameservers = [TEST_DNS_ROOT]

        answers = root_resolver.query('ns1.subdomain.test', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue(SECOND_IP == item.to_text(), msg=item)

        error, _ = self.mm['dns'].run("remove_server", id=server_id)
        self.assertTrue(error == None)

        error, _ = self.mm['dns'].run("smart_remove_external_subdomain", fqdn="subdomain.test", ip_addr=SECOND_IP)
        self.assertTrue(error == None, msg=error)

        try:
            answers = root_resolver.query('subdomain.test', 'NS')
            self.fail()
        except dns.resolver.NXDOMAIN: 
            pass
        except dns.exception.Timeout:
            pass

    # @unittest.skip("long...")
    def test_dns_smart_subdomain(self):
        error, server_1_id = self.mm['dns'].run("smart_add_subdomain_server", fqdn="domain.test", ip_addr='172.16.3.10')
        self.assertTrue(error == None, msg=error)

        time.sleep(20)

        root_resolver = dns.resolver.Resolver()
        root_resolver.nameservers = [TEST_DNS_ROOT]
        root_resolver.timeout = 10.0
        root_resolver.lifetime = 10.0
        root_resolver.edns = True

        try:
            root_resolver.query('ns1.domain.test', 'A')
        except Exception as e:
            print(e)
            pass
        answers = root_resolver.query('ns1.domain.test', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue('172.16.3.10' == item.to_text(), msg=item)

        error, _ = self.mm['dns'].run("add_host", fqdn="host1.domain.test", ip_addr='172.16.3.200')
        self.assertTrue(error == None, msg=error)

        answers = root_resolver.query('host1.domain.test', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue('172.16.3.200' == item.to_text(), msg=item)

        error, server_2_id = self.mm['dns'].run("smart_add_subdomain_server", fqdn="subdomain.domain.test", ip_addr='172.16.3.11')
        self.assertTrue(error == None, msg=error)

        error, result = self.mm['dns'].run("add_host", fqdn="host1.subdomain.domain.test", ip_addr='172.16.3.201')
        self.assertTrue(error == None, msg=error)

        answers = root_resolver.query('host1.subdomain.domain.test', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue('172.16.3.201' == item.to_text(), msg=item)

        error, result = self.mm['dns'].run("smart_remove_subdomain_server", id=server_2_id)
        self.assertTrue(error == None, msg=error)

        try:
            answers = root_resolver.query('host1.subdomain.domain.test', 'A')
            self.fail()
        except:
            pass

        error, result = self.mm['dns'].run("smart_remove_subdomain_server", id=server_1_id)
        self.assertTrue(error == None, msg=error)

        try:
            answers = root_resolver.query('host1.domain.test', 'A')
            self.fail()
        except:
            pass

        try:
            answers = root_resolver.query('domain.test', 'NS')
            self.fail()
        except:
            pass

    # @unittest.skip("long...")
    def test_dns_smart_root(self):
        root_ip_addr = '172.16.3.12'
        error, server_1_id = self.mm['dns'].run("smart_add_root_server", root_name="com", ip_addr=root_ip_addr)
        self.assertTrue(error == None, msg=error)

        time.sleep(20)

        root_resolver = dns.resolver.Resolver()
        root_resolver.nameservers = [TEST_DNS_ROOT]

        answers = root_resolver.query('ns1.com', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue(root_ip_addr == item.to_text(), msg=item)

        error, result = self.mm['dns'].run("add_host", fqdn="host1.com", ip_addr='172.16.3.200')
        self.assertTrue(error == None, msg=error)

        answers = root_resolver.query('host1.com', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue('172.16.3.200' == item.to_text(), msg=item)

        error, server_2_id = self.mm['dns'].run("smart_add_subdomain_server", fqdn="domain.com", ip_addr='172.16.3.11')
        self.assertTrue(error == None, msg=error)

        error, result = self.mm['dns'].run("add_host", fqdn="host1.domain.com", ip_addr='172.16.3.201')
        self.assertTrue(error == None, msg=error)

        answers = root_resolver.query('host1.domain.com', 'A')
        self.assertTrue(answers is not None)
        for resp in answers.response.answer:
            for item in resp.items:
                self.assertTrue('172.16.3.201' == item.to_text(), msg=item)

        error, result = self.mm['dns'].run("smart_remove_subdomain_server", id=server_2_id)
        self.assertTrue(error == None, msg=error)

        try:
            answers = root_resolver.query('host1.domain.test', 'A')
            self.fail()
        except:
            pass

        error, result = self.mm['dns'].run("smart_remove_root_server", id=server_1_id)
        self.assertTrue(error == None, msg=error)

        try:
            answers = root_resolver.query('ns1.com', 'A')
            self.fail()
        except:
            pass
   

    def tearDown(self):
        pass
示例#17
0
    def __init__(self, ip="127.0.0.1"):

        wait = animation.Wait(text="Looking for local FakerNet server")
        wait.start()
        self.mm = ModuleManager(ip=ip)
        error = self.mm.load()
        wait.stop()
        if error is not None:
            self.mm = ModuleManager(ip=ip, https=True, https_ignore=True)
            error = self.mm.load()
            wait.stop()
            if error is not None:
                if ip == "127.0.0.1":
                    print_formatted_text(
                        HTML('\n\n<ansired>{}</ansired>'.format(error)))
                    wait = animation.Wait(text="FakerNet console is starting")
                    wait.start()
                    self.mm = ModuleManager()
                    self.mm.load()
                    wait.stop()

                    self.mm['init'].check()
                    self.host = "local"
                else:
                    print_formatted_text(
                        HTML(
                            '<ansired>Failed to connect to the server at {}</ansired>'
                            .format(ip)))
                    sys.exit(1)
            else:
                self.host = self.mm.ip
        else:
            self.host = self.mm.ip

        file_history = FileHistory(".fnhistory")
        self.session = PromptSession(history=file_history)
        self.global_vars = {"AUTO_ADD": False}

        self.completer = CommandCompleter(self.mm, self.global_vars)

        if self.mm.ip == None:
            err, _ = self.mm['init'].run("verify_permissions")
            if err is not None:
                print_formatted_text(HTML('<ansired>{}</ansired>'.format(err)))
                sys.exit(1)

        print_formatted_text(HTML(
            '<ansigreen>{}</ansigreen>'.format(ASCIIART)))
        print_formatted_text(HTML('<skyblue>Internet-in-a-box\n</skyblue>'))
        if self.mm.ip == None:
            print_formatted_text(
                HTML('<ansigreen>NOTE: In non-server mode!</ansigreen>'))
            if self.mm['init'].init_needed:
                self.setup_prompts()
        else:
            print_formatted_text(
                HTML('<ansigreen>Connected to {}</ansigreen>'.format(
                    self.mm.ip)))

        self.running = True
        self.current_command = None
        self.mm.logger.info("Started console")
示例#18
0
class FakerNetConsole():
    def __init__(self, ip="127.0.0.1"):

        wait = animation.Wait(text="Looking for local FakerNet server")
        wait.start()
        self.mm = ModuleManager(ip=ip)
        error = self.mm.load()
        wait.stop()
        if error is not None:
            self.mm = ModuleManager(ip=ip, https=True, https_ignore=True)
            error = self.mm.load()
            wait.stop()
            if error is not None:
                if ip == "127.0.0.1":
                    print_formatted_text(
                        HTML('\n\n<ansired>{}</ansired>'.format(error)))
                    wait = animation.Wait(text="FakerNet console is starting")
                    wait.start()
                    self.mm = ModuleManager()
                    self.mm.load()
                    wait.stop()

                    self.mm['init'].check()
                    self.host = "local"
                else:
                    print_formatted_text(
                        HTML(
                            '<ansired>Failed to connect to the server at {}</ansired>'
                            .format(ip)))
                    sys.exit(1)
            else:
                self.host = self.mm.ip
        else:
            self.host = self.mm.ip

        file_history = FileHistory(".fnhistory")
        self.session = PromptSession(history=file_history)
        self.global_vars = {"AUTO_ADD": False}

        self.completer = CommandCompleter(self.mm, self.global_vars)

        if self.mm.ip == None:
            err, _ = self.mm['init'].run("verify_permissions")
            if err is not None:
                print_formatted_text(HTML('<ansired>{}</ansired>'.format(err)))
                sys.exit(1)

        print_formatted_text(HTML(
            '<ansigreen>{}</ansigreen>'.format(ASCIIART)))
        print_formatted_text(HTML('<skyblue>Internet-in-a-box\n</skyblue>'))
        if self.mm.ip == None:
            print_formatted_text(
                HTML('<ansigreen>NOTE: In non-server mode!</ansigreen>'))
            if self.mm['init'].init_needed:
                self.setup_prompts()
        else:
            print_formatted_text(
                HTML('<ansigreen>Connected to {}</ansigreen>'.format(
                    self.mm.ip)))

        self.running = True
        self.current_command = None
        self.mm.logger.info("Started console")

    def setup_prompts(self):
        print_formatted_text(
            HTML(
                '<skyblue>Welcome to FakerNet. We need to setup the base of your fake internet.</skyblue>'
            ))

        base_net = None

        # Setup network
        premessage = "Please enter the initial network allocation. The main DNS server will be hosted here."
        ok = False
        while not ok:

            print_formatted_text(
                HTML('<slateblue>{}</slateblue>'.format(premessage)))
            base_net = prompt_builder.prompt_get_network(
                prompt_text="network>")

            err, _ = self.mm['netreserve'].run(
                "add_network",
                net_addr=base_net,
                description=
                "The central network for Fakernet. Hosts central DNS server and other critical services.",
                switch="fakernet0")
            if err is None:
                ok = True
            else:
                print_formatted_text(HTML('<ansired>{}</ansired>'.format(err)))

        # Setup DNS server

        dns_root = None

        ok = False
        while not ok:
            premessage = "Please enter the root name for the DNS server, this could be 'test', 'fake' or something else."
            print_formatted_text(
                HTML('<slateblue>{}</slateblue>'.format(premessage)))

            dns_root = prompt_builder.prompt_get_dns_name(
                prompt_text="dns name>")

            premessage = "Enter the IP of the main DNS server. This will be the main resolver for your FakerNet instance.\n\n(You will need to point all systems to this DNS server for things to work.)"
            print_formatted_text(
                HTML('<slateblue>{}</slateblue>'.format(premessage)))

            dns_ip = prompt_builder.prompt_get_ip_in_network(
                base_net, prompt_text="dns ip>")

            err, _ = self.mm['dns'].run(
                "add_server",
                ip_addr=dns_ip,
                description="FakerNet Main DNS Resolver",
                domain=dns_root)
            if err is None:
                ok = True
                err, _ = self.mm['dns'].run("add_zone",
                                            id=1,
                                            direction="fwd",
                                            zone=dns_root)
                if err is not None:
                    print_formatted_text(
                        HTML('<ansired>{}</ansired>'.format(err)))
                    ok = False

            else:
                print_formatted_text(HTML('<ansired>{}</ansired>'.format(err)))

        # Setup CA
        ok = False
        while not ok:
            premessage = "Please enter the IP of the main CA server. Services will auto-generate their certificates from here."
            print_formatted_text(
                HTML('<slateblue>{}</slateblue>'.format(premessage)))

            ca_ip = prompt_builder.prompt_get_ip_in_network(
                base_net, prompt_text="ca ip>")

            err, _ = self.mm['minica'].run("add_server",
                                           fqdn="ca." + dns_root,
                                           ip_addr=ca_ip)
            if err is None:
                ok = True
            else:
                print_formatted_text(HTML('<ansired>{}</ansired>'.format(err)))

        print_formatted_text(
            HTML('<ansigreen>{}</ansigreen>'.format("Setup complete!")))

    def print_result(self, error, result):
        if error is not None:
            print_formatted_text(
                HTML('<ansired>Error: {}</ansired>'.format(error)))
        else:
            if isinstance(result,
                          dict) and 'rows' in result and 'columns' in result:
                print_table(result['rows'], result['columns'])
            else:
                print_formatted_text(HTML('<ansigreen>OK</ansigreen>'))

    def run_module_function(self, module_name, function_name, args):
        error, result = self.mm[module_name].run(function_name, **args)
        self.print_result(error, result)

    def start(self):
        while self.running:
            try:
                prompt = self.host + '> '
                if self.current_command is not None:
                    self.completer.in_func_level = True
                    self.completer.run_options = self.current_command[
                        'function']
                    prompt = self.host + "(" + self.current_command[
                        'display_name'] + ')> '

                command_string = self.session.prompt(prompt,
                                                     completer=self.completer)

                command_split = []
                try:
                    command_split = shlex.split(command_string)
                except ValueError:
                    print_formatted_text(
                        HTML('<ansired>Invalid quotes or command</ansired>'))

                if len(command_split) > 0:
                    if self.current_command is not None:
                        self.func_level(command_split)
                    else:
                        self.main_level(command_split)

            except KeyboardInterrupt:
                self.running = False
            except EOFError:
                pass

    def main_level(self, command_input):
        command = command_input[0].lower()
        if command == "exit":
            self.running = False
        elif command == "run":
            self.command_run(command_input[1:])
        elif command == "global":
            pass
        elif command == "uglobal":
            pass
        elif command == "userls":
            error, users = self.mm.list_users()
            for user in users:
                print(" * " + user)
        elif command == "useradd":
            username = input("username> ")
            ok = False
            while not ok:
                password1 = getpass(prompt="password> ")
                password2 = getpass(prompt="password (again)> ")
                if password1 != password2:
                    print("Passwords do not match")
                else:
                    ok = True

            self.mm.add_user(username, password1)

        elif command == "list_all":
            error, server_list = self.mm.list_all_servers()
            if error is None:
                print_table(server_list,
                            ["Module", "ID", "IP", "Description", "status"])
            else:
                print_formatted_text(
                    HTML('<ansired>Error: "{}"</ansired>'.format(error)))
        elif command == "save":
            error = None
            if len(command_input) > 1:
                self.mm.save_state(save_name=command_input[1])
            else:
                self.mm.save_state()

            if error is None:
                print_formatted_text(HTML('<ansigreen>Save OK</ansigreen>'))
            else:
                print_formatted_text(
                    HTML('<ansired>Save Error: "{}"</ansired>'.format(error)))
        elif command == "restore":
            error = None
            if len(command_input) > 1:
                error, _ = self.mm.restore_state(save_name=command_input[1])
            else:
                error, _ = self.mm.restore_state()

            if error is None:
                print_formatted_text(HTML('<ansigreen>Restore OK</ansigreen>'))
            else:
                print_formatted_text(
                    HTML('<ansired>Restore Error: "{}"</ansired>'.format(
                        error)))
        else:
            print_formatted_text(
                HTML('<ansired>Error: Invalid command "{}"</ansired>'.format(
                    command)))

    def func_level(self, command_input):
        command = command_input[0].lower()
        if command == "exit":
            self.current_command = None
            self.completer.in_func_level = False
        elif command == "run":
            self.command_run(command_input[1:])
        elif command == "set":
            if len(command_input) < 3:
                print_formatted_text(
                    HTML('<ansiyellow>set VAR VALUE</ansiyellow>'))
                return

            var_name = command_input[1]
            value = command_input[2]

            if var_name not in self.current_command['function']:
                print_formatted_text(
                    HTML('<ansired>Error: Invalid variable "{}"</ansired>'.
                         format(var_name)))
                return

            self.current_command['vars'][var_name] = value
        elif command == "unset":
            if len(command_input) < 2:
                print_formatted_text(
                    HTML('<ansiyellow>unset VAR</ansiyellow>'))
                return

            var_name = command_input[1]

            if var_name not in self.current_command['function']:
                print_formatted_text(
                    HTML('<ansired>Error: Invalid variable "{}"</ansired>'.
                         format(var_name)))
                return

            del self.current_command['vars'][var_name]

        elif command == "show":
            if "_desc" in self.current_command['function']:
                print_formatted_text(
                    HTML('<ansigreen>{}</ansigreen>'.format(
                        self.current_command['function']['_desc'])))
            rows = []
            for variable in self.current_command['function']:
                if variable == "_desc":
                    continue
                if variable in self.current_command['vars']:
                    rows.append(
                        [variable, self.current_command['vars'][variable]])
                else:
                    rows.append([variable, "NULL"])
            print_table(rows, ["Variables", "Values"])
        elif command == "execute":
            for variable in self.current_command['function']:
                if variable == "_desc":
                    continue
                if variable not in self.current_command['vars']:
                    print_formatted_text(
                        HTML('<ansired>Error: Variable "{}" not set</ansired>'.
                             format(variable)))
                    return

            module_name = self.current_command['module_name']
            if module_name not in self.mm.list_modules():
                print_formatted_text(
                    HTML('<ansired>Error: Got invalid module "{}"</ansired>'.
                         format(module_name)))

            function_name = self.current_command['function_name']

            self.run_module_function(module_name, function_name,
                                     self.current_command['vars'])

        else:
            print_formatted_text(
                HTML('<ansired>Error: Invalid command "{}"</ansired>'.format(
                    command)))

    def command_run(self, args):
        if len(args) < 2:
            print_formatted_text(
                HTML('<ansiyellow>run MODULE FUNCTION</ansiyellow>'))
            return

        module_name = args[0]
        if module_name not in self.mm.list_modules():
            print_formatted_text(
                HTML('<ansired>Error: Invalid module "{}"</ansired>'.format(
                    module_name)))
            return

        module = self.mm[module_name]
        function = args[1]
        # Special function "help" lists all available functions
        if function == "help":
            rows = []
            for function in module.__FUNCS__.keys():
                description = ""
                if "_desc" in module.__FUNCS__[function]:
                    description = module.__FUNCS__[function]['_desc']
                rows.append([function, description])
            print_table(rows, ["Functions", "Descriptions"])
        elif function in module.__FUNCS__.keys():
            # If there are not parameters, just run the function
            if len(module.__FUNCS__[function]) == 0 or len(
                    module.__FUNCS__[function]
            ) == 1 and "_desc" in module.__FUNCS__[function]:
                error, result = module.run(function)
                if error is None:
                    if 'rows' in result and 'columns' in result:
                        print_table(result['rows'], result['columns'])
                else:
                    print_formatted_text(
                        HTML('<ansired>Error: {}</ansired>'.format(error)))
            else:
                show_name = module_name + '.' + function

                out = show_name
                if "_desc" in module.__FUNCS__[function]:
                    out += ": " + module.__FUNCS__[function]['_desc']

                print_formatted_text(
                    HTML('<ansigreen>{}</ansigreen>'.format(out)))
                self.current_command = {
                    "module_name": module_name,
                    "display_name": show_name,
                    "function_name": function,
                    "function": module.__FUNCS__[function],
                    "vars": {}
                }
        else:
            print_formatted_text(
                HTML('<ansired>Error: Invalid function "{}"</ansired>'.format(
                    function)))
示例#19
0
 def setUp(self):
     self.mm = ModuleManager()
     self.mm.load()
     self.mm['minica'].check()