Exemplo n.º 1
0
    def test_get_agent_id(self):
        """Testing method or function named get_agent_id."""
        # Test. Agent_id shouldn't change
        agent_name = random()
        expected = files.get_agent_id(agent_name, self.config)
        result = files.get_agent_id(agent_name, self.config)
        self.assertEqual(result, expected)

        # Delete the file, make sure a new ID is generated
        filename = files.agent_id_file(agent_name, self.config)
        os.remove(filename)
        _expected = files.get_agent_id(agent_name, self.config)
        _result = files.get_agent_id(agent_name, self.config)
        self.assertEqual(_result, _expected)
        self.assertNotEqual(expected, _expected)
    def __init__(self, agent_program, polling_interval):
        """Initialize the class.

        Args:
            agent_program: Name of agent program collecting the data
            polling_interval: Polling interval

        Returns:
            None

        Variables:
            self.data: List of TargetDataPoints objects created by polling
            self.valid: True if the object contains TargetDataPoints objects

        """
        # Initialize key variables
        self.agent_program = agent_program
        self.agent_hostname = socket.getfqdn()
        self.agent_timestamp = int(time() * 1000)
        self.data = []
        self.valid = False
        self.agent_polling_interval = polling_interval * 1000

        # Get the agent_id
        from .configuration import Config
        config = Config()
        self.agent_id = files.get_agent_id(agent_program, config)
Exemplo n.º 3
0
    def __init__(self, agent_name, directory=None):
        """Instantiate the class.

        Args:
            agent_name: Name of agent generating the private key
            directory: Alternative key storage directory

        Returns:
            None

        """
        # Initialize key variables
        config = configuration.Config()
        self._agent_name = agent_name

        # Use the agent_id as the email address because it is a unique
        # identifier across all agents. This allows multiple agents with the
        # same name to have indepenent sessions.
        self.email = files.get_agent_id(agent_name, config)

        # Associate directories
        if directory is None:
            # Store keys and keyrings in directories named after the agent.
            # If the same directory were universally used there could be
            # conflicts in cases where the API daemon and agents run on the
            # same server This eliminates this risk.
            keyring_directory = config.keyring_directory(agent_name)
            self._keys_directory = config.keys_directory(agent_name)
        else:
            keyring_directory = '{}{}.keyring'.format(directory, os.sep)
            self._keys_directory = directory
            files.mkdir(directory)
            files.mkdir(keyring_directory)

        # Initialize GPG object. Note: options=['--pinentry-mode=loopback']
        # ensures the passphrase can be entered via python and won't prompt
        # the user.
        self._gpg = gnupg.GPG(gnupghome=keyring_directory,
                              options=['--pinentry-mode=loopback'])

        # Import metadata for managing keys
        metadata = self._import()

        # Create and store metadata if nonexistent
        if metadata is None:
            metadata = self._generate(self.email)
            self._export(metadata)

        # Share passphrase
        self._passphrase = metadata.passphrase
        self._fingerprint = metadata.fingerprint

        # Get the public key ID
        self._public_keyid = self._get_public_keyid(metadata.fingerprint)
Exemplo n.º 4
0
    def test___init__(self):
        """Testing function __init__."""
        # Setup AgentPolledData variable
        agent_program = 'brown_bear'
        agent_hostname = socket.getfqdn()
        polling_interval = 20
        apd = AgentPolledData(agent_program, polling_interval)
        agent_id = files.get_agent_id(agent_program, self.config)

        # Test
        self.assertTrue(bool(apd.agent_timestamp))
        self.assertEqual(apd.agent_polling_interval, polling_interval * 1000)
        self.assertEqual(apd.agent_id, agent_id)
        self.assertEqual(apd.agent_program, agent_program)
        self.assertEqual(apd.agent_hostname, agent_hostname)
        self.assertFalse(apd.valid)
Exemplo n.º 5
0
    def test_pexport(self):
        """Testing function pexport."""
        # Initialize key variables
        config = configuration.BaseConfig()

        # Test
        for _, data_ in self.instances.items():
            # Get instance information
            instance = data_['instance']
            email = data_['email']
            fingerprint = instance.fingerprint(email)

            # Create a new instance
            new_agent = hashlib.md5('{}'.format(random()).encode()).hexdigest()
            new_email = files.get_agent_id(new_agent, config)
            new_directory = tempfile.mkdtemp()
            new_instance = encrypt.Encryption(new_agent, new_directory)
            new_public_key = new_instance.pexport()
            new_fingerprint = new_instance.fingerprint(new_email)

            # There should be only one public key
            public_key = instance.pexport()

            # Import public key
            instance.pimport(new_public_key)
            result = instance.pexport(new_fingerprint)

            # There should be a match
            self.assertEqual(new_public_key, result)
            self.assertNotEqual(result, public_key)

            # Test deletion of nonexistent fingerprint
            status = instance.pdelete('foo')
            self.assertFalse(status)

            # Test deletion of primary fingerprint
            status = instance.pdelete(fingerprint)
            self.assertFalse(status)

            # Test deletion of primary fingerprint
            status = instance.pdelete(new_fingerprint)
            self.assertTrue(status)
            result = instance.pexport(new_fingerprint)
            self.assertIsNone(result)

            # Delete directory
            shutil.rmtree(new_directory)
Exemplo n.º 6
0
def create_cache():
    """Testing method / function records."""
    # Initialize key variables
    config = ServerConfig()
    polling_interval = 20
    cache_directory = config.agent_cache_directory(PATTOO_API_AGENT_NAME)
    result = {
        'pattoo_agent_program': data.hashstring(str(random())),
        'pattoo_agent_polled_target': socket.getfqdn(),
        'pattoo_key': data.hashstring(str(random())),
        'pattoo_value': round(uniform(1, 100), 5),
        'pattoo_agent_hostname': socket.getfqdn()
    }

    # We want to make sure we get a different AgentID each time
    filename = files.agent_id_file(
        result['pattoo_agent_program'],
        config)
    if os.path.isfile(filename) is True:
        os.remove(filename)
    result['pattoo_agent_id'] = files.get_agent_id(
        result['pattoo_agent_program'],
        config)

    # Setup AgentPolledData
    apd = AgentPolledData(result['pattoo_agent_program'], polling_interval)

    # Initialize TargetDataPoints
    ddv = TargetDataPoints(result['pattoo_agent_hostname'])

    # Setup DataPoint
    data_type = DATA_INT
    variable = DataPoint(
        result['pattoo_key'], result['pattoo_value'], data_type=data_type)

    # Add data to TargetDataPoints
    ddv.add(variable)

    # Write data to cache
    apd.add(ddv)
    cache_dict = converter.posting_data_points(
        converter.agentdata_to_post(apd))
    cache_file = '{}{}cache_test.json'.format(cache_directory, os.sep)
    with open(cache_file, 'w') as _fp:
        json.dump(cache_dict, _fp)

    return result
Exemplo n.º 7
0
def _relay(url):
    """Relay data to pattoo server.

    Args:
        url: Pattoo spoked agent URL

    Returns:
        None

    """
    # Initialize key variables
    config = Config()
    agent_id = files.get_agent_id(PATTOO_AGENT_LINUX_HUBD, config)

    # Initialize key variables
    passive = PassiveAgent(PATTOO_AGENT_LINUX_HUBD, agent_id, url)
    passive.relay()
Exemplo n.º 8
0
    def setUp(self):
        """Run these steps before each test is performed."""
        # Initialize key variables
        config = configuration.BaseConfig()

        # Setup encryption instances
        self.instances = defaultdict(lambda: defaultdict(dict))

        directory = tempfile.mkdtemp()
        for item in range(2):
            agent = hashlib.md5('{}'.format(random()).encode()).hexdigest()
            email = files.get_agent_id(agent, config)
            self.instances[item]['directory'] = directory
            self.instances[item]['agent'] = agent
            self.instances[item]['email'] = email
            self.instances[item]['instance'] = encrypt.Encryption(
                agent, directory)