Esempio n. 1
0
    def __init__(self, device_id):
        self.logger = Utils.create_logger("certificate")

        self.jwt = RedisClient().get_jwt()

        self.c_name = device_id
        self.key = {"pem": self.generate_private_key()}
        self.csr = {"pem": self.generate_csr()}
        self.crt = {}
        self.crt["fingerprint"], self.crt["pem"] = self.generate_certificate()
Esempio n. 2
0
    def __init__(self, device_id: str, run_id: str, should_revoke: bool,
                 should_renew: bool):
        """
        MQTT client constructor. To get this to work, you should call setup() after instantiating
        the class.

        Args:
            device_id: device identifier
            run_id: client run identifier
            should_revoke: whether this client should have its certificate revoked
            should_renew: whether this client should have its certificate renewed
        """
        self.logger = Utils.create_logger("mqtt_client")

        Utils.validate_tenant(CONFIG["app"]["tenant"])
        Utils.validate_device_id(device_id)

        if len(run_id) < 1:
            raise ValueError("the run ID must have at least one character")

        if should_renew and should_revoke:
            raise ValueError(
                "only one of should_renew and should_revoke can be True")

        self.device_id = device_id
        self.run_id = run_id
        self.should_revoke = should_revoke
        self.should_renew = should_renew
        self.is_renewed = False
        self.is_revoked = False

        self.is_connected = False
        # If this variable is set, the on_disconnect callback will not try to reconnect
        # the device again
        self.disconnect_forever = False
        self.mqttc = None

        self.tenant = CONFIG["app"]["tenant"]
        self.username = '******'.format(self.tenant, self.device_id)
        self.topic = "{0}/attrs".format(self.username)
        self.sub_topic = "{0}/config".format(self.username)

        self.device_cert_dir = CONFIG["security"]["cert_dir"]
        self.new_cert = None

        self.pubmmap = {}
        self.submmap = {}

        # Used to count the time between connection and revocation/renovation
        self.start_time = 0

        self.create_certificate()
        self.configure_mqtt()
Esempio n. 3
0
    def __init__(self) -> None:
        """
        Attempts to stablish a connection.
        """
        self.logger = Utils.create_logger("redis_client")

        try:
            self.certificates = redis.Redis(
                host=CONFIG['locust']['redis']['host'],
                port=CONFIG['locust']['redis']['port'],
                db=CONFIG['locust']['redis']['certificates_db'])
            self.mapped = redis.Redis(
                host=CONFIG['locust']['redis']['host'],
                port=CONFIG['locust']['redis']['port'],
                db=CONFIG['locust']['redis']['mapped_db'])

        except Exception as exception:
            self.logger.error(str(exception))
            raise
Esempio n. 4
0
    def test_create_logger(self, mock_os_env_get, mock_formatter,
                           mock_stream_handler, mock_get_logger):
        """
        create_logger() should create a logger with the supplied name.
        """
        mock_os_env_get.get.return_value = "info"

        logger_name = "test_logger"
        logger = Utils.create_logger(name=logger_name)

        mock_get_logger.assert_called_with(logger_name)
        mock_stream_handler.assert_called_once()
        mock_formatter.assert_called_once()

        self.assertTrue(logger.hasHandlers())

        mock_os_env_get.reset_mock()
        mock_formatter.reset_mock()
        mock_stream_handler.reset_mock()
        mock_get_logger.reset_mock()
Esempio n. 5
0
from multiprocessing import Process
import time
import uuid
import shutil
import sys
import os
import redis
from typing import List, Tuple
import requests

from src.ejbca.thing import Thing
from src.config import CONFIG
from src.utils import Utils
from src.dojot.api import DojotAPI

LOGGER = Utils.create_logger("generate_cert")


class GenerateCerts():
    """
    Certificate and Dojot certificate/device manager.
    """
    def __init__(self):
        """
        Creates the parsers and subparsers.
        """
        parser = argparse.ArgumentParser()

        # Creating subparsers
        subparsers = parser.add_subparsers(dest="topic")
Esempio n. 6
0
"""
API calls to Dojot.
"""
import json
from typing import Callable, List, Dict
import sys
import requests
import gevent

from src.config import CONFIG
from src.utils import Utils

LOGGER = Utils.create_logger("api")


class APICallError(Exception):
    """
    Error when trying to call Dojot API.
    """


class DojotAPI():
    """
    Utility class with API calls to Dojot.
    """
    @staticmethod
    def get_jwt() -> str:
        """
        Request a JWT token.
        """
        url = "{0}/auth".format(CONFIG['dojot']['url'])
Esempio n. 7
0
"""
Certificate utilities.
"""
import os
import requests

from src.config import CONFIG
from src.utils import Utils
from src.ejbca.thing import Thing
from src.mqtt_locust.redis_client import RedisClient

LOGGER = Utils.create_logger("cert_utils")


class CertUtils:
    """
    Handles certificate-related operations.
    """
    @staticmethod
    def get_private_key_file(device_id: str) -> str:
        """
        Creates the key filename.
        """
        Utils.validate_device_id(device_id)
        return "{0}.key".format(device_id)

    @staticmethod
    def get_certificate_file(device_id: str) -> str:
        """
        Creates the certificate filename.
        """