Пример #1
0
 def __init__(self, key_directory=None):
     self.scr = SystemConfigReader()
     ssc = SystemConfigReader()
     database_options = ssc.get_all_values_from_section('Database')
     self.__dbm = DatabaseManagerMongo(**database_options)
     self.ssw = SystemSettingsWriter(self.__dbm)
     self.key_directory = key_directory or SystemConfigReader.DEFAULT_CONFIG_LOCATION + "/keys"
Пример #2
0
    def update_db_version(self):
        # update version updater settings
        try:
            updater_settings_values = UpdaterModule.__DEFAULT_SETTINGS__
            ssr = SystemSettingsReader(self.setup_database_manager)
            try:
                updater_settings_values = ssr.get_all_values_from_section(
                    'updater')
                updater_setting_instance = UpdateSettings(
                    **updater_settings_values)
            except Exception:
                # create updater section if not exist
                system_setting_writer: SystemSettingsWriter = SystemSettingsWriter(
                    self.setup_database_manager)
                updater_setting_instance = UpdateSettings(
                    **updater_settings_values)
                system_setting_writer.write(
                    _id='updater', data=updater_setting_instance.__dict__)

            # start running update files
            updater_setting_instance.run_updates(
                updater_settings_values.get('version'), ssr)

        except Exception as err:
            self.status = UpdateRoutine.UpateStatus.ERROR
            raise RuntimeError(
                f'Something went wrong during the generation of the updater module. \n Error: {err}'
            )
Пример #3
0
 def increase_updater_version(self, value: int):
     ssr = SystemSettingsReader(self.database_manager)
     system_setting_writer: SystemSettingsWriter = SystemSettingsWriter(
         self.database_manager)
     updater_settings_values = ssr.get_all_values_from_section('updater')
     updater_setting_instance = UpdateSettings(**updater_settings_values)
     updater_setting_instance.version = value
     system_setting_writer.write(_id='updater',
                                 data=updater_setting_instance.__dict__)
Пример #4
0
class KeyGenerator:
    def __init__(self, key_directory=None):
        self.scr = SystemConfigReader()
        ssc = SystemConfigReader()
        database_options = ssc.get_all_values_from_section('Database')
        self.__dbm = DatabaseManagerMongo(**database_options)
        self.ssw = SystemSettingsWriter(self.__dbm)
        self.key_directory = key_directory or SystemConfigReader.DEFAULT_CONFIG_LOCATION + "/keys"

    def generate_rsa_keypair(self):
        from Crypto.PublicKey import RSA
        key = RSA.generate(2048)
        private_key = key.export_key()
        public_key = key.publickey().export_key()

        asymmetric_key = {'private': private_key, 'public': public_key}
        self.ssw.write('security', {'asymmetric_key': asymmetric_key})

    def generate_symmetric_aes_key(self):
        from Crypto import Random
        self.ssw.write('security',
                       {'symmetric_aes_key': Random.get_random_bytes(32)})
Пример #5
0
 def __init__(self, database_manager):
     self.ssr = SystemSettingsReader(database_manager)
     self.ssw = SystemSettingsWriter(database_manager)
     self.salt = "cmdb"
Пример #6
0
class SecurityManager:
    DEFAULT_BLOCK_SIZE = 32
    DEFAULT_ALG = 'HS512'
    DEFAULT_EXPIRES = int(10)

    def __init__(self, database_manager):
        self.ssr = SystemSettingsReader(database_manager)
        self.ssw = SystemSettingsWriter(database_manager)
        self.salt = "cmdb"

    def generate_hmac(self, data):
        import hashlib
        import hmac

        generated_hash = hmac.new(self.get_symmetric_aes_key(),
                                  bytes(data + self.salt, 'utf-8'),
                                  hashlib.sha256)

        generated_hash.hexdigest()

        return base64.b64encode(generated_hash.digest()).decode("utf-8")

    def encrypt_aes(self, raw):
        """
        see https://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256
        :param raw: unencrypted data
        :return:
        """
        if type(raw) == list:
            import json
            from bson import json_util
            raw = json.dumps(raw, default=json_util.default)
        raw = SecurityManager._pad(raw).encode('UTF-8')
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.get_symmetric_aes_key(), AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw))

    def decrypt_aes(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.get_symmetric_aes_key(), AES.MODE_CBC, iv)
        return SecurityManager._unpad(cipher.decrypt(
            enc[AES.block_size:])).decode('utf-8')

    @staticmethod
    def _pad(s):
        return s + (SecurityManager.DEFAULT_BLOCK_SIZE - len(s) % SecurityManager.DEFAULT_BLOCK_SIZE) * \
               chr(SecurityManager.DEFAULT_BLOCK_SIZE - len(s) % SecurityManager.DEFAULT_BLOCK_SIZE)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s) - 1:])]

    def generate_symmetric_aes_key(self):
        return self.ssw.write(
            'security', {'symmetric_aes_key': Random.get_random_bytes(32)})

    def get_symmetric_aes_key(self):
        try:
            symmetric_key = self.ssr.get_value('symmetric_aes_key', 'security')
        except NoDocumentFound:
            self.generate_symmetric_aes_key()
            symmetric_key = self.ssr.get_value('symmetric_aes_key', 'security')
        return symmetric_key

    @staticmethod
    def encode_object_base_64(data: object):
        from bson.json_util import dumps
        return base64.b64encode(dumps(data).encode('utf-8')).decode("utf-8")
Пример #7
0
    def setup(self) -> SetupStatus:
        LOGGER.info('SETUP ROUTINE: STARTED...')
        self.status = SetupRoutine.SetupStatus.RUNNING

        # check database
        if not self.__check_database():
            self.status = SetupRoutine.SetupStatus.ERROR
            raise RuntimeError(
                'The database managers could not be initialized. Perhaps the database cannot be reached, \
                or the database was already initialized.')

        if self.__is_database_empty():
            # init database
            try:
                self.__init_database()
            except Exception as err:
                self.status = SetupRoutine.SetupStatus.ERROR
                raise RuntimeError(
                    f'Something went wrong during the initialization of the database. \n Error: {err}'
                )

            # generate keys
            LOGGER.info('SETUP ROUTINE: Generate rsa key pair')

            try:
                self.init_keys()
            except Exception as err:
                self.status = SetupRoutine.SetupStatus.ERROR
                raise RuntimeError(
                    f'Something went wrong during the generation of the rsa keypair. \n Error: {err}'
                )

            # create user management
            LOGGER.info('SETUP ROUTINE: UserModel management')
            try:
                self.__create_user_management()
            except Exception as err:
                self.status = SetupRoutine.SetupStatus.ERROR
                raise RuntimeError(
                    f'Something went wrong during the generation of the user management. \n Error: {err}'
                )

            # create version updater settings
            try:
                from cmdb.updater import UpdaterModule
                from cmdb.updater.updater_settings import UpdateSettings
                from cmdb.utils.system_reader import SystemSettingsReader
                from cmdb.utils.system_writer import SystemSettingsWriter
                system_setting_writer: SystemSettingsWriter = SystemSettingsWriter(
                    self.setup_database_manager)

                updater_setting_instance = UpdateSettings(
                    **UpdaterModule.get_last_version())
                system_setting_writer.write(
                    _id='updater', data=updater_setting_instance.__dict__)
            except Exception as err:
                self.status = SetupRoutine.SetupStatus.ERROR
                raise RuntimeError(
                    f'Something went wrong during the generation of the updater module. \n Error: {err}'
                )

        self.status = SetupRoutine.SetupStatus.FINISHED
        LOGGER.info('SETUP ROUTINE: FINISHED!')
        return self.status
Пример #8
0
from cmdb.utils.system_reader import SystemSettingsReader
from cmdb.utils.system_writer import SystemSettingsWriter

try:
    from cmdb.utils.error import CMDBError
except ImportError:
    CMDBError = Exception

auth_blueprint = RootBlueprint('auth_rest', __name__, url_prefix='/auth')
LOGGER = logging.getLogger(__name__)

with current_app.app_context():
    user_manager: UserManager = current_app.user_manager
    system_settings_reader: SystemSettingsReader = SystemSettingsReader(
        current_app.database_manager)
    system_setting_writer: SystemSettingsWriter = SystemSettingsWriter(
        current_app.database_manager)


@auth_blueprint.route('/settings/', methods=['GET'])
@auth_blueprint.route('/settings', methods=['GET'])
@login_required
@insert_request_user
@right_required('base.system.view')
def get_auth_settings(request_user: User):
    auth_module = AuthModule(system_settings_reader)
    return make_response(auth_module.settings)


@auth_blueprint.route('/settings/', methods=['POST', 'PUT'])
@auth_blueprint.route('/settings', methods=['POST', 'PUT'])
@login_required