Example #1
0
    def secure(self, update_user=None):
        """Configure the Trove administrative user.
        Update an existing user if given.
        Create a new one using the default database credentials
        otherwise and drop the built-in user when finished.
        """
        LOG.info(_('Configuring Trove superuser.'))

        current_superuser = update_user or models.CassandraUser(
            self.default_superuser_name, self.default_superuser_password)

        if update_user:
            os_admin = models.CassandraUser(update_user.name,
                                            utils.generate_random_password())
            CassandraAdmin(current_superuser).alter_user_password(os_admin)
        else:
            os_admin = models.CassandraUser(self._ADMIN_USER,
                                            utils.generate_random_password())
            CassandraAdmin(current_superuser)._create_superuser(os_admin)
            CassandraAdmin(os_admin).drop_user(current_superuser)

        self.__create_cqlsh_config({
            self._CONF_AUTH_SEC: {
                self._CONF_USR_KEY: os_admin.name,
                self._CONF_PWD_KEY: os_admin.password
            }
        })

        # Update the internal status with the new user.
        self.status = CassandraAppStatus(os_admin)

        return os_admin
    def _create_replication_user(self, pwfile):
        """Create the replication user. Unfortunately, to be able to
        run pg_rewind, we need SUPERUSER, not just REPLICATION privilege
        """

        pw = utils.generate_random_password()
        operating_system.write_file(pwfile, pw, as_root=True)
        operating_system.chown(pwfile,
                               user=self.PGSQL_OWNER,
                               group=self.PGSQL_OWNER,
                               as_root=True)
        operating_system.chmod(pwfile,
                               FileMode.OCTAL_MODE("0600"),
                               as_root=True)

        # TODO(atomic77) Alter user is swallowing the replication
        # option for some reason -- enable this code when the
        # underlying issue is fixed
        # repl_user = models.PostgreSQLUser(name=REPL_USER,
        #                                  password=REPL_PW)
        # self._create_user(context=None, user=repl_user)
        # self.alter_user(None, repl_user, 'REPLICATION', 'LOGIN')
        pgutil.psql("CREATE USER %s SUPERUSER ENCRYPTED "
                    "password '%s';" % (REPL_USER, pw))
        return pw
Example #3
0
    def _create_replication_user(self):
        replication_user = None
        replication_password = utils.generate_random_password(16)

        mysql_user = None  # cache the model as we just want name validation

        retry_count = 0

        while replication_user is None:
            try:
                name = 'slave_' + str(uuid.uuid4())[:8]
                if mysql_user:
                    mysql_user.name = name
                else:
                    mysql_user = models.MySQLUser(
                        name=name, password=replication_password
                    )
                    mysql_user.check_create()
                MySqlAdmin().create_user([mysql_user.serialize()])
                LOG.debug("Trying to create replication user " +
                          mysql_user.name)
                replication_user = {
                    'name': mysql_user.name,
                    'password': replication_password
                }
            except Exception:
                retry_count += 1
                if retry_count > 5:
                    LOG.error("Replication user retry count exceeded")
                    raise

        return replication_user
Example #4
0
    def secure(self, config_contents):
        LOG.debug("Securing MySQL now.")
        clear_expired_password()

        LOG.debug("Generating admin password.")
        admin_password = utils.generate_random_password()

        # By default, MySQL does not require a password at all for connecting
        # as root
        engine = sqlalchemy.create_engine(CONNECTION_STR_FORMAT % ('root', ''),
                                          echo=True)
        with self.local_sql_client(engine, use_flush=False) as client:
            self._create_admin_user(client, admin_password)

        LOG.debug("Switching to the '%s' user now.", ADMIN_USER_NAME)
        engine = sqlalchemy.create_engine(
            CONNECTION_STR_FORMAT %
            (ADMIN_USER_NAME, urllib.parse.quote(admin_password)),
            echo=True)
        with self.local_sql_client(engine) as client:
            self._remove_anonymous_user(client)

        self.stop_db()
        self._reset_configuration(config_contents, admin_password)
        self.start_mysql()
        LOG.debug("MySQL secure complete.")
Example #5
0
 def __init__(self, password=None, *args, **kwargs):
     if password is None:
         password = utils.generate_random_password()
     super(EnterpriseDBRootUser, self).__init__("enterprisedb",
                                                password=password,
                                                *args,
                                                **kwargs)
Example #6
0
    def __init__(self, password=None, *args, **kwargs):
        if password is None:
            password = utils.generate_random_password()

        # TODO(pmalik): Name should really be 'Administrator' instead.
        super(CouchbaseRootUser, self).__init__("root", password=password,
                                                *args, **kwargs)
Example #7
0
    def enable_root(cls, root_password=None):
        """Enable access with the sys user and/or
           reset the sys password.
        """
        if root_password:
            sys_pwd = root_password
        else:
            sys_pwd = utils.generate_random_password(password_length=30)

        ora_admin = OracleAdmin()
        databases, marker = ora_admin.list_databases()
        for database in databases:
            oradb = models.OracleSchema.deserialize_schema(database)
            with LocalOracleClient(oradb.name, service=True) as client:
                client.execute('alter user sys identified by "%s"' %
                               sys_pwd)

        oracnf = OracleConfig()
        oracnf.enable_root()
        oracnf.sys_password = sys_pwd
        LOG.debug('enable_root completed')

        user = models.RootUser()
        user.name = "sys"
        user.host = "%"
        user.password = sys_pwd
        return user.serialize()
Example #8
0
 def _add_query_routers(self, query_routers, config_server_ips,
                        admin_password=None):
     """Configure the given query routers for the cluster.
     If this is a new_cluster an admin user will be created with a randomly
     generated password, else the password needs to be retrieved from
     and existing query router.
     """
     LOG.debug('adding new query router(s) %s with config server '
               'ips %s' % ([i.id for i in query_routers],
                           config_server_ips))
     for query_router in query_routers:
         try:
             LOG.debug("calling add_config_servers on query router %s"
                       % query_router.id)
             guest = self.get_guest(query_router)
             guest.add_config_servers(config_server_ips)
             if not admin_password:
                 LOG.debug("creating cluster admin user")
                 admin_password = utils.generate_random_password()
                 guest.create_admin_user(admin_password)
             else:
                 guest.store_admin_password(admin_password)
         except Exception:
             LOG.exception(_("error adding config servers"))
             self.update_statuses_on_failure(self.id)
             return False
     return True
Example #9
0
 def create_database(self, databases):
     """Create the given database(s)."""
     dbName = None
     db_create_failed = []
     LOG.debug("Creating Oracle databases.")
     ora_conf = OracleConfig()
     for database in databases:
         oradb = models.OracleSchema.deserialize_schema(database)
         dbName = oradb.name
         ora_conf.db_name = dbName
         LOG.debug("Creating Oracle database: %s." % dbName)
         try:
             sys_pwd = utils.generate_random_password(password_length=30)
             ora_conf.sys_password = sys_pwd
             run_command(system.CREATE_DB_COMMAND %
                         {'gdbname': dbName, 'sid': dbName,
                          'pswd': sys_pwd, 'db_ram': CONF.get(MANAGER).db_ram_size,
                          'template': CONF.get(MANAGER).template})
             client = LocalOracleClient(sid=dbName, service=True, user_id='sys', password=sys_pwd)
             self._create_admin_user(client)
             self.create_cloud_user_role(database)
         except exception.ProcessExecutionError:
             LOG.exception(_(
                 "There was an error creating database: %s.") % dbName)
             db_create_failed.append(dbName)
             pass
     if len(db_create_failed) > 0:
         LOG.exception(_("Creating the following databases failed: %s.") %
                       db_create_failed)
Example #10
0
    def _create_replication_user(self):
        replication_user = None
        replication_password = utils.generate_random_password(16)

        mysql_user = models.MySQLUser()
        mysql_user.password = replication_password

        retry_count = 0

        while replication_user is None:
            try:
                mysql_user.name = 'slave_' + str(uuid.uuid4())[:8]
                MySqlAdmin().create_user([mysql_user.serialize()])
                LOG.debug("Trying to create replication user " +
                          mysql_user.name)
                replication_user = {
                    'name': mysql_user.name,
                    'password': replication_password
                }
            except Exception:
                retry_count += 1
                if retry_count > 5:
                    LOG.error(_("Replication user retry count exceeded"))
                    raise

        return replication_user
Example #11
0
 def __init__(self, password=None, *args, **kwargs):
     if password is None:
         password = utils.generate_random_password()
     super(CassandraRootUser, self).__init__("cassandra",
                                             password=password,
                                             *args,
                                             **kwargs)
Example #12
0
    def secure(self):
        """Create the Trove admin user.

        The service should not be running at this point.
        This will enable role-based access control (RBAC) by default.
        """
        if self.status.is_running:
            raise RuntimeError(
                _("Cannot secure the instance. "
                  "The service is still running."))

        temp_changeid = 'localhost_auth_bypass'
        self.configuration_manager.apply_system_override(
            {'setParameter': {
                'enableLocalhostAuthBypass': True
            }}, temp_changeid)
        try:
            self.configuration_manager.apply_system_override(
                {'security': {
                    'authorization': 'enabled'
                }})
            self.start_db(update_db=False)
            password = utils.generate_random_password()
            self.create_admin_user(password)
            LOG.debug("MongoDB secure complete.")
        finally:
            self.configuration_manager.remove_system_override(temp_changeid)
            self.stop_db()
Example #13
0
 def enable_root(self, root_password=None):
     """Resets the root password."""
     LOG.info(_LI("Enabling root."))
     user = models.RootUser()
     user.name = "root"
     user.host = "%"
     user.password = root_password or utils.generate_random_password()
     if not self.is_root_enabled():
         self._create_user(user.name, user.password, 'pseudosuperuser')
     else:
         LOG.debug("Updating %s password." % user.name)
         try:
             out, err = system.exec_vsql_command(
                 self._get_database_password(),
                 system.ALTER_USER_PASSWORD % (user.name, user.password))
             if err:
                 if err.is_warning():
                     LOG.warning(err)
                 else:
                     LOG.error(err)
                     raise RuntimeError(
                         _("Failed to update %s "
                           "password.") % user.name)
         except exception.ProcessExecutionError:
             LOG.error(_("Failed to update %s password.") % user.name)
             raise RuntimeError(
                 _("Failed to update %s password.") % user.name)
     return user.serialize()
Example #14
0
    def enable_root(self, context, root_password=None):
        """Create a superuser user or reset the superuser password.

        The default PostgreSQL administration account is 'postgres'.
        This account always exists and cannot be removed.
        Its attributes and access can however be altered.

        Clients can connect from the localhost or remotely via TCP/IP:

        Local clients (e.g. psql) can connect from a preset *system* account
        called 'postgres'.
        This system account has no password and is *locked* by default,
        so that it can be used by *local* users only.
        It should *never* be enabled (or it's password set)!!!
        That would just open up a new attack vector on the system account.

        Remote clients should use a build-in *database* account of the same
        name. It's password can be changed using the "ALTER USER" statement.

        Access to this account is disabled by Trove exposed only once the
        superuser access is requested.
        Trove itself creates its own administrative account.

            {"_name": "postgres", "_password": "******"}
        """
        user = {
            "_name": "postgres",
            "_password": root_password or utils.generate_random_password(),
        }
        query = pgutil.UserQuery.alter_user(user['_name'], user['_password'],
                                            None, *self.ADMIN_OPTIONS)
        pgutil.psql(query, timeout=30)
        return user
Example #15
0
 def _create_admin_user(self, context):
     """Create an administrative user for Trove.
     Force password encryption.
     """
     password = utils.generate_random_password()
     os_admin = {"_name": self.ADMIN_USER, "_password": password, "_databases": [{"_name": self.ADMIN_USER}]}
     self._create_user(context, os_admin, True, *self.ADMIN_OPTIONS)
Example #16
0
 def enable_root(self, root_password=None):
     """Resets the root password."""
     LOG.info(_LI("Enabling root."))
     user = models.RootUser()
     user.name = "root"
     user.host = "%"
     user.password = root_password or utils.generate_random_password()
     if not self.is_root_enabled():
         self._create_user(user.name, user.password, 'pseudosuperuser')
     else:
         LOG.debug("Updating %s password." % user.name)
         try:
             out, err = system.exec_vsql_command(
                 self._get_database_password(),
                 system.ALTER_USER_PASSWORD % (user.name, user.password))
             if err:
                 if err.is_warning():
                     LOG.warning(err)
                 else:
                     LOG.error(err)
                     raise RuntimeError(_("Failed to update %s "
                                          "password.") % user.name)
         except exception.ProcessExecutionError:
             LOG.error(_("Failed to update %s password.") % user.name)
             raise RuntimeError(_("Failed to update %s password.")
                                % user.name)
     return user.serialize()
Example #17
0
 def __init__(self, password=None, *args, **kwargs):
     if password is None:
         password = utils.generate_random_password()
     super(PostgreSQLRootUser, self).__init__("postgres",
                                              password=password,
                                              *args,
                                              **kwargs)
Example #18
0
 def _generate_database_password(self):
     """Generate and write the password to vertica.cnf file."""
     config = ConfigParser.ConfigParser()
     config.add_section('credentials')
     config.set('credentials', 'dbadmin_password',
                utils.generate_random_password())
     self.write_config(config)
Example #19
0
    def enable_root(cls, root_password=None):
        """Enable access with the sys user and/or
           reset the sys password.
        """
        if root_password:
            sys_pwd = root_password
        else:
            sys_pwd = utils.generate_random_password(password_length=30)

        ora_admin = OracleAdmin()
        databases, marker = ora_admin.list_databases()
        for database in databases:
            oradb = models.OracleSchema.deserialize_schema(database)
            with LocalOracleClient(oradb.name, service=True) as client:
                client.execute('alter user sys identified by "%s"' % sys_pwd)

        oracnf = OracleConfig()
        oracnf.enable_root()
        oracnf.sys_password = sys_pwd
        LOG.debug('enable_root completed')

        user = models.RootUser()
        user.name = "sys"
        user.host = "%"
        user.password = sys_pwd
        return user.serialize()
Example #20
0
 def _generate_database_password(self):
     """Generate and write the password to vertica.cnf file."""
     config = ConfigParser.ConfigParser()
     config.add_section('credentials')
     config.set('credentials', 'dbadmin_password',
                utils.generate_random_password())
     self.write_config(config)
Example #21
0
 def enable_root(self, root_password=None):
     """Create user 'root' with the dba_user role and/or reset the root
        user password.
     """
     LOG.debug("---Enabling root user---")
     if not root_password:
         root_password = utils.generate_random_password(PASSWORD_MAX_LEN)
     root_user = models.OracleUser(ROOT_USERNAME, root_password)
     with LocalOracleClient(CONF.guest_name, service=True) as client:
         client.execute("SELECT USERNAME FROM ALL_USERS "
                        "WHERE USERNAME = upper('%s')" %
                        root_user.name.upper())
         if client.rowcount == 0:
             client.execute("CREATE USER %(username)s "
                            "IDENTIFIED BY %(password)s" % {
                                'username': root_user.name,
                                'password': root_user.password
                            })
         else:
             client.execute("ALTER USER %(username)s "
                            "IDENTIFIED BY %(password)s" % {
                                'username': root_user.name,
                                'password': root_user.password
                            })
         client.execute("GRANT PDB_DBA TO %s" % ROOT_USERNAME)
     return root_user.serialize()
Example #22
0
    def secure(self, config_contents, overrides):
        LOG.info(_("Generating admin password."))
        admin_password = utils.generate_random_password()
        service.clear_expired_password()
        engine = sqlalchemy.create_engine("mysql://root:@localhost:3306",
                                          echo=True)
        with LocalSqlClient(engine) as client:
            self._remove_anonymous_user(client)
            self._create_admin_user(client, admin_password)
        self.stop_db()
        self._reset_configuration(config_contents, admin_password)
        self._apply_user_overrides(overrides)
        self.start_mysql()
        # TODO(cp16net) figure out reason for PXC not updating the password
        try:
            with LocalSqlClient(engine) as client:
                query = text("select Host, User from mysql.user;")
                client.execute(query)
        except Exception:
            LOG.debug('failed to query mysql')
        # creating the admin user after the config files are written because
        # percona pxc was not commiting the grant for the admin user after
        # removing the annon users.
        self._wait_for_mysql_to_be_really_alive(CONF.timeout_wait_for_service)
        with LocalSqlClient(engine) as client:
            self._create_admin_user(client, admin_password)
        self.stop_db()

        self._reset_configuration(config_contents, admin_password)
        self._apply_user_overrides(overrides)
        self.start_mysql()
        self._wait_for_mysql_to_be_really_alive(CONF.timeout_wait_for_service)
        LOG.debug("MySQL secure complete.")
Example #23
0
    def secure(self):
        """Create the Trove admin user.

        The service should not be running at this point.
        This will enable role-based access control (RBAC) by default.
        """
        if self.status.is_running:
            raise RuntimeError(_("Cannot secure the instance. "
                                 "The service is still running."))

        temp_changeid = 'localhost_auth_bypass'
        self.configuration_manager.apply_system_override(
            {'setParameter': {'enableLocalhostAuthBypass': True}},
            temp_changeid)
        try:
            self.configuration_manager.apply_system_override(
                {'security': {'authorization': 'enabled'}})
            self.start_db(update_db=False)
            password = utils.generate_random_password()
            self.create_admin_user(password)
            LOG.debug("MongoDB secure complete.")
        finally:
            self.configuration_manager.remove_system_override(
                temp_changeid)
            self.stop_db()
Example #24
0
    def secure(self, update_user=None, password=None):
        """Configure the Trove administrative user.
        Update an existing user if given.
        Create a new one using the default database credentials
        otherwise and drop the built-in user when finished.
        """
        LOG.info(_('Configuring Trove superuser.'))

        if password is None:
            password = utils.generate_random_password()

        admin_username = update_user.name if update_user else self._ADMIN_USER
        os_admin = models.CassandraUser(admin_username, password)

        if update_user:
            CassandraAdmin(update_user).alter_user_password(os_admin)
        else:
            cassandra = models.CassandraUser(
                self.default_superuser_name, self.default_superuser_password)
            CassandraAdmin(cassandra)._create_superuser(os_admin)
            CassandraAdmin(os_admin).drop_user(cassandra)

        self._update_admin_credentials(os_admin)

        return os_admin
Example #25
0
    def _generate_root_password(client):
        """Generate, set, and preserve a random password
           for root@localhost when invoking mysqladmin to
           determine the execution status of the mysql service.
        """
        localhost = "localhost"
        new_password = utils.generate_random_password()
        uu = sql_query.SetPassword(models.MySQLUser.root_username,
                                   host=localhost,
                                   new_password=new_password)
        t = text(str(uu))
        client.execute(t)

        # Save the password to root's private .my.cnf file
        root_sect = {
            'client': {
                'user': '******',
                'password': new_password,
                'host': localhost
            }
        }
        operating_system.write_file('/root/.my.cnf',
                                    root_sect,
                                    codec=IniCodec(),
                                    as_root=True)
Example #26
0
 def _generate_root_password(client):
     """Generate and set a random root password and forget about it."""
     localhost = "localhost"
     uu = sql_query.UpdateUser("root", host=localhost,
                               clear=utils.generate_random_password())
     t = text(str(uu))
     client.execute(t)
Example #27
0
 def _generate_root_password(client):
     """Generate and set a random root password and forget about it."""
     localhost = "localhost"
     uu = sql_query.UpdateUser("root", host=localhost,
                               clear=utils.generate_random_password())
     t = text(str(uu))
     client.execute(t)
Example #28
0
 def _add_query_routers(self, query_routers, config_server_ips,
                        admin_password=None):
     """Configure the given query routers for the cluster.
     If this is a new_cluster an admin user will be created with a randomly
     generated password, else the password needs to be retrieved from
     and existing query router.
     """
     LOG.debug('adding new query router(s) %(routers)s with config server '
               'ips %(ips)s', {'routers': [i.id for i in query_routers],
                               'ips': config_server_ips})
     for query_router in query_routers:
         try:
             LOG.debug("calling add_config_servers on query router %s",
                       query_router.id)
             guest = self.get_guest(query_router)
             guest.add_config_servers(config_server_ips)
             if not admin_password:
                 LOG.debug("creating cluster admin user")
                 admin_password = utils.generate_random_password()
                 guest.create_admin_user(admin_password)
             else:
                 guest.store_admin_password(admin_password)
         except Exception:
             LOG.exception(_("error adding config servers"))
             self.update_statuses_on_failure(self.id)
             return False
     return True
Example #29
0
    def secure(self, config_contents, overrides):
        LOG.info(_("Generating admin password."))
        admin_password = utils.generate_random_password()
        service_base.clear_expired_password()
        engine = sqlalchemy.create_engine("mysql://root:@127.0.0.1:3306",
                                          echo=True)
        with LocalSqlClient(engine) as client:
            self._remove_anonymous_user(client)
            self._create_admin_user(client, admin_password)
        self.stop_db()
        self._reset_configuration(config_contents, admin_password)
        self._apply_user_overrides(overrides)
        self.start_mysql()
        # TODO(cp16net) figure out reason for PXC not updating the password
        try:
            with LocalSqlClient(engine) as client:
                query = text("select Host, User from mysql.user;")
                client.execute(query)
        except Exception:
            LOG.debug('failed to query mysql')
        # creating the admin user after the config files are written because
        # percona pxc was not commiting the grant for the admin user after
        # removing the annon users.
        self._wait_for_mysql_to_be_really_alive(
            CONF.timeout_wait_for_service)
        with LocalSqlClient(engine) as client:
            self._create_admin_user(client, admin_password)
        self.stop_db()

        self._reset_configuration(config_contents, admin_password)
        self._apply_user_overrides(overrides)
        self.start_mysql()
        self._wait_for_mysql_to_be_really_alive(
            CONF.timeout_wait_for_service)
        LOG.debug("MySQL secure complete.")
Example #30
0
    def start_db(self, update_db=False, ds_version=None, command=None,
                 extra_volumes=None):
        """Start and wait for database service."""
        docker_image = CONF.get(CONF.datastore_manager).docker_image
        image = (f'{docker_image}:latest' if not ds_version else
                 f'{docker_image}:{ds_version}')
        command = command if command else ''

        try:
            root_pass = self.get_auth_password(file="root.cnf")
        except exception.UnprocessableEntity:
            root_pass = utils.generate_random_password()

        # Get uid and gid
        user = "******" % (CONF.database_service_uid, CONF.database_service_uid)

        # Create folders for mysql on localhost
        for folder in ['/etc/mysql', '/var/run/mysqld']:
            operating_system.ensure_directory(
                folder, user=CONF.database_service_uid,
                group=CONF.database_service_uid, force=True,
                as_root=True)

        volumes = {
            "/etc/mysql": {"bind": "/etc/mysql", "mode": "rw"},
            "/var/run/mysqld": {"bind": "/var/run/mysqld",
                                "mode": "rw"},
            "/var/lib/mysql": {"bind": "/var/lib/mysql", "mode": "rw"},
        }
        if extra_volumes:
            volumes.update(extra_volumes)

        try:
            LOG.info("Starting docker container, image: %s", image)
            docker_util.start_container(
                self.docker_client,
                image,
                volumes=volumes,
                network_mode="host",
                user=user,
                environment={
                    "MYSQL_ROOT_PASSWORD": root_pass,
                    "MYSQL_INITDB_SKIP_TZINFO": 1,
                },
                command=command
            )

            # Save root password
            LOG.debug("Saving root credentials to local host.")
            self.save_password('root', root_pass)
        except Exception:
            LOG.exception("Failed to start mysql")
            raise exception.TroveError(_("Failed to start mysql"))

        if not self.status.wait_for_status(
            service_status.ServiceStatuses.HEALTHY,
            CONF.state_change_wait_time, update_db
        ):
            raise exception.TroveError(_("Failed to start mysql"))
Example #31
0
    def reset_password_for_restore(self,
                                   ds_version=None,
                                   data_dir='/var/lib/mysql/data'):
        """Reset the root password after restore the db data.

        We create a temporary database container by running mysqld_safe to
        reset the root password.
        """
        LOG.info('Starting to reset password for restore')

        try:
            root_pass = self.app.get_auth_password(file="root.cnf")
        except exception.UnprocessableEntity:
            root_pass = utils.generate_random_password()
            self.app.save_password('root', root_pass)

        with tempfile.NamedTemporaryFile(mode='w') as init_file, \
            tempfile.NamedTemporaryFile(suffix='.err') as err_file:
            operating_system.write_file(
                init_file.name,
                f"ALTER USER 'root'@'localhost' IDENTIFIED BY '{root_pass}';")
            command = (f'mysqld_safe --init-file={init_file.name} '
                       f'--log-error={err_file.name} '
                       f'--datadir={data_dir}')
            extra_volumes = {
                init_file.name: {
                    "bind": init_file.name,
                    "mode": "rw"
                },
                err_file.name: {
                    "bind": err_file.name,
                    "mode": "rw"
                },
            }

            # Allow database service user to access the temporary files.
            for file in [init_file.name, err_file.name]:
                operating_system.chmod(file,
                                       operating_system.FileMode.SET_ALL_RWX(),
                                       force=True,
                                       as_root=True)

            try:
                self.app.start_db(ds_version=ds_version,
                                  command=command,
                                  extra_volumes=extra_volumes)
            except Exception as err:
                LOG.error('Failed to reset password for restore, error: %s',
                          str(err))
                LOG.debug('Content in init error log file: %s',
                          err_file.read())
                raise err
            finally:
                LOG.debug(
                    'The init container log: %s',
                    docker_util.get_container_logs(self.app.docker_client))
                docker_util.remove_container(self.app.docker_client)

        LOG.info('Finished to reset password for restore')
Example #32
0
 def _secure(self, context):
     # Create a new administrative user for Trove and also
     # disable the built-in superuser.
     self.create_database(context, [{"_name": self.ADMIN_USER}])
     self._create_admin_user(context)
     pgutil.PG_ADMIN = self.ADMIN_USER
     postgres = {"_name": self.PG_BUILTIN_ADMIN, "_password": utils.generate_random_password()}
     self.alter_user(context, postgres, "NOSUPERUSER", "NOLOGIN")
Example #33
0
 def _generate_root_password(client):
     """Generate and set a random root password and forget about it."""
     localhost = "localhost"
     uu = sql_query.SetPassword(
         models.MySQLUser.root_username, host=localhost,
         new_password=utils.generate_random_password())
     t = text(str(uu))
     client.execute(t)
Example #34
0
 def _mangle_config_command_name(self):
     """Hide the 'CONFIG' command from the clients by renaming it to a
     random string known only to the guestagent.
     Return the mangled name.
     """
     mangled = utils.generate_random_password()
     self._rename_command('CONFIG', mangled)
     return mangled
Example #35
0
    def __init__(self, password=None, *args, **kwargs):
        if password is None:
            pwd_len = min(self.MAX_PASSWORD_LEN, CONF.default_password_length)
            password = utils.generate_random_password(pwd_len)

        # TODO(pmalik): Name should really be 'Administrator' instead.
        super(CouchbaseRootUser, self).__init__("root", password=password,
                                                *args, **kwargs)
Example #36
0
 def root(cls, name=None, password=None, *args, **kwargs):
     if not name:
         name = cls.root_username
     if not password:
         password = utils.generate_random_password()
     user = cls(name, password, *args, **kwargs)
     user.make_root()
     return user
Example #37
0
 def root(cls, name=None, password=None, *args, **kwargs):
     if not name:
         name = cls.root_username
     if not password:
         password = utils.generate_random_password()
     user = cls(name, password, *args, **kwargs)
     user.make_root()
     return user
Example #38
0
 def _create_admin_user(self, context):
     """Create an administrative user for Trove.
     Force password encryption.
     """
     password = utils.generate_random_password()
     os_admin = {'_name': self.ADMIN_USER, '_password': password,
                 '_databases': [{'_name': self.ADMIN_USER}]}
     self._create_user(context, os_admin, True, *self.ADMIN_OPTIONS)
Example #39
0
 def __init__(self, password=None):
     super(MySQLRootUser, self).__init__()
     self._name = "root"
     self._host = "%"
     if password is None:
         self._password = utils.generate_random_password()
     else:
         self._password = password
Example #40
0
 def _generate_root_password(client):
     """Generate and set a random root password and forget about it."""
     localhost = "localhost"
     uu = sql_query.SetPassword(
         models.MySQLUser.root_username, host=localhost,
         new_password=utils.generate_random_password())
     t = text(str(uu))
     client.execute(t)
Example #41
0
 def __init__(self, password=None):
     super(MySQLRootUser, self).__init__()
     self._name = "root"
     self._host = "%"
     if password is None:
         self._password = utils.generate_random_password()
     else:
         self._password = password
Example #42
0
 def _mangle_config_command_name(self):
     """Hide the 'CONFIG' command from the clients by renaming it to a
     random string known only to the guestagent.
     Return the mangled name.
     """
     mangled = utils.generate_random_password()
     self._rename_command('CONFIG', mangled)
     return mangled
Example #43
0
 def _secure(self, context):
     # Create a new administrative user for Trove and also
     # disable the built-in superuser.
     self.create_database(context, [{'_name': self.ADMIN_USER}])
     self._create_admin_user(context)
     pgutil.PG_ADMIN = self.ADMIN_USER
     postgres = {'_name': self.PG_BUILTIN_ADMIN,
                 '_password': utils.generate_random_password()}
     self.alter_user(context, postgres, 'NOSUPERUSER', 'NOLOGIN')
Example #44
0
 def enable_root(self, password=None):
     """Create a user 'root' with role 'root'."""
     if not password:
         LOG.debug('Generating root user password.')
         password = utils.generate_random_password()
     root_user = models.MongoDBUser(name='admin.root', password=password)
     root_user.roles = {'db': 'admin', 'role': 'root'}
     self.create_validated_user(root_user)
     return root_user.serialize()
Example #45
0
 def enable_root(self, password=None):
     """Create a user 'root' with role 'root'."""
     if not password:
         LOG.debug("Generating root user password.")
         password = utils.generate_random_password()
     root_user = models.MongoDBUser(name="admin.root", password=password)
     root_user.roles = {"db": "admin", "role": "root"}
     self.create_user(root_user)
     return root_user.serialize()
Example #46
0
 def secure(self):
     '''
     Create the Trove admin user.
     The service should not be running at this point.
     '''
     self.start_db(update_db=False)
     password = utils.generate_random_password()
     self.create_admin_user(password)
     LOG.debug("CouchDB secure complete.")
Example #47
0
 def _create_admin_user(self, context, databases=None):
     """Create an administrative user for Trove.
     Force password encryption.
     """
     password = utils.generate_random_password()
     os_admin = models.PostgreSQLUser(self.ADMIN_USER, password)
     if databases:
         os_admin.databases.extend([db.serialize() for db in databases])
     self._create_user(context, os_admin, True, *self.ADMIN_OPTIONS)
Example #48
0
 def enable_root(self, password=None):
     """Create a user 'root' with role 'root'."""
     if not password:
         LOG.debug('Generating root user password.')
         password = utils.generate_random_password()
     root_user = models.MongoDBUser(name='admin.root', password=password)
     root_user.roles = {'db': 'admin', 'role': 'root'}
     self.create_validated_user(root_user)
     return root_user.serialize()
Example #49
0
 def secure(self):
     '''
     Create the Trove admin user.
     The service should not be running at this point.
     '''
     self.start_db(update_db=False)
     password = utils.generate_random_password()
     self.create_admin_user(password)
     LOG.debug("CouchDB secure complete.")
Example #50
0
 def _create_admin_user(self, context, databases=None):
     """Create an administrative user for Trove.
     Force password encryption.
     """
     password = utils.generate_random_password()
     os_admin = models.PostgreSQLUser(self.ADMIN_USER, password)
     if databases:
         os_admin.databases.extend([db.serialize() for db in databases])
     self._create_user(context, os_admin, True, *self.ADMIN_OPTIONS)
Example #51
0
        def _create_resources():

            if cluster_config:
                cluster_id = cluster_config.get("id", None)
                shard_id = cluster_config.get("shard_id", None)
                instance_type = cluster_config.get("instance_type", None)
            else:
                cluster_id = shard_id = instance_type = None

            db_info = DBInstance.create(name=name, flavor_id=flavor_id,
                                        tenant_id=context.tenant,
                                        volume_size=volume_size,
                                        datastore_version_id=
                                        datastore_version.id,
                                        task_status=InstanceTasks.BUILDING,
                                        configuration_id=configuration_id,
                                        slave_of_id=slave_of_id,
                                        cluster_id=cluster_id,
                                        shard_id=shard_id,
                                        type=instance_type)
            LOG.debug("Tenant %(tenant)s created new Trove instance %(db)s."
                      % {'tenant': context.tenant, 'db': db_info.id})

            # if a configuration group is associated with an instance,
            # generate an overrides dict to pass into the instance creation
            # method

            config = Configuration(context, configuration_id)
            overrides = config.get_configuration_overrides()
            service_status = InstanceServiceStatus.create(
                instance_id=db_info.id,
                status=tr_instance.ServiceStatuses.NEW)

            if CONF.trove_dns_support:
                dns_client = create_dns_client(context)
                hostname = dns_client.determine_hostname(db_info.id)
                db_info.hostname = hostname
                db_info.save()

            root_password = None
            if cls.get_root_on_create(
                    datastore_version.manager) and not backup_id:
                root_password = utils.generate_random_password()

            task_api.API(context).create_instance(db_info.id, name, flavor,
                                                  image_id, databases, users,
                                                  datastore_version.manager,
                                                  datastore_version.packages,
                                                  volume_size, backup_id,
                                                  availability_zone,
                                                  root_password, nics,
                                                  overrides, slave_of_id,
                                                  cluster_config)

            return SimpleInstance(context, db_info, service_status,
                                  root_password)
Example #52
0
    def enable_root(cls, root_password=None):
        user = models.RootUser()
        user.name = "root"
        user.host = "%"
        user.password = root_password or utils.generate_random_password()

        if root_password:
            CouchbaseRootAccess().write_password_to_file(root_password)
        else:
            CouchbaseRootAccess().set_password(user.password)
        return user.serialize()
Example #53
0
    def add_members(self, members):
        """
        This method is used by a replica-set member instance.
        """
        def check_initiate_status():
            """
            This method is used to verify replica-set status.
            """
            status = MongoDBAdmin().get_repl_status()

            if((status["ok"] == 1) and
               (status["members"][0]["stateStr"] == "PRIMARY") and
               (status["myState"] == 1)):
                    return True
            else:
                return False

        def check_rs_status():
            """
            This method is used to verify replica-set status.
            """
            status = MongoDBAdmin().get_repl_status()
            primary_count = 0

            if status["ok"] != 1:
                return False
            if len(status["members"]) != (len(members) + 1):
                return False
            for rs_member in status["members"]:
                if rs_member["state"] not in [1, 2, 7]:
                    return False
                if rs_member["health"] != 1:
                    return False
                if rs_member["state"] == 1:
                    primary_count += 1

            return primary_count == 1

        # Create the admin user on this member.
        # This is only necessary for setting up the replica set.
        # The query router will handle requests once this set
        # is added as a shard.
        password = utils.generate_random_password()
        self.create_admin_user(password)

        # initiate replica-set
        MongoDBAdmin().rs_initiate()
        # TODO(ramashri) see if hardcoded values can be removed
        utils.poll_until(check_initiate_status, sleep_time=60, time_out=100)

        # add replica-set members
        MongoDBAdmin().rs_add_members(members)
        # TODO(ramashri) see if hardcoded values can be removed
        utils.poll_until(check_rs_status, sleep_time=60, time_out=100)
        def _create_cluster():
            cluster_node_ids = self.find_cluster_node_ids(cluster_id)

            # Wait for cluster nodes to get to cluster-ready status.
            LOG.debug("Waiting for all nodes to become ready.")
            if not self._all_instances_ready(cluster_node_ids, cluster_id):
                return

            cluster_nodes = self.load_cluster_nodes(context, cluster_node_ids)

            LOG.debug("All nodes ready, proceeding with cluster setup.")
            seeds = self.choose_seed_nodes(cluster_nodes)

            # Configure each cluster node with the list of seeds.
            # Once all nodes are configured, start the seed nodes one at a time
            # followed by the rest of the nodes.
            try:
                LOG.debug("Selected seed nodes: %s" % seeds)

                for node in cluster_nodes:
                    LOG.debug("Configuring node: %s." % node['id'])
                    node['guest'].set_seeds(seeds)
                    node['guest'].set_auto_bootstrap(False)

                LOG.debug("Starting seed nodes.")
                for node in cluster_nodes:
                    if node['ip'] in seeds:
                        node['guest'].restart()
                        node['guest'].set_auto_bootstrap(True)

                LOG.debug("All seeds running, starting remaining nodes.")
                for node in cluster_nodes:
                    if node['ip'] not in seeds:
                        node['guest'].restart()
                        node['guest'].set_auto_bootstrap(True)

                # Create the in-database user via the first node. The remaining
                # nodes will replicate in-database changes automatically.
                # Only update the local authentication file on the other nodes.
                LOG.debug("Securing the cluster.")
                key = utils.generate_random_password()
                admin_creds = None
                for node in cluster_nodes:
                    if admin_creds is None:
                        admin_creds = node['guest'].cluster_secure(key)
                    else:
                        node['guest'].store_admin_credentials(admin_creds)
                    node['guest'].cluster_complete()

                LOG.debug("Cluster configuration finished successfully.")
            except Exception:
                LOG.exception(_("Error creating cluster."))
                self.update_statuses_on_failure(cluster_id)
Example #55
0
 def secure(self, cluster_config=None):
     # Secure the server by storing the cluster key  if this is a cluster
     # or creating the admin user if this is a single instance.
     LOG.debug('Securing MongoDB instance.')
     if cluster_config:
         self.store_key(cluster_config['key'])
     else:
         LOG.debug('Generating admin password.')
         password = utils.generate_random_password()
         self.start_db()
         self.create_admin_user(password)
         self.stop_db()
     LOG.debug('MongoDB secure complete.')
Example #56
0
 def _create_admin_user(self, ora_sys_client):
     """
     Create a os_admin user with a random password
     with all privileges similar to the root user.
     """
     with ora_sys_client as client:
         oracnf = OracleConfig()
         if not oracnf.admin_password:
             oracnf.admin_password = utils.generate_random_password(password_length=30)
         q = sql_query.CreateUser(ADMIN_USER_NAME, oracnf.admin_password)
         client.execute(str(q))
         q = ('grant sysdba, sysoper to %s' % ADMIN_USER_NAME)
         client.execute(str(q))
Example #57
0
 def disable_root(cls):
     """Disable reset the sys password."""
     sys_pwd = utils.generate_random_password(password_length=30)
     ora_admin = OracleAdmin()
     databases, marker = ora_admin.list_databases()
     for database in databases:
         oradb = models.OracleSchema.deserialize_schema(database)
         with LocalOracleClient(oradb.name, service=True) as client:
             client.execute('alter user sys identified by "%s"' %
                            sys_pwd)
     oracnf = OracleConfig()
     oracnf.disable_root()
     oracnf.sys_password = sys_pwd
     LOG.debug('disable_root completed')
Example #58
0
    def secure(self, config_contents, overrides):
        LOG.info(_("Generating admin password..."))
        admin_password = utils.generate_random_password()
        clear_expired_password()
        engine = sqlalchemy.create_engine("mysql://root:@localhost:3306",
                                          echo=True)
        with LocalSqlClient(engine) as client:
            self._remove_anonymous_user(client)
            self._create_admin_user(client, admin_password)

        self.stop_db()
        self._write_mycnf(admin_password, config_contents, overrides)
        self.start_mysql()

        LOG.info(_("Dbaas secure complete."))