32.4. Ограничение доступа администратора СУБД к данным #

На основе технологии разграничения прав между привилегированными пользователями СУБД был создан механизм, запрещающий администраторам СУБД и БД доступ к данным, включая просмотр, при сохранении возможности заниматься администрированием, таким как резервное копирование и восстановление, диагностика, настройка БД, создание и удаление БД.

32.4.1. Обзор #

Конфиденциальная информация хранится в таблицах, которые, в свою очередь, находятся в схемах БД. По умолчанию администратор СУБД и администраторы всех соответствующих БД имеют к ней доступ, что может привести к несанкционированному доступу. Для защиты данных Postgres Pro Enterprise необходимо зарегистрировать зону повышенной безопасности, что удобно сделать на уровне схемы, и определить правила доступа к ней.

Такая схема описана в Подразделе 5.10.3. Она имеет выделенного владельца и администратора безопасности. Это должны быть разные пользователи БД:

  • Администратор безопасности, или менеджер прав доступа, сможет только выдавать разрешения пользователям на доступ к объектам зоны, но работа с объектами будет для него недоступна: он не сможет их создавать, просматривать или изменять.

  • Владелец зоны сможет работать с объектами зоны.

Владельца и администратора безопасности зоны повышенной безопасности создаёт суперпользователь. Для целей их создания и назначения привилегий доверенный администратор инфраструктуры временно и подконтрольно разрешает вход для суперпользователя, переведя СУБД в технологический режим.

32.4.2. Создание администраторов и менеджеров зоны повышенной безопасности #

32.4.2.1. Временное открытие для суперпользователя postgres входа в базу с локальной консоли #

Администратор инфраструктуры root вносит в pg_hba.conf строки, разрешающие соединения для суперпользователя с локальной консоли:

TYPE    DATABASE    USER      ADDRESS       METHOD
local   all         postgres                peer
host    all         postgres  127.0.0.1/32  reject
host    all         postgres  ::1/128       reject

Чтобы новые ограничения вступили в силу требуется перезапуск сервера СУБД:

# pg_ctl restart

32.4.2.2. Создание управляющих зоны повышенной безопасности #

Процедура создания выделенного владельца (менеджера) зоны повышенной безопасности DV_OWNER и администратора безопасности (менеджера прав доступа) DV_SEC_OFFICER требует привлечения суперпользователя. Это вызвано тем, что, в случае создания учётных записей этих пользователей от имени администратора СУБД или администратора БД, у этих администраторов останется право ADMIN OPTION, от которого они даже не могут отказаться.

Чтобы исключить риски, связанные как с доверием к администраторам, у которых сохранилась бы возможность управлять DV_OWNER и DV_SEC_OFFICER, так и на случай доступа к их учётными записям злоумышленника, операция выполняется от имени суперпользователя.

В целях демонстрации в данном примере предполагается, что зона повышенной безопасности будет создаваться в базе данных DB1.

$ psql postgres
CREATE USER DV_OWNER WITH LOGIN; -- Не забудьте установить первичный пароль
CREATE USER DV_SEC_OFFICER WITH LOGIN; -- Не забудьте установить первичный пароль
GRANT CONNECT ON DATABASE db1 TO DV_SEC_OFFICER;
GRANT CONNECT ON DATABASE db1 TO DV_OWNER;
EXIT;

32.4.2.3. Создание зоны повышенной безопасности #

Создание зоны повышенной безопасности является крайне важным шагом и возможно только с участием суперпользователя, которому временно разрешён вход в базу.

Чтобы создать объект, владельцем которого будет другая роль, или назначить другой роли права владения уже существующим объектом, необходимо иметь право SET ROLE для этой роли. В противном случае команды ALTER ... OWNER TO или CREATE DATABASE ... OWNER выдадут ошибку, как описано в GRANT.

В силу независимости DV_OWNER доступ к этой роли через SET ROLE со стороны администратора СУБД или администратора БД предоставляться не должен, поэтому не рекомендуется выдавать им права владения SQL-объектами. Поэтому наилучшим вариантом является создание зоны повышенной безопасности от имени суперпользователя.

Обратите внимание на изменённый синтаксис команды ALTER SCHEMA. Предложения SECURITY OFFICER и RESET SECURITY OFFICER соответственно задают или удаляют администратора безопасности схемы. Когда задаётся администратор безопасности, схема становится схемой vault, как описано в ALTER SCHEMA.

$ psql db1 -U postgres
CREATE SCHEMA vault;
GRANT ALL ON SCHEMA vault TO DV_OWNER;
GRANT USAGE ON SCHEMA vault to DV_SEC_OFFICER;
ALTER SCHEMA vault OWNER TO DV_OWNER;
ALTER SCHEMA vault SECURITY OFFICER TO DV_SEC_OFFICER;
EXIT;

32.4.2.4. Защита пользователей зоны повышенной безопасности от администраторов #

Пользователи с доступом к зоне повышенной безопасности должны быть надёжно защищены. У администратора СУБД или администраторов БД не должно быть права ADMIN OPTION в отношении этих пользователей, иначе у администраторов может возникнуть возможность получить несанкционированный доступ к данным зоны повышенной безопасности.

Для исключения данной уязвимости требуется лишить других пользователей права ADMIN OPTION на пользователей зоны повышенной безопасности при помощи команды REVOKE ADMIN OPTION. Рассмотрим это на примере пользователя vault_user, которого создадим ролью PGPRO_DB_1_ADMIN:

$ psql db1 -U db1_admin
CREATE USER vault_user; -- Не забудьте установить пароли
GRANT CONNECT ON DATABASE db1 TO vault_user;
EXIT;

Сначала необходимо проверить, кто имеет право ADMIN OPTION на пользователя vault_user:

$ psql db1 -U postgres
SELECT rn.rolname "role", mn.rolname member, gn.rolname grantor, am.admin_option
FROM pg_auth_members am
JOIN pg_roles rn ON rn.oid = am.roleid
JOIN pg_roles mn ON mn.oid = am.member
JOIN pg_roles gn ON gn.oid = am.grantor
WHERE rn.rolname = 'vault_user' AND am.admin_option = true
ORDER BY member;

В данном примере такие права есть у роли db1_admin:

    role    |      member      |     grantor      | admin_option
------------+------------------+------------------+--------------
 vault_user | db1_admin        | postgres         | t
(1 row)

Теперь суперпользователь postgres отзовёт у роли db1_admin такие права:

$ psql db1 -U postgres
REVOKE ADMIN OPTION FOR vault_user FROM db1_admin CASCADE;

После чего необходимо ещё раз убедиться, что не осталось лишних пользователей с правом ADMIN OPTION на пользователя vault_user:

$ psql db1 -U postgres
SELECT rn.rolname "role", mn.rolname member, gn.rolname grantor, am.admin_option
FROM pg_auth_members am
JOIN pg_roles rn ON rn.oid = am.roleid
JOIN pg_roles mn ON mn.oid = am.member
JOIN pg_roles gn ON gn.oid = am.grantor
WHERE rn.rolname = 'vault_user' AND am.admin_option = true
ORDER BY member;

    role    |      member      |     grantor      | admin_option
------------+------------------+------------------+--------------
(0 rows)

32.4.2.5. Закрытие доступа к зоне повышенной безопасности для суперпользователя #

Чтобы запретить соединение для суперпользователя, администратор инфраструктуры вносит в pg_hba.conf следующие строки:

TYPE     DATABASE  USER       ADDRESS       METHOD
local    all       postgres                 reject
host     all       postgres   127.0.0.1/32  reject
host     all       postgres   ::1/128       reject

Чтобы новые ограничения вступили в силу, требуется перезапуск сервера СУБД:

# pg_ctl restart

32.4.3. Создание таблицы в зоне повышенной безопасности #

Поскольку только менеджер (владелец) зоны может работать с её объектами, таблицы создаётся от имени DV_OWNER:

$ psql db1 -U dv_owner
CREATE TABLE vault.vault_table (user_name TEXT, balance DECIMAL(10,2));
EXIT;

32.4.4. Перенос таблицы в зону повышенной безопасности #

Предположим, что администратор БД создал таблицу, которую позже было решено перенести в зону повышенной безопасности:

$ psql db1 -U db1_admin

CREATE TABLE working_table(id INT, info TEXT);

Этот пользователь может также наполнить таблицу данными:

INSERT INTO working_table(id, info) VALUES (1, 'Number One');

В дальнейшем может понадобиться передать владение этой таблицей к DV_OWNER, чтобы он перенёс её в зону повышенной безопасности. В PostgreSQL существует требование-ограничение: пользователь может передать владение своей таблицей другому пользователю, только если у него с этим пользователем есть общая роль:

ALTER TABLE working_table OWNER TO DV_OWNER;
ERROR:  must be able to SET ROLE "DV_OWNER"

Поэтому передачу прав владения и перемещение таблицы в зону повышенной безопасности должен проводить суперпользователь postgres. Для этого необходимо временно разрешить ему доступ в СУБД:

$ psql db1 -U postgres
ALTER TABLE working_table OWNER TO DV_OWNER;

После выполнения этой команды доступ суперпользователю postgres в СУБД необходимо снова закрыть.

Теперь DV_OWNER может переместить таблицу в зоны повышенной безопасности:

$ psql db1 -U dv_owner
ALTER TABLE working_table SET SCHEMA vault;

32.4.5. Разрешение доступа к защищённой таблице #

Поскольку только администратор безопасности (менеджер прав доступа) зоны может выдавать разрешения пользователям на работу с объектами зоны, управление привилегиями осуществляется от имени DV_SEC_OFFICER. Данные будут доступны только явно указанным пользователям. Все прочие не будут иметь к ним доступа, включая администратора СУБД и администратора БД. Соответствующие команды GRANT должны выглядеть так:

$ psql db1 -U dv_sec_officer
GRANT USAGE ON SCHEMA vault TO vault_user;
GRANT INSERT,UPDATE,DELETE,SELECT,TRUNCATE ON vault.vault_table TO vault_user;
GRANT INSERT,UPDATE,DELETE,SELECT,TRUNCATE ON vault.working_table TO vault_user;
EXIT;

32.4.6. Проверка доступа: наполнение защищённой таблицы данными #

Подключившись к БД db1 от имени пользователя, которому предоставлен доступ к зоне повышенной безопасности, можно убедиться, что его прав для доступа к данным в этой зоне достаточно:

$ psql db1 -U vault_user
INSERT INTO vault.vault_table( user_name, balance) VALUES( 'Ann', 200);
INSERT INTO vault.vault_table( user_name, balance) VALUES( 'Bob', 3000);
SELECT * FROM vault.vault_table;
SELECT * FROM vault.working_table;
EXIT;

32.4.7. Изменения в программе экспорта базы данных #

При восстановлении зоны повышенной безопасности понадобятся два разных администратора, поскольку один из них не сможет восстановить права доступа, а другой — объекты зоны. Поэтому в программе для экспорта базы данных pg_dump предусмотрена раздельная выгрузка структуры и данных, а также прав доступа зоны повышенной безопасности. Для этого следует воспользоваться специальными ключами --no-privileges и --privileges-only.

Выгрузка данных с помощью pg_dump выполняется в следующем порядке:

  1. Администратор БД выгружает все данные, кроме данных зоны повышенной безопасности, используя параметр --exclude-schema.

  2. DV_OWNER выгружает данные зоны повышенной безопасности, используя параметры --schema и --no-privileges.

  3. DV_OWNER выгружает права доступа, используя параметры --schema и --privileges-only.

Загружать данные с помощью pg_restore необходимо в следующем порядке:

  1. Администратор БД восстанавливает все данные, кроме данных зоны повышенной безопасности.

  2. DV_OWNER восстанавливает данные зоны повышенной безопасности.

  3. DV_SEC_OFFICER восстанавливает права доступа в зону повышенной безопасности.

32.4.8. Изменения в программе проверки целостности #

В утилиту для проверки целостности pg_integrity_check внесены следующие изменения:

  • С помощью ключа -C можно выбрать, каталог какой именно базы нужно проверять (в данном случае, той, где создана зона повышенной безопасности).

  • С помощью параметра --syslog теперь можно организовать запись результатов проверки контрольных сумм в syslog.

  • pg_integrity_check записывает как информацию об успешных проверках с уровнем важности Information, так и о неуспешных проверках с уровнем важности Critical.

32.4.  Restricting DBMS Administrator's Data Access #

Based on the Separation of Duties between Privileged DBMS Users technology, the Postgres Professional company has created a mechanism to block DBMS Administrator's and DB Administrator's data access, including viewing, but allow them to continue performing administration such as backup/restore, diagnostics, DB creation, deletion, and configuring.

32.4.1. Overview #

Sensitive information is stored in tables, which are contained in DB schemas. By default, the DBMS Administrator and DB Administrators of appropriate databases can access this information, which makes a real issue. To protect data, Postgres Pro Enterprise provides an enhanced security mechanism — the Postgres Pro secured schema and defines access rules for this schema.

This schema, described in Section 5.10.3, will have a dedicated schema owner and security officer. They must be different DB users:

  • The security officer (manager of access rights) will only be able to grant or revoke user access privileges for schema objects, but will be unable to work with schema objects: create, view, or modify them.

  • The schema owner will be able to work with schema objects.

A superuser must create the owner and security officer of the secured schema. Hence, to create them and grant privileges, it is needed to switch the DBMS to a single mode and temporarily allow login of a superuser under the control of the trusted infrastructure administrator.

32.4.2. Creating Administrators and Managers of the DB Secured Schema #

32.4.2.1. Granting a Temporary postgres Superuser Right for a DB Login from the Local Console #

The infrastructure administrator root adds lines to pg_hba.conf that allow superuser connections from the local console:

TYPE    DATABASE    USER      ADDRESS       METHOD
local   all         postgres                peer
host    all         postgres  127.0.0.1/32  reject
host    all         postgres  ::1/128       reject

DBMS server restart is needed for the new restrictions to take effect:

# pg_ctl restart

32.4.2.2. Creating Managers of the Secured Schema #

The process of creating a dedicated owner (manager) of the secured schema DV_OWNER and a security officer (manager of access rights) DV_SEC_OFFICER requires involvement of a superuser because if these accounts are created by the DBMS Administrator or DB_Administrator, these administrators will still have the ADMIN OPTION right, which they even cannot revoke.

To address risks both related to the trust in administrators, who would retain the possibility to manage DV_OWNER and DV_SEC_OFFICER, and to access of malicious users to their accounts, the superuser performs the operations needed.

To simplify, this example assumes that the secured schema will be created in the DB1 database.

$ psql postgres
CREATE USER DV_OWNER WITH LOGIN; -- Do not forget to set initial password
CREATE USER DV_SEC_OFFICER WITH LOGIN; -- Do not forget to set initial password
GRANT CONNECT ON DATABASE db1 TO DV_SEC_OFFICER;
GRANT CONNECT ON DATABASE db1 TO DV_OWNER;
EXIT;

32.4.2.3. Creating the Secured Schema #

Creation of the secured schema is a critical activity, which must involve the superuser, who needs a temporary permission for the DB login.

For a role to be able to create an object that will be owned by a different role or to grant ownership of an existing object to a different role, the SET ROLE right is needed, otherwise the command ALTER ... OWNER TO or CREATE DATABASE ... OWNER will issue an error, as explained in GRANT.

As the DV_OWNER is independent, access of the DBMS Administrator or DB Administrator to this role through SET ROLE should not be granted, and these administrators should not have ownership rights for SQL objects. Hence, creation of the secured schema by the superuser is the best way.

In the commands below, pay attention to the modified syntax of the ALTER SCHEMA command. The SECURITY OFFICER/RESET SECURITY OFFICER clause sets/resets the security officer, respectively. When you set the security officer, the schema becomes the vault schema, as described in ALTER SCHEMA.

$ psql db1 -U postgres
CREATE SCHEMA vault;
GRANT ALL ON SCHEMA vault TO DV_OWNER;
GRANT USAGE ON SCHEMA vault to DV_SEC_OFFICER;
ALTER SCHEMA vault OWNER TO DV_OWNER;
ALTER SCHEMA vault SECURITY OFFICER TO DV_SEC_OFFICER;
EXIT;

32.4.2.4. Protecting Secured Schema Users from Administrators #

Users with access to the secured schema must be strongly protected. You cannot permit DBMS Administrator and DB Administrator have the ADMIN OPTION for secured schema users as in this case, these administrators may potentially get unauthorized access to the secured schema data.

To prevent from this vulnerability, the ADMIN OPTION for secured schema users must be revoked from other users by the REVOKE ADMIN OPTION command. Let's see how to do this by example of the vault_user user, which will be created by the PGPRO_DB_1_ADMIN role:

$ psql db1 -U db1_admin
CREATE USER vault_user; -- Do not forget to set passwords
GRANT CONNECT ON DATABASE db1 TO vault_user;
EXIT;

First, let's check who has ADMIN OPTION for vault_user:

$ psql db1 -U postgres
SELECT rn.rolname "role", mn.rolname member, gn.rolname grantor, am.admin_option
FROM pg_auth_members am
JOIN pg_roles rn ON rn.oid = am.roleid
JOIN pg_roles mn ON mn.oid = am.member
JOIN pg_roles gn ON gn.oid = am.grantor
WHERE rn.rolname = 'vault_user' AND am.admin_option = true
ORDER BY member;

In this example, the db1_admin role has these rights:

    role    |      member      |     grantor      | admin_option
------------+------------------+------------------+--------------
 vault_user | db1_admin        | postgres         | t
(1 row)

The postgres superuser will now revoke them from the db1_admin role:

$ psql db1 -U postgres
REVOKE ADMIN OPTION FOR vault_user FROM db1_admin CASCADE;

Finally, let's make sure that there are no extra users with the ADMIN OPTION for vault_user:

$ psql db1 -U postgres
SELECT rn.rolname "role", mn.rolname member, gn.rolname grantor, am.admin_option
FROM pg_auth_members am
JOIN pg_roles rn ON rn.oid = am.roleid
JOIN pg_roles mn ON mn.oid = am.member
JOIN pg_roles gn ON gn.oid = am.grantor
WHERE rn.rolname = 'vault_user' AND am.admin_option = true
ORDER BY member;

    role    |      member      |     grantor      | admin_option
------------+------------------+------------------+--------------
(0 rows)

32.4.2.5. Revoking Superuser Access to the Secured Schema #

To block superuser connections, the infrastructure administrator adds these lines to pg_hba.conf:

TYPE     DATABASE  USER       ADDRESS       METHOD
local    all       postgres                 reject
host     all       postgres   127.0.0.1/32  reject
host     all       postgres   ::1/128       reject

Restart of the DBMS server is needed for the new restrictions to take effect:

# pg_ctl restart

32.4.3. Creating a Table in the Secured Schema #

As the schema manager (owner) can only work with its objects, the DV_OWNER creates tables there:

$ psql db1 -U dv_owner
CREATE TABLE vault.vault_table (user_name TEXT, balance DECIMAL(10,2));
EXIT;

32.4.4. Moving a Table to the Secured Schema #

Let's assume that the DB Administrator created a table:

$ psql db1 -U db1_admin

CREATE TABLE working_table(id INT, info TEXT);

This user can also fill this table with data:

INSERT INTO working_table(id, info) VALUES (1, 'Number One');

Later it was decided to move this table to the secured schema. To do this, the table ownership should be transferred to DV_OWNER, who will move it to the secured schema. However, PostgreSQL has a restricting requirement: the ownership of one's table can only be transferred to a user if there is a role that is member of both the old and new owning role:

ALTER TABLE working_table OWNER TO DV_OWNER;
ERROR:  must be able to SET ROLE "DV_OWNER"

Therefore, the superuser postgres must transfer the table ownership. To do this, the superuser postgres needs temporary DBMS access:

$ psql db1 -U postgres
ALTER TABLE working_table OWNER TO DV_OWNER;

After execution of this command, DBMS access must be revoked from the superuser postgres.

DV_OWNER will move the table to the secured schema:

$ psql db1 -U dv_owner
ALTER TABLE working_table SET SCHEMA vault;

32.4.5. Permitting Access to a Protected Table #

As the schema security officer (manager of access rights) can only grant users with permissions to access schema objects, the DV_SEC_OFFICER manages the privileges. Only users that are explicitly specified will be able to access data. Other users, including DBMS Administrator and DB Administrator, will not have access to the data. Appropriate GRANT commands are as follows:

$ psql db1 -U dv_sec_officer
GRANT USAGE ON SCHEMA vault TO vault_user;
GRANT INSERT,UPDATE,DELETE,SELECT,TRUNCATE ON vault.vault_table TO vault_user;
GRANT INSERT,UPDATE,DELETE,SELECT,TRUNCATE ON vault.working_table TO vault_user;
EXIT;

32.4.6. Checking Access: Filling in a Protected Table #

Connecting to the db1 database as a user that was granted access to the secured schema, we can make sure that the user's privileges are sufficient to access data in the secured schema:

$ psql db1 -U vault_user
INSERT INTO vault.vault_table( user_name, balance) VALUES( 'Ann', 200);
INSERT INTO vault.vault_table( user_name, balance) VALUES( 'Bob', 3000);
SELECT * FROM vault.vault_table;
SELECT * FROM vault.working_table;
EXIT;

32.4.7. Changes Made to an Export Application #

When restoring a secured schema, two different administrators are needed as one of them will be unable to restore access rights, while the other one will be unable to restore schema objects. Therefore, pg_dump now enables separate dumping of the schema and data and of access privileges for the secured schema. --no-privileges and --privileges-only options, respectively, enable this separate dumping.

Dump operations with pg_dump must be performed in the following order:

  1. The DB Administrator dumps all data except the secured schema, using the --exclude-schema option.

  2. The DV_OWNER dumps the secured schema data, using the --schema and --no-privileges options.

  3. The DV_OWNER dumps the access privileges, using the --schema and --privileges-only options.

Restore operations using pg_restore must be performed in the following order:

  1. The DB Administrator restores all data except the secured schema.

  2. The DV_OWNER restores the secured schema data.

  3. The DV_SEC_OFFICER restores the access privileges for the secured schema.

32.4.8. Changes Made to the Integrity-check Utility #

The following changes have been made to pg_integrity_check:

  • The new -C option allows you to specify the database whose system catalog must be validated. Tip: specify the one where the secured schema is created.

  • The new --syslog option allows you to write checksum validation results into syslog.

  • pg_integrity_check can now log information about both successful validation with the Information importance level and unsuccessful validation with the Critical importance level.

FAQ