Beispiel #1
0
def seed_db():
    from core.models import Account,Server,ConnectionType
    local_c = ConnectionType(name='local',connection_class='local')
    local_c.save()
    local = Server(ip_address='127.0.0.1',name='localhost',connection_type_id=local_c.id)    
    local.save()
    act = Account(username='******',password='******',base_dir='/',server_id=local.id)
    act.save()
Beispiel #2
0
    def save(self, **kwargs):
        if len(ConfOssecServer.get_all()) == 0:
            self.name = "Ossec-Server"
            super().save(**kwargs)
            # generate a ssh key
            sshkey = SshKey(name="Ossec-Server-SSH",
                            file="~/.ssh/ossec-server_rsa")
            sshkey.save()
            # port ssh -> grep 'Port ' /etc/ssh/sshd_config | cut -f2  -d ' '
            process = subprocess.Popen(
                'grep "Port " /etc/ssh/sshd_config | cut -f2 -d " "',
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                universal_newlines=True,
                shell=True)
            outdata, errdata = process.communicate()
            try:
                port = int(outdata)
            except TypeError:
                port = 22
            server = Server(
                name="main-Ossec-server",
                host="127.0.0.1",
                remote_user=settings.OSSEC_REMOTE_USER,
                remote_port=port,
                os=OsSupported.objects.get(name=settings.OSSEC_REMOTE_OS),
                become=True,
                become_pass="",
                ssh_private_key_file=sshkey)
            server.save()
            ossec_server = OssecServer(
                name="Ossec-server",
                configuration=self,
                secure_deployment=True,
                installed=True,
                scheduled_check_enabled=True,
                scheduled_check_crontab=CrontabSchedule.objects.get(id=2),
                server=server)
            ossec_server.save()
            ip = self.external_ip
            with open(settings.BASE_DIR + "/ossec/ossec-conf-agent.xml") as f:
                conf_full_default = f.read()
            t = Template(conf_full_default)
            final_conf_default = t.render(ip=ip)
            with open(settings.BASE_DIR + "/ossec/ossec-conf-agent.xml",
                      'w') as f:
                f.write(final_conf_default)

            with open(settings.BASE_DIR +
                      "/ossec/preloaded-vars-agent.conf") as f:
                conf_install = f.read()
            t = Template(conf_install)
            final_conf_install = t.render(ip=ip)
            with open(settings.BASE_DIR + "/ossec/preloaded-vars-agent.conf",
                      'w') as f:
                f.write(final_conf_install)
        else:
            raise Exception("Only one Ossec server allowed")
Beispiel #3
0
def seed_db():
    from core.models import Account, Server, ConnectionType
    local_c = ConnectionType(name='local', connection_class='local')
    local_c.save()
    local = Server(ip_address='127.0.0.1',
                   name='localhost',
                   connection_type_id=local_c.id)
    local.save()
    act = Account(username='******',
                  password='******',
                  base_dir='/',
                  server_id=local.id)
    act.save()
Beispiel #4
0
 def test_create_deploy_rules_task(self):
     probe = Probe.get_by_id(1)
     create_deploy_rules_task(probe)
     periodic_task = PeriodicTask.objects.get(
         name=probe.name + '_deploy_rules_' +
         str(probe.scheduled_rules_deployment_crontab))
     self.assertEqual(periodic_task.task, 'core.tasks.deploy_rules')
     self.assertEqual(periodic_task.args,
                      str([
                          probe.name,
                      ]).replace("'", '"'))
     probe = Probe.objects.create(
         name="probe2",
         description="test",
         created_date="2017-09-23T21:00:53.094Z",
         secure_deployment=True,
         scheduled_check_enabled=True,
         scheduled_check_crontab=CrontabSchedule.objects.get(id=2),
         scheduled_rules_deployment_enabled=False,
         server=Server.get_by_id(1),
         installed=True)
     create_deploy_rules_task(probe)
     periodic_task = PeriodicTask.objects.get(
         name=probe.name + '_deploy_rules_' +
         str(CrontabSchedule.objects.get(id=4)))
     self.assertEqual(periodic_task.task, 'core.tasks.deploy_rules')
Beispiel #5
0
 def test_execute(self):
     server = Server.get_by_id(1)
     self.assertEqual(execute(server, {'test_hostame': "hostname"}, become=False),
                      {'test_hostame': 'test-travis'})
     self.assertEqual(execute(server, {'test_ok': "hostname 1>/dev/null"}, become=False),
                      {'test_ok': 'OK'})
     with self.assertRaises(Exception):
         execute(server, {'test_fail': "service ssh status"}, become=False)
Beispiel #6
0
 def test_connection(self):
     server = Server.get_by_id(1)
     client = connection(server)
     stdin, stdout, stderr = client.exec_command("hostname")
     self.assertEqual(stdout.channel.recv_exit_status(), 0)
     self.assertEqual(stdout.read().decode('utf-8'), 'test-travis\n')
     self.assertEqual(stderr.readlines(), [])
     client.close()
Beispiel #7
0
 def test_server(self):
     response = self.client.get('/api/v1/core/server/1/test_connection/')
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(response.data, {'status': True})
     server = Server.get_by_id(1)
     server.become = False
     server.save()
     response = self.client.get('/api/v1/core/server/1/test_connection/')
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(response.data, {'status': True})
Beispiel #8
0
 def test_execute_become(self):
     server = Server.get_by_id(1)
     self.assertEqual(execute(server, {'test_hostame': "hostname"}, become=True),
                      {'test_hostame': 'test-travis'})
     self.assertIn('ssh.service', execute(server, {'test_status': "service ssh status"}, become=True)['test_status'])
     server.become_pass = None
     server.save()
     with self.assertRaises(Exception):
         execute(server, {'test_hostame': "hostname"}, become=True)
     server.become = False
     server.save()
     with self.assertRaises(Exception):
         execute(server, {'test_hostame': "hostname"}, become=True)
     with self.assertRaises(Exception):
         execute_copy(server, src=settings.ROOT_DIR + '/LICENSE', dest='/tmp/LICENSE', become=True)
Beispiel #9
0
 def test_server(self):
     self.assertEqual(str(Server.get_by_id(1)),
                      ' - server.treussart.com, Os : debian')
     self.assertTrue(Server.get_by_id(1).test()['status'])
     self.assertTrue(Server.get_by_id(1).test_become()['status'])
     Server.objects.create(name="test",
                           host="test",
                           os=OsSupported.get_by_id(1),
                           remote_user="******",
                           remote_port=22,
                           become=True,
                           become_method="sudo",
                           become_user="******",
                           become_pass="******",
                           ssh_private_key_file=SshKey.objects.get(id=1))
     self.assertNotEqual(Server.get_by_id(2).become_pass, "not encrypted")
     self.assertGreater(len(Server.get_by_id(2).become_pass), 99)
     self.assertEqual(str(Server.get_by_id(2)), 'test - test, Os : debian')
     self.assertFalse(Server.get_by_id(2).test()['status'])
     self.assertFalse(Server.get_by_id(2).test_become()['status'])
     self.assertEqual(Server.get_by_id(3), None)
 def test_cve(self):
     all_check_cve = Checkcve.get_all()
     check_cve = Checkcve.get_by_id(1)
     self.assertEqual(len(all_check_cve), 1)
     self.assertFalse(check_cve.vulnerability_found)
     self.assertEqual(str(check_cve), "checkcve1  test")
     self.assertEqual(check_cve.type, "Checkcve")
     self.assertIn("<h2>cpe:/a:openssl:openssl:1.1.0</h2>",
                   check_cve.check_cve())
     checkcve_1 = Checkcve.objects.create(name='test 2',
                                          server=Server.get_by_id(1),
                                          whitelist=WhiteList.get_by_id(1),
                                          vulnerability_found=False,
                                          vulnerabilities=[])
     checkcve_1.softwares.add(Software.get_by_id(3))
     checkcve_1.save()
     self.assertIn("No CVE found !", checkcve_1.check_cve())
     checkcve_1.delete()
Beispiel #11
0
 def test_admin(self):
     response = self.client.get('/admin/core/server/', follow=True)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(len(Server.get_all()), 1)
     response = self.client.post('/admin/core/server/add/', {'name': 'test-server',
                                                             'host': 'test.com',
                                                             'os': '1',
                                                             'remote_user': '******',
                                                             'remote_port': 22,
                                                             'become_method': 'sudo',
                                                             'become_user': '******',
                                                             'become_pass': '******',
                                                             'become': True,
                                                             'ssh_private_key_file': '1',
                                                             },
                                 follow=True)
     self.assertEqual(response.status_code, 200)
     self.assertIn(' was added successfully', str(response.content))
     self.assertIn('Connection to the server Failed', str(response.content))
     self.assertNotEqual(Server.objects.get(name='test-server').become_pass, 'test')
     self.assertEqual(len(Server.get_all()), 2)
     Server.get_by_id(1).delete()
     self.assertEqual(len(Server.get_all()), 1)
     response = self.client.post('/admin/core/server/add/', {'name': 'test-server-ok',
                                                             'host': 'server.treussart.com',
                                                             'os': '1',
                                                             'remote_user': '******',
                                                             'remote_port': 33003,
                                                             'become_method': 'sudo',
                                                             'become_user': '******',
                                                             'become_pass': '******',
                                                             'become': False,
                                                             'ssh_private_key_file': '1',
                                                             },
                                 follow=True)
     self.assertEqual(response.status_code, 200)
     self.assertIn(' was added successfully', str(response.content))
     self.assertIn('Connection to the server OK', str(response.content))
     self.assertEqual(len(Server.get_all()), 2)
Beispiel #12
0
 def test_execute_copy_put_become(self):
     server = Server.get_by_id(1)
     result = execute_copy(server, src=settings.ROOT_DIR + '/LICENSE', dest='/tmp/LICENSE', become=True)
     self.assertEqual(result, {'copy': 'OK', 'mv': {'mv': 'OK'}})
Beispiel #13
0
 def test_execute_copy_put(self):
     server = Server.get_by_id(1)
     result = execute_copy(server, src=settings.ROOT_DIR + '/LICENSE', dest='LICENSE')
     self.assertEqual(result, {'copy': 'OK'})
     with self.assertRaises(Exception):
         execute_copy(server, src=settings.ROOT_DIR + '/LICENSE', dest='/')
Beispiel #14
0
def list(request, validated={}, *args, **kwargs):
    if request.method == 'GET':
        server = Server.objects.filter(
            name__contains=validated['match']).values('id', 'name')

        if validated['ip'] is not None:
            server = server.filter(ip=validated['ip'])

        if validated['port'] is not None:
            server = server.filter(port=validated['port'])

        limit = validated['limit']
        offset = validated['offset']
        server = server[offset:] if limit < 0 else server[offset:limit]

        return [s for s in server]
    elif request.method == 'PUT':
        try:
            ip = socket.gethostbyname(validated['ip'])
        except socket.gaierror as e:
            return _('Could not resolve host by domain ({0})').format(e), 500

        server = Server()
        server.port = validated['port']
        server.password = validated['password']
        server.ip = ip
        server.name = validated['name']
        server.game = validated['game']

        if validated['verify']:
            try:
                conn = RCONBase(server, timeout=3)
                conn.connect()
                conn.authenticate(timeout=3)
                conn.close()
            except valve.rcon.RCONTimeoutError:
                return _('Server timed out'), 500
            except valve.rcon.RCONAuthenticationError:
                return _('Could not authenticate with given password'), 500
            except ConnectionError as e:
                return _('Could not reach server ({0})').format(e), 500
            except TimeoutError as e:
                return _('Could not reach server ({0})').format(e), 500

        # we don't want to have a plain password, but we need to. RCON does not hash pwds
        server.password = validated['password']
        if 'mode' in validated:
            server.mode = validated['mode']

        server.save()

        return ['passed']