F.40. pg_proaudit
- F.40.1. Установка расширения
pg_proaudit- F.40.2. Удаление расширения
pg_proaudit- F.40.3. Функции для настройки записи событий безопасности в журнал
- F.40.4. Представление pg_proaudit_settings
- F.40.5. События безопасности
- F.40.6. Параметры конфигурации журнала событий безопасности
- F.40.7. Просмотр журнала событий безопасности
- F.40.8. Примеры
- F.40.2. Удаление расширения
Расширение pg_proaudit позволяет регистрировать различные события, связанные с безопасностью.
pg_proaudit работает параллельно со стандартными средствами протоколирования PostgreSQL (сборщиком сообщений) и не зависит от них. Журнал событий безопасности расширения pg_proaudit сохраняется отдельно от журнала работы сервера. При запуске Postgres Pro Enterprise расширение pg_proaudit запускает специальный фоновый процесс, который записывает в журнал информацию о событиях безопасности.
Правила регистрации событий сохраняются в файле конфигурации pg_proaudit.conf, располагающемся в каталоге данных кластера (PGDATA). Он представляет собой текстовый файл, который можно редактировать непосредственно, используя инструменты операционной системы. Для изменения его содержимого средствами SQL предусмотрены несколько функций pg_proaudit. В представлении pg_proaudit_settings можно посмотреть текущие правила pg_proaudit, даже если они ещё не были сохранены в файл pg_proaudit.conf.
Все фиксируемые события разделяются на следующие классы:
команды DDL для создания, изменения и удаления объектов СУБД (баз данных, табличных пространств, схем, таблиц, представлений, последовательностей, языков, функций)
команды управления доступом к объектам баз данных (
GRANT,REVOKE)команды DML для обращения к объектам баз данных (
INSERT,UPDATE,DELETE,SELECT,TRUNCATEдля таблиц/представлений,EXECUTEдля функций)события аутентификации/отключения от баз данных
все команды, выполняемые определённым пользователем
События безопасности могут записываться как в централизованное средство журналирования операционной системы (syslog), так и в обычные файлы. Оба варианта могут использоваться одновременно. Все записи pg_proaudit в syslog имеют метку AUDIT, что позволяет однозначно их определять. Файлы журнала событий могут записываться в форматах CEF (общий формат записи событий, Common Event Format) и CSV (значения, разделённые запятыми, Comma Separated Values). Каждое событие записывается в отдельную строку, в которой выделяются следующие поля:
дата и время события
имя пользователя (
current_user)имя базы данных
идентификатор серверного процесса (PID)
уровень важности:
INFOилиERRORпоследовательный номер команды в сеансе
номер подкоманды в сложных командах (
CREATE TABLE ... AS SELECT ...)имя оператора
тип объекта
имя объекта
результат выполнения оператора:
SUCCESS(успех) илиFAILURE(отказ)дополнительная информация, например сообщение об ошибке в случае результата
FAILUREили параметры подключения и название приложения для событияAUTHENTICATE; незавершённые попытки аутентификации помечаются как [EOF. No credentials provided] (Конец файла. Учётные данные не предоставлены)текст SQL-команды
параметры команды (например, для
PREPARE)имя пользователя (
session_user)уникальный идентификатор события (в формате UUIDv7 )
идентификатор транзакции (XID)
виртуальный идентификатор транзакции (VXID)
Событие содержит информацию о значениях session_user и current_user, которые используются в рамках пользовательского сеанса. Поэтому можно идентифицировать пользователя, даже если он сменит идентификатор пользователя с помощью команды SET ROLE.
Значения XID и VXID могут быть нулевыми, если событие не относится к транзакции (например, событие DISCONNECT).
Вы можете определить каталог, в котором будут храниться файлы журналов безопасности и настроить ротацию этих файлов. В pg_proaudit предусмотрена возможность переключения на новый файл журнала либо после определённого интервала времени, либо по достижении определённого размера файла журнала. Это позволяет организовать процедуру очистки журналов безопасности.
Пользователь Postgres Pro с атрибутом SUPERUSER должен давать доступ к расширению pg_proaudit и журналам событий безопасности только пользователям, исполняющим роль администратора информационной безопасности.
F.40.1. Установка расширения pg_proaudit
Расширение pg_proaudit включено в состав Postgres Pro Enterprise как стандартное расширение. Чтобы задействовать pg_proaudit, выполните следующие действия:
Добавьте
pg_proauditв переменнуюshared_preload_librariesв файлеpostgresql.conf:shared_preload_libraries = 'pg_proaudit'
Перезагрузите сервер базы данных для применения изменений. Чтобы убедиться, что библиотека
pg_proauditустановлена правильно, выполните следующую команду:SHOW shared_preload_libraries;
В каждой базе данных, для которой должны регистрироваться события безопасности, создайте расширение
pg_proaudit, выполнив следующий запрос:CREATE EXTENSION pg_proaudit;
Расширение
pg_proauditдобавляет несколько функций для управления файломpg_proaudit.conf, представлениеpg_proaudit_settings, показывающее текущие правилаpg_proaudit, и событийные триггеры.
F.40.2. Удаление расширения pg_proaudit
Чтобы корректно удалить pg_proaudit, выполните следующие шаги:
Удалите расширение
pg_proaudit, выполнив следующий запрос:DROP EXTENSION pg_proaudit;
Удалите
pg_proauditиз переменнойshared_preload_librariesв файлеpostgresql.conf.Пропустите этот шаг, если в кластере несколько баз данных и удалить расширение необходимо только для одной из них. В данном случае перед удалением расширения рекомендуется удалить правила регистрации событий, относящиеся к соответствующей базе данных.
F.40.3. Функции для настройки записи событий безопасности в журнал
Для настройки регистрации событий в pg_proaudit предусмотрен SQL-интерфейс, состоящий из различных функций, а также представление pg_proaudit_settings.
pg_proaudit_set_rule(db_name text, event_type text, object_type text, object_name text, role_name text, comment text)
Создаёт правило регистрации событий с заданными параметрами. Регистрация начинается сразу после завершения функции pg_proaudit_set_rule(), но файл pg_proaudit.conf не изменяется. Для сохранения изменений в файле pg_proaudit.conf вызовите функцию pg_proaudit_save().
Аргументы:
db_name— имя базы данных, для которой задаётся правило регистрации событий. Указание NULL или пустой строки означает, что регистрируются события для всех баз данных, в которых создано расширениеpg_proaudit. При указании значения current_database() события регистрируются для текущей базы данных.event_type— тип событий, которые должны регистрироваться, включая имена операторов SQL, а также названия событийAUTHENTICATEиDISCONNECT. Если указано значениеALL, NULL или пустая строка, включается регистрация всех возможных событий для объектов заданного типа. Например, для объектов типаTABLEключевое словоALLвключает регистрацию командSELECT,INSERT,UPDATE,DELETE,TRUNCATE,COPY, а такжеCREATE,ALTERиDROP. Также можно настроить регистрацию классов событий, используя следующие значения:ALL_DDL,ALL_DDL_NONTEMP,ALL_DML,ALL_DML_NONTEMP,ALL_MOD,ALL_PROC,ALL_ROLEиMISC. Полный список допустимых значений параметраevent_typeприведён в Подразделе F.40.5.object_type— тип объектов, для которых должны регистрироваться события безопасности. Если указано значениеALL, NULL или пустая строка, включается регистрация событий для всех типов объектов. Например, для регистрации всех попыток доступа к сторонним таблицам укажите тип объектаFOREIGN TABLEдля событияSELECT. Если вevent_typeпередаётсяAUTHENTICATE,DISCONNECT,SETилиRESET, вobject_typeдолжен передаваться NULL. Для всех событий, относящихся к действиям с пользователями, напримерCREATE USERилиDROP USER, в качестве типа объекта нужно передаватьROLE. Поддерживаются следующие типы объектов:COMPOSITE TYPE,DATABASE,EVENT TRIGGER,FUNCTION,INDEX,PREPARED STATEMENT,ROLE,SEQUENCE,SCHEMA,TABLE,FOREIGN TABLE,TOAST TABLE,TABLESPACE,VIEW,MATERIALIZED VIEW,CATALOG RELATIONиCATALOG FUNCTION.Примечание
Чтобы регистрировать события для объектов системного каталога, необходимо включить параметр конфигурации pg_proaudit.log_catalog_access. В противном случае эти события не будут зарегистрированы, даже если в правиле указан тип объекта
CATALOG RELATION,CATALOG FUNCTIONилиALL.object_name— имя объекта, для которого задаётся правило регистрации событий. При указании NULL или пустой строки регистрация событий включается для всех имён объектов.role_name— имя роли, для которой задаётся правило регистрации событий. Если указано, позволяет регистрировать действия, совершённые пользователем с правами этой роли. Это означает, что как минимум один из атрибутов пользовательского сеанса,session_userилиcurrent_user, должен либо совпадать сrole_name, либо прямо или косвенно являться членом указанной роли. При указании пустой строки или значения NULL включается регистрация событий для всех имён ролей, а при указании значения current_role() события регистрируются для текущей роли.comment— комментарий, описывающий созданное правило регистрации событий. Этот аргумент не влияет на выполнение правила и не отражается в журнале.
pg_proaudit_remove_rule(db_name text, event_type text, object_type text, object_name text, role_name text)
Удаляет конкретное правило регистрации событий с заданными параметрами. Для сохранения изменений в файле конфигурации pg_proaudit.conf вызовите функцию pg_proaudit_save().
Примечание
Если правило, которое вы хотите удалить, настроено для регистрации типа событий DISCONNECT, то события отключения могут продолжать регистрироваться после удаления правила. За дополнительными сведениями обратитесь к Подразделу F.40.3.1.
Аргументы:
db_name— имя базы данных, для которой удаляется правило регистрации событий.event_type— тип событий, для которого удаляется правило регистрации. Список возможных значений приведён в Подразделе F.40.5.object_type— тип объекта, для которого удаляется правило регистрации событий.object_name— имя объекта, для которого удаляется правило регистрации событий.role_name— имя роли, для которой удаляется правило регистрации событий.
pg_proaudit_show()
Возвращает список регистрируемых событий в виде таблицы. Эта функция применяется в представлении pg_proaudit_settings.
pg_proaudit_reload()
Считывает конфигурацию регистрации из файла pg_proaudit.conf. Вы должны вызывать эту функцию, если файл pg_proaudit.conf изменялся непосредственно средствами операционной системы.
pg_proaudit_reset()
Удаляет все правила регистрации событий. Для сохранения изменённой конфигурации в файле pg_proaudit.conf вызовите функцию pg_proaudit_save().
pg_proaudit_save()
Сохраняет правила регистрации событий из памяти в файле pg_proaudit.conf. Файл pg_proaudit.conf размещается в каталоге данных кластера (PGDATA). Изменить расположение файла pg_proaudit.conf нельзя.
F.40.3.1. Обработка событий отключения от базы данных
Когда настроено правило для регистрации типа событий DISCONNECT, и пользователь аутентифицируется в базе данных, то расширение pg_proaudit проверяет, удовлетворяет ли правилу соответствующее событие отключения и нужно ли его регистрировать.
Если такое событие должно быть зарегистрировано, то удаление правила не оказывает влияния на него. Событие будет зарегистрировано вне зависимости от того, существует ли правило на момент отключения.
Рассмотрим следующий пример:
Администратор настраивает следующее правило регистрации событий:
SELECT pg_proaudit_set_rule ('postgres', 'DISCONNECT', null, null, null, 'Any disconnect from the postgres DB');Пользователь подключается к базе данных
postgresи аутентифицируется в ней.Поскольку правило действует, позже будет зарегистрировано соответствующее событие отключения.
Администратор удаляет правило регистрации событий, при этом пользователь всё ещё подключён к базе данных:
SELECT pg_proaudit_remove_rule('postgres', 'DISCONNECT', null, null, null);Пользователь отключается от базы данных.
Соответствующее событие отключения регистрируется, несмотря на то, что правило было удалено.
F.40.3.2. Обработка имён объектов
Строковые представления имён базы данных, пользователя, роли и других объектов сравниваются независимо от регистра, даже если имя объекта в базе данных заключено в кавычки, и хранятся в нижнем регистре.
Строки, представляющие имена объектов, необходимо передавать функциям pg_proaudit_set_rule и pg_proaudit_remove_rule как обычные строки: одинарную кавычку необходимо удвоить без экранирования, а другие символы передаются как есть, без экранирования или переноса.
Например, правила для таблиц table1 и "TaBlE1" будут одинаковыми, а их имена можно передавать символами как верхнего, так и нижнего регистра, как и имена ролей. Перед созданием правила для баз данных pg_proaudit проверяет, действительно ли существует указанная база данных, и эта проверка чувствительна к регистру.
В следующих примерах показано создание «странных» имён объектов с указанием корректных правил для них.
CREATE TABLE "TAbLe''123"(); SELECT pg_proaudit_set_rule(current_database(), null, null, 'public.TabLe''''123', null, 'tst cmnt');
CREATE TABLE "taBlE""123"(); SELECT pg_proaudit_set_rule(null, null, null, 'public.taBlE"123', null);
CREATE SCHEMA "(BIG!) Schema"; CREATE TABLE "(BIG!) Schema"."My Tab.lE"(); SELECT pg_proaudit_set_rule(null, null, null, '(BIG!) Schema.My Tab.lE', null);
CREATE ROLE "Some '@#$%' person" WITH LOGIN; SELECT pg_proaudit_set_rule(null, 'authenticate', null, null, 'Some ''@#$%'' person');
CREATE ROLE "Some '@#$%' person" WITH SUPERUSER; \c - "Some '@#$%' person" SELECT pg_proaudit_set_rule(null, 'disconnect', null, null, current_user);
CREATE DATABASE " D B 1";
SELECT pg_proaudit_set_rule(' D B 1', 'authenticate', null, null, null);CREATE DATABASE " D b 2"; \c " D b 2" CREATE EXTENSION pg_proaudit; SELECT pg_proaudit_set_rule(current_database(), 'disconnect', null, null, null);
F.40.4. Представление pg_proaudit_settings
В этом представлении показываются текущие правила pg_proaudit, даже если они ещё не были сохранены в файл pg_proaudit.conf. Представление pg_proaudit_settings образуют следующие столбцы:
db_name(text) — имя базы данных, в которой регистрируются события.event_type(text) — тип регистрируемых событий.object_type(text) — тип объекта, для которого должны регистрироваться события безопасности.object_name(text) — имя объекта, для которого должны регистрироваться события.role_name(text) — роль, от имени которой должны выполняться регистрируемые действия.comment(text) — комментарий, описывающий созданное правило регистрации событий.
F.40.5. События безопасности
Можно настроить расширение pg_proaudit для регистрации событий безопасности определённых классов или конкретных событий, указав соответствующее значение в аргументе event_type функции pg_proaudit_set_rule().
Поддерживаются следующие классы событий безопасности:
ALL_DDL:CREATE,ALTER,DROPдля любого объекта базы данных, за исключением хранимых процедур и функций.ALL_DDL_NONTEMP: такой же класс, какALL_DDL, но его область действия ограничена только теми объектами базы данных, которые не находятся во временных схемахpg_temp_.nnnALL_DML:SELECT,INSERT,UPDATE,DELETE,TRUNCATEдля любых типов таблиц;EXECUTEдля функций и хранимых процедур.ALL_DML_NONTEMP: такой же класс, какALL_DML, но его область действия ограничена только теми объектами базы данных, которые не находятся во временных схемахpg_temp_.nnnALL_MOD:INSERT,UPDATE,DELETE,TRUNCATEдля любых типов таблиц.ALL_PROC:CREATE,ALTER,DROPдля любых функций и хранимых процедур.ALL_ROLE:CREATE,ALTER,DROPв отношенииUSER,ROLE,GROUP,PROFILE, а также выполнение командыGRANT.MISC: все события, не относящиеся к другим вышеперечисленным классам.
Поддерживаются следующие события безопасности:
ANALYZE
AUTHENTICATE
DISCONNECT
ALTER AGGREGATE
ALTER COLLATION
ALTER CONVERSION
ALTER DATABASE
ALTER DEFAULT PRIVILEGES
ALTER DOMAIN
ALTER EVENT TRIGGER
ALTER EXTENSION
ALTER FOREIGN DATA WRAPPER
ALTER FOREIGN TABLE
ALTER FUNCTION
ALTER INDEX
ALTER LANGUAGE
ALTER LARGE OBJECT
ALTER MATERIALIZED VIEW
ALTER OPERATOR
ALTER OPERATOR CLASS
ALTER OPERATOR FAMILY
ALTER POLICY
ALTER PROFILE
ALTER ROLE, ALTER USER, ALTER GROUP
ALTER RULE
ALTER SCHEMA
ALTER SEQUENCE
ALTER SERVER
ALTER SYSTEM
ALTER TABLE
ALTER TABLESPACE
ALTER TEXT SEARCH CONFIGURATION
ALTER TEXT SEARCH DICTIONARY
ALTER TEXT SEARCH PARSER
ALTER TEXT SEARCH TEMPLATE
ALTER TRIGGER
ALTER TYPE
ALTER USER MAPPING
ALTER VIEW
CHECKPOINT
CLUSTER
COMMENT
COPY
CREATE ACCESS METHOD
CREATE AGGREGATE
CREATE CAST
CREATE COLLATION
CREATE CONVERSION
CREATE DATABASE
CREATE DOMAIN
CREATE EVENT TRIGGER
CREATE EXTENSION
CREATE FOREIGN DATA WRAPPER
CREATE FOREIGN TABLE
CREATE FUNCTION
CREATE INDEX
CREATE LANGUAGE
CREATE MATERIALIZED VIEW
CREATE OPERATOR
CREATE OPERATOR CLASS
CREATE OPERATOR FAMILY
CREATE POLICY
CREATE PROFILE
CREATE ROLE, CREATE USER, CREATE GROUP
CREATE RULE
CREATE SCHEMA
CREATE SEQUENCE
CREATE SERVER
CREATE TABLE, CREATE TABLE AS, SELECT INTO
CREATE TABLESPACE
CREATE TEXT SEARCH CONFIGURATION
CREATE TEXT SEARCH DICTIONARY
CREATE TEXT SEARCH PARSER
CREATE TEXT SEARCH TEMPLATE
CREATE TRANSFORM
CREATE TRIGGER
CREATE TYPE
CREATE USER MAPPING
CREATE VIEW
DEALLOCATE
DELETE
DISCARD ALL
DISCARD PLANS
DISCARD SEQUENCES
DISCARD TEMP
DO
DROP ACCESS METHOD
DROP AGGREGATE
DROP CAST
DROP COLLATION
DROP CONVERSION
DROP DATABASE
DROP DOMAIN
DROP EVENT TRIGGER
DROP EXTENSION
DROP FOREIGN DATA WRAPPER
DROP FOREIGN TABLE
DROP FUNCTION
DROP INDEX
DROP LANGUAGE
DROP MATERIALIZED VIEW
DROP OPERATOR
DROP OPERATOR CLASS
DROP OPERATOR FAMILY
DROP OWNED
DROP POLICY
DROP PROFILE
DROP ROLE, DROP USER, DROP GROUP
DROP RULE
DROP SCHEMA
DROP SEQUENCE
DROP SERVER
DROP TABLE
DROP TABLESPACE
DROP TEXT SEARCH CONFIGURATION
DROP TEXT SEARCH DICTIONARY
DROP TEXT SEARCH PARSER
DROP TEXT SEARCH TEMPLATE
DROP TRANSFORM
DROP TRIGGER
DROP TYPE
DROP USER MAPPING
DROP VIEW
EXECUTE
FETCH
GRANT
INSERT
MOVE
PREPARE
REASSIGN OWNED
REFRESH MATERIALIZED VIEW
REINDEX
RESET
REVOKE
SECURITY LABEL
SELECT
SET
UPDATE
TRUNCATE TABLE
VACUUM
F.40.6. Параметры конфигурации журнала событий безопасности
Расширение pg_proaudit предоставляет несколько параметров конфигурации для управления файлами журналов событий безопасности. Эти параметры можно задать непосредственно в файле конфигурации postgresql.conf или посредством команды ALTER SYSTEM. Чтобы изменения вступили в силу, вызовите функцию pg_reload_conf() или перезапустите сервер баз данных. Для дополнительной настройки можно использовать параметры конфигурации syslog_ident и syslog_facility.
pg_proaudit.log_destination(string)Определяет метод регистрации событий безопасности. Возможные значения:
csvlog— записывать события безопасности в файл CSV.ceflog— записывать события безопасности в файл CEF. CEF — это открытый текстовый формат, предназначенный для записей журнала. Он содержит стандартный заголовок и переменное расширение, оформленное в виде пар ключ-значение.syslog— передавать события безопасности в syslog.cefsyslog— передавать события безопасности в формате CEF в syslog.
Этот параметр может содержать одно или несколько этих значений, разделённых запятыми. Однако обратите внимание, что значения
syslogиcefsyslogявляются взаимоисключающими. Если указаны оба, приоритет имеетcefsyslog, а значениеsyslogигнорируется.По умолчанию:
csvlogpg_proaudit.log_catalog_access(boolean)Определяет, будут ли регистрироваться обращения к объектам системного каталога в схеме
pg_catalog.Со значением
offтакие события не регистрируются, даже если есть правила для типов объектовCATALOG RELATION,CATALOG FUNCTIONилиALL.Не рекомендуется задавать для этого параметра значение
on, если вы не планируете регистрировать события для объектов системного каталога. В противном случае это может влиять на производительность Postgres Pro, даже если правила для упомянутых типов объектов отсутствуют.По умолчанию:
offpg_proaudit.log_command_text(boolean)Определяет, будет ли записываться в журнал текст команд SQL, вызывающих события безопасности.
По умолчанию включено.
pg_proaudit.log_directory(string)Задаёт путь к каталогу для хранения файлов журналов в форматах CSV и CEF. Это может быть абсолютный путь или путь, заданный относительно каталога данных (
PGDATA). Этот параметр используется, если для параметра pg_proaudit.log_destination указано значениеcsvlogилиceflog.По умолчанию:
pg_proauditpg_proaudit.log_filename(string)Определяет шаблон имён для файлов журналов событий безопасности. Этот шаблон может содержать спецпоследовательности с %, похожие на те, которые перечислены в спецификации
strftimeстандарта Open Group (http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html). Этот параметр используется, если для параметра pg_proaudit.log_destination указано значениеcsvlogилиceflog.По умолчанию:
postgresql-%Y-%m-%d_%H%M%S.logpg_proaudit.log_rotation_size(integer)Задаёт максимальный размер файла журнала, в килобайтах. По достижении этого размера
pg_proauditсоздаёт для записи событий безопасности новый файл. Если для параметра установлено значение0, создание новых файлов в зависимости от размера текущего файла отключается. Этот параметр используется, если для параметра pg_proaudit.log_destination указано значениеcsvlogилиceflog.По умолчанию: 10 МБ
pg_proaudit.log_rotation_age(integer)Задаёт максимальное время жизни файла журнала, в минутах. По истечении этого времени
pg_proauditсоздаёт новый файл для записи событий безопасности. Если для параметра установлено значение0, создание новых файлов по истечении времени отключается. Этот параметр используется, если для параметра pg_proaudit.log_destination указано значениеcsvlogилиceflog.По умолчанию: 1 день
pg_proaudit.log_truncate_on_rotation(boolean)Определяет, должны ли усекаться файлы журналов при переключении записи на уже существующий файл журнала. Если для параметра установлено значение
off,pg_proauditпродолжает запись в конец файла. Этот параметр используется, если для параметра pg_proaudit.log_destination указано значениеcsvlogилиceflog.По умолчанию:
offpg_proaudit.max_rules_count(integer)Определяет максимально допустимое количество правил. Чтобы изменение параметра вступило в силу, необходимо перезагрузить сервер базы данных.
По умолчанию: 500
F.40.7. Просмотр журнала событий безопасности
Файлы журналов событий безопасности представляют собой текстовые файлы, которые можно просмотреть средствами операционной системы. Чтобы прочитать файлы журналов на уровне SQL, вы можете применить расширение file_fdw — обёртку сторонних данных для обращения к файлам на сервере. Для этого выполните следующие действия:
Установите
file_fdwи создайте определение стороннего сервера:CREATE EXTENSION file_fdw; CREATE SERVER pg_proauditlog FOREIGN DATA WRAPPER file_fdw;
Создайте стороннюю таблицу, определив её столбцы и указав абсолютный путь к файлу журнала. Фактический путь определяется параметрами
pg_proaudit.log_directoryиpg_proaudit.log_filename.CREATE FOREIGN TABLE pg_proaudit_log ( log_time timestamp(3) with time zone, current_usr_name text, database_name text, session_pid text, error_severity text, session_line_num bigint, session_line_subcommand_num bigint, event_type text, object_type text, object_name text, status text, error_message text, query_text text, query_args text, session_usr_name text, uuid text, xid text, vxid text ) SERVER pg_proauditlog OPTIONS (filename 'absolute_file_path_to_log_file.csv', FORMAT 'csv' );
Убедитесь в том, что параметр pg_proaudit.log_destination содержит значение csvlog, включающее запись событий безопасности в файлы CSV.
F.40.8. Примеры
В качестве примера давайте настроим регистрацию следующих событий:
аутентификация/отключение от базы данных
postgresвсе действия пользователя, если как минимум один из атрибутов пользовательского сеанса,
session_userилиcurrent_user, либо явно установлен в значениеpostgres, либо прямо или косвенно является членом этой ролисоздание, изменение и удаление любых таблиц
все операции с таблицей
app_table, принадлежащей схемеpublic
Все события должны записываться в файлы в формате CSV и храниться неделю. Для обращения к журналу событий необходимо организовать доступ на уровне SQL. Для решения этой задачи выполните следующее:
Воспользовавшись psql, убедитесь, что предварительная подготовка расширения pg_proaudit в базе данных postgres выполнена:
SHOW shared_preload_libraries;
shared_preload_libraries
--------------------------
pg_proaudit
\dx pg_proaudit
List of installed extensions
Name | Version | Schema | Description
-------------+---------+--------+---------------------------------
pg_proaudit | 2.0 | public | provides auditing functionalityДобавьте следующие строки в файл конфигурации postgresql.conf:
pg_proaudit.log_destination = 'csvlog' pg_proaudit.log_directory = 'audit' pg_proaudit.log_filename = 'audit-%u.csv' pg_proaudit.log_rotation_age = 1440 pg_proaudit.log_rotation_size = 0 pg_proaudit.log_truncate_on_rotation = on pg_proaudit.log_command_text = on
Чтобы изменения вступили в силу, выполните:
SELECT pg_reload_conf();
Проверьте, были ли установлены желаемые значения следующих параметров:
SHOW pg_proaudit.log_destination; SHOW pg_proaudit.log_directory; SHOW pg_proaudit.log_filename; SHOW pg_proaudit.log_rotation_age; SHOW pg_proaudit.log_rotation_size; SHOW pg_proaudit.log_truncate_on_rotation; SHOW pg_proaudit.log_command_text;
Предположим, что ваша переменная окружения PGDATA указывает на каталог данных кластера. Так как в pg_proaudit.log_directory задан относительный путь, файлы журналов будут находиться в каталоге $PGDATA/audit. Создадим пустые файлы для семи дней недели и сделаем их доступными только для владельца:
touch $PGDATA/audit/audit-1.csv touch $PGDATA/audit/audit-2.csv touch $PGDATA/audit/audit-3.csv touch $PGDATA/audit/audit-4.csv touch $PGDATA/audit/audit-5.csv touch $PGDATA/audit/audit-6.csv touch $PGDATA/audit/audit-7.csv chmod 600 $PGDATA/audit/audit-*.csv
Создайте таблицу для чтения записей журнала:
CREATE TABLE pg_proaudit_log ( log_time timestamp(3) with time zone, current_usr_name text, database_name text, session_pid text, error_severity text, session_line_num bigint, session_line_subcommand_num bigint, event_type text, object_type text, object_name text, status text, error_message text, query_text text, query_args text, session_usr_name text, uuid text, xid text, vxid text );
Установите расширение file_fdw и создайте сторонний сервер:
CREATE EXTENSION file_fdw; CREATE SERVER pg_proauditlog FOREIGN DATA WRAPPER file_fdw;
Теперь создадим для таблицы pg_proaudit_log семь дочерних сторонних таблиц, для каждого дня недели:
CREATE FOREIGN TABLE pg_proaudit_log_1 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-1.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_2 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-2.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_3 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-3.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_4 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-4.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_5 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-5.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_6 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-6.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_7 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-7.csv', FORMAT 'csv');
Чтобы настроить регистрацию интересующих событий безопасности, подключитесь к базе данных postgres и выполните следующие команды:
SELECT pg_proaudit_set_rule (current_database(), 'AUTHENTICATE', null, null, null, 'Any authentication in the current DB'); SELECT pg_proaudit_set_rule (current_database(), 'DISCONNECT', null, null, null, 'Any disconnect from the current DB'); SELECT pg_proaudit_set_rule (current_database(), 'ALL', 'TABLE', null, null, 'Any operations with any table in the current DB'); SELECT pg_proaudit_set_rule (current_database(), 'ALL', null, null, 'postgres', 'Any operation by "postgres" user in the current DB');
Создайте таблицу app_table и включите регистрацию всех операций с этой таблицей:
CREATE TABLE app_table (id int, name text); SELECT pg_proaudit_set_rule (current_database(), 'ALL', null, 'public.app_table', null);
Проверьте, работает ли регистрация событий должным образом:
SELECT * FROM pg_proaudit_settings; db_name | event_type | object_type | object_name | role_name | comment ----------+--------------+-------------+------------------+-----------+---------------------------------------------------- postgres | authenticate | ALL | | | Any authentication in the current DB postgres | disconnect | ALL | | | Any disconnect from the current DB postgres | ALL | table | | | Any operations with any table in the current DB postgres | ALL | ALL | | postgres | Any operation by "postgres" user in the current DB postgres | ALL | ALL | public.app_table | | (5 rows)
Сохраните эти правила регистрации событий в файле pg_proaudit.conf, чтобы они не были потеряны при перезапуске сервера:
SELECT pg_proaudit_save();
Выполним несколько запросов, обращающихся к таблице app_table:
INSERT INTO app_table VALUES (1, 'first'); SELECT * FROM app_table;
Проверьте записи в журнале, относящиеся к таблице app_table:
SELECT to_char(log_time, 'DD.MM.YY HH24:MI:SS') AS when, current_usr_name,
session_pid, event_type, query_text, session_usr_name
FROM pg_proaudit_log
WHERE object_name = 'public.app_table';
when | current_usr_name | session_pid | event_type | query_text | session_usr_name
-------------------+------------------+-------------+--------------+---------------------------------------------+------------------
27.09.23 12:44:27 | postgres | 2010 | CREATE TABLE | CREATE TABLE app_table (id int, name text); | postgres
27.09.23 12:45:55 | postgres | 2010 | INSERT | INSERT INTO app_table VALUES (1, 'first'); | postgres
27.09.23 12:46:00 | postgres | 2010 | SELECT | SELECT * FROM app_table; | postgres
(3 rows)Мы настроили еженедельную ротацию файлов журналов с переключением файлов журналов каждый день. Это означает, что запросы к таблице pg_proaudit_log будут возвращать только события, произошедшие за последнюю неделю. Более старые события будут автоматически удаляться при ротации файлов. Для дополнительного ограничения доступа к определённым записям журнала вы можете создать отдельные представления на базе таблицы pg_proaudit_log и разрешить чтение этих представлений, используя встроенные механизмы управления доступом Postgres Pro.
F.40. pg_proaudit
- F.40.1. Installing the
pg_proauditExtension- F.40.2. Uninstalling the
pg_proauditExtension- F.40.3. Functions to Configure Security Event Logging
- F.40.4. pg_proaudit_settings View
- F.40.5. Security Events
- F.40.6. Security Event Log Configuration Parameters
- F.40.7. Viewing Security Event Log
- F.40.8. Examples
- F.40.2. Uninstalling the
The pg_proaudit extension enables detailed logging of various security events.
pg_proaudit works in parallel with the standard PostgreSQL logging solutions (logging collector) and does not depend on them. Security event log of the pg_proaudit extension is stored separately from the server log. At the Postgres Pro Enterprise startup, pg_proaudit launches a special background process to log security events.
Logging rules are stored in the pg_proaudit.conf configuration file located in the cluster data directory (PGDATA). It is a text file that can be edited directly using operating system facilities. To modify the file using SQL, you can use several pg_proaudit functions. The pg_proaudit_settings view displays the current pg_proaudit rules, even if they have not been saved into the pg_proaudit.conf file yet.
All the logged events belong to the following classes:
DDL commands for creating, changing, and deleting DBMS objects (databases, tablespaces, schemas, tables, views, sequences, languages, functions)
access control commands for database objects (
GRANT,REVOKE)DML commands for access to database objects (
INSERT,UPDATE,DELETE,SELECT,TRUNCATEfor tables and/or views,EXECUTEfor functions)database authentication/disconnection events
all commands executed by a particular user
Security events can be logged both in the centralized logging solution of the operating system (syslog) and in the standard file-system files. Event logs can be written both into the syslog and into the files simultaneously. For clear identification, all pg_proaudit records in the syslog are marked with AUDIT. Event log files can be written in the CEF (Common Event Format) and CSV (Comma-Separated Values) formats. Each event is logged on a separate line that contains the following fields:
date and time of the event
current user name
database name
server process ID (PID)
severity level:
INFOorERRORserial number of the command in a session
subcommand number in complex commands (
CREATE TABLE ... AS SELECT ...)operator name
object type
object name
operator execution results:
SUCCESSorFAILUREadditional information like error message in case of
FAILUREor connection parameters and the application name for theAUTHENTICATEevent; unfinished authentication attempts are marked as [EOF. No credentials provided]text of the SQL command
parameters of the command (for example, for
PREPARE)session user name
unique ID of the event (in the UUIDv7 format)
transaction ID (XID)
virtual transaction ID (VXID)
An event contains the information about both session_user and current_user of the session. Therefore, it will be possible to identify the user, even if they execute the SET ROLE command to change user identifier.
The XID and VXID values can be zero if an event does not relate to a transaction (e. g. the DISCONNECT event).
You can define a directory to store security log files and set up log file rotation. pg_proaudit can switch to a new log file either after the specified time interval, or when the specified size of the log file is exceeded. This enables you to define a workflow for cleaning up security event logs.
Postgres Pro user with the SUPERUSER attribute should grant access to the pg_proaudit extension and security event log files only to the user with the information security administrator role.
F.40.1. Installing the pg_proaudit Extension
The pg_proaudit extension is a built-in extension included into Postgres Pro Enterprise. To enable pg_proaudit, complete the following steps:
Add
pg_proauditto theshared_preload_librariesvariable in thepostgresql.conffile:shared_preload_libraries = 'pg_proaudit'
Restart the database server for the changes to take effect. To verify that the
pg_proauditlibrary was installed correctly, you can run the following command:SHOW shared_preload_libraries;
In each database for which you are going to log security events, create the
pg_proauditextension using the following query:CREATE EXTENSION pg_proaudit;
The
pg_proauditextension adds several functions for managing thepg_proaudit.conffile, thepg_proaudit_settingsview that displays the currentpg_proauditrules and event triggers.
F.40.2. Uninstalling the pg_proaudit Extension
To properly uninstall pg_proaudit, complete the following steps:
Delete the
pg_proauditextension using the following query:DROP EXTENSION pg_proaudit;
Remove
pg_proauditfrom theshared_preload_librariesvariable in thepostgresql.conffile.Skip this step if you have several databases in the cluster and you want to remove the extension only for one of them. In this case, it is recommended to remove logging rules related to the corresponding database prior to uninstalling the extension.
F.40.3. Functions to Configure Security Event Logging
To configure security event logging, pg_proaudit provides an SQL interface that consists of several functions and the pg_proaudit_settings view.
pg_proaudit_set_rule(db_name text, event_type text, object_type text, object_name text, role_name text, comment text)
Creates the logging rule with the specified parameters. When the pg_proaudit_set_rule() function completes, security event logging starts immediately, but the pg_proaudit.conf file is not updated. To save the changes in the pg_proaudit.conf file, call the pg_proaudit_save() function.
Arguments:
db_name— name of the database for which the logging rule is established. An empty string or NULL specified in this argument means that events are logged for all databases where thepg_proauditextension is created. When set to current_database(), events for the current database are logged.event_type— type of the event that needs to be logged, including SQL operator names, as well asAUTHENTICATEandDISCONNECTevents. When set toALL, as well as when an empty string or NULL is specified, enables logging for all events available for the specified object type. For example, for theTABLEobject type, theALLkeyword enables logging for commandsSELECT,INSERT,UPDATE,DELETE,TRUNCATE,COPY, as well asCREATE,ALTER,DROP. You can also set up logging of event classes by specifying the following values:ALL_DDL,ALL_DDL_NONTEMP,ALL_DML,ALL_DML_NONTEMP,ALL_MOD,ALL_PROC,ALL_ROLE, andMISC. For the full list of possibleevent_typevalues, see Section F.40.5.object_type— type of the object for which security events need to be logged. When set toALL, as well as when an empty string or the NULL is specified, enables logging of events for all object types. For example, specifyFOREIGN TABLEobject type for theSELECTevent to log all attempts to access foreign tables. Use NULL ifevent_typeis set toAUTHENTICATE,DISCONNECT,SET, orRESET, and theROLEvalue for all events that reference user actions, such asCREATE USERorDROP USER. The following object types are supported:COMPOSITE TYPE,DATABASE,EVENT TRIGGER,FUNCTION,INDEX,PREPARED STATEMENT,ROLE,SEQUENCE,SCHEMA,TABLE,FOREIGN TABLE,TOAST TABLE,TABLESPACE,VIEW,MATERIALIZED VIEW,CATALOG RELATION, andCATALOG FUNCTION.Note
To log security events for system catalog objects, it is required to enable the pg_proaudit.log_catalog_access configuration parameter. Otherwise, these events will not be logged, even if the
CATALOG RELATION,CATALOG FUNCTION, orALLobject type is specified in the rule.object_name— name of the object for which the logging rule is established. When an empty string or NULL is specified, enables logging of events for all object names.role_name— name of the role for which the logging rule is established. If specified, allows logging the actions caused by the user who has the privileges of the role. This means that at least one of the user session attributes,session_userorcurrent_user, should either be equal to therole_name, or be directly or indirectly a member of this role. When an empty string or NULL is specified, enables logging of actions caused by any user. When set to current_role, the logging rule is established for the user current role.comment— comment to describe the created logging rule. This argument does not affect the rule execution and is not reflected in the log.
pg_proaudit_remove_rule(db_name text, event_type text, object_type text, object_name text, role_name text)
Removes the specific logging rule with the set parameters. To save the changes in the pg_proaudit.conf file, call the pg_proaudit_save() function.
Note
If the rule that you want to remove is configured to log the DISCONNECT event type, then disconnect events may still be logged after the rule is removed. For additional information, see Section F.40.3.1.
Arguments:
db_name— name of the database for which the logging rule needs to be removed.event_type— type of the event for which the logging rule needs to be removed. For the full list of possibleevent_typevalues, see Section F.40.5.object_type— type of the object for which the logging rule needs to be removed.object_name— name of the object for which the logging rule needs to be removed.role_name— name of the role for which the logging rule needs to be removed.
pg_proaudit_show()
Returns logged events in a table view. This function is used by the pg_proaudit_settings view.
pg_proaudit_reload()
Reads logging configuration from the pg_proaudit.conf file. You must call this function if the pg_proaudit.conf file was modified manually using the operating system facilities.
pg_proaudit_reset()
Removes all logging rules. To save information about the canceled logging in the pg_proaudit.conf file, call the pg_proaudit_save() function.
pg_proaudit_save()
Saves logging rules from memory into the pg_proaudit.conf file. The pg_proaudit.conf file is located in the cluster data directory (PGDATA). You cannot change the pg_proaudit.conf file location.
F.40.3.1. Handling Database Disconnection Events
When a logging rule is configured for DISCONNECT event type, and a user authenticates in a database, then the pg_proaudit extension checks whether the corresponding disconnection event satisfies the rule and must be logged.
If the event must be logged, then the removal of the logging rule has no effect on the event. This event will be logged no matter if the logging rule exists at the moment of disconnect.
Consider the following example:
An administrator configures the following logging rule:
SELECT pg_proaudit_set_rule ('postgres', 'DISCONNECT', null, null, null, 'Any disconnect from the postgres DB');A user connects to the
postgresdatabase and goes through authentication.For the rule in effect, a corresponding disconnection event will be logged later.
The administrator removes the logging rule, while the user is still connected to the database:
SELECT pg_proaudit_remove_rule('postgres', 'DISCONNECT', null, null, null);The user disconnects from the database.
The corresponding disconnection event is logged despite the removal of the logging rule.
F.40.3.2. Handling Object Names
Comparison of string representations of names for database, user, role and other objects is case-insensitive even if the object name in the database is enclosed in quotes. These string representations are stored as lower-case strings.
Strings representing object names need to be passed to functions pg_proaudit_set_rule and pg_proaudit_remove_rule as regular strings: a single quote needs repeating, and other characters are passed as is, without escaping or wrapping.
For example, rules for tables table1 and "TaBlE1" will be the same, and their names can be passed in upper-case or lower-case characters. The same holds for roles. As for databases, before creating a rule, pg_proaudit checks whether this database actually exists, and this check is case-sensitive.
The following examples illustrate creation of "weird" object names and specifying correct audit rules for them.
create table "TAbLe''123"(); SELECT pg_proaudit_set_rule(current_database(), null, null, 'public.TabLe''''123', null, 'tst cmnt');
create table "taBlE""123"(); SELECT pg_proaudit_set_rule(null, null, null, 'public.taBlE"123', null);
create schema "(BIG!) Schema"; create table "(BIG!) Schema"."My Tab.lE"(); SELECT pg_proaudit_set_rule(null, null, null, '(BIG!) Schema.My Tab.lE', null);
create role "Some '@#$%' person" with login; SELECT pg_proaudit_set_rule(null, 'authenticate', null, null, 'Some ''@#$%'' person');
create role "Some '@#$%' person" with superuser; \c - "Some '@#$%' person" SELECT pg_proaudit_set_rule(null, 'disconnect', null, null, current_user);
create database " D B 1";
SELECT pg_proaudit_set_rule(' D B 1', 'authenticate', null, null, null);
create database " D b 2"; \c " D b 2" create extension pg_proaudit; SELECT pg_proaudit_set_rule(current_database(), 'disconnect', null, null, null);
F.40.4. pg_proaudit_settings View
This view displays the current pg_proaudit rules, even if they have not been saved into the pg_proaudit.conf file yet. The pg_proaudit_settings view consists of the following columns:
db_name(text) — name of the database for which to log security events.event_type(text) — event type to log.object_type(text) — type of the object for which security events are to be logged.object_name(text) — name of the object for which security events are to be logged.role_name(text) — the role on behalf of which logged actions are performed.comment(text) — comment to describe the created logging rule.
F.40.5. Security Events
You can configure the pg_proaudit extension to log classes of security events and specific events by specifying the respective value in the event_type argument of the pg_proaudit_set_rule() function.
The following classes of security events are supported:
ALL_DDL:CREATE,ALTER,DROPfor any database object except stored procedures and functions.ALL_DDL_NONTEMP: same asALL_DDLbut the scope is limited to the objects that are not contained inpg_temp_temporary schemas.nnnALL_DML:SELECT,INSERT,UPDATE,DELETE,TRUNCATEfor any table type;EXECUTEfor functions and stored procedures.ALL_DML_NONTEMP: same asALL_DMLbut the scope is limited to the objects that are not contained inpg_temp_temporary schemas.nnnALL_MOD:INSERT,UPDATE,DELETE,TRUNCATEfor any table type.ALL_PROC:CREATE,ALTER,DROPfor any function and stored procedure.ALL_ROLE:CREATE,ALTER,DROPforUSER,ROLE,GROUP,PROFILE, as well as execution of theGRANTcommand.MISC: all events not related to any of the other classes mentioned above.
The following specific security events are supported:
ANALYZE
AUTHENTICATE
DISCONNECT
ALTER AGGREGATE
ALTER COLLATION
ALTER CONVERSION
ALTER DATABASE
ALTER DEFAULT PRIVILEGES
ALTER DOMAIN
ALTER EVENT TRIGGER
ALTER EXTENSION
ALTER FOREIGN DATA WRAPPER
ALTER FOREIGN TABLE
ALTER FUNCTION
ALTER INDEX
ALTER LANGUAGE
ALTER LARGE OBJECT
ALTER MATERIALIZED VIEW
ALTER OPERATOR
ALTER OPERATOR CLASS
ALTER OPERATOR FAMILY
ALTER POLICY
ALTER PROFILE
ALTER ROLE, ALTER USER, ALTER GROUP
ALTER RULE
ALTER SCHEMA
ALTER SEQUENCE
ALTER SERVER
ALTER SYSTEM
ALTER TABLE
ALTER TABLESPACE
ALTER TEXT SEARCH CONFIGURATION
ALTER TEXT SEARCH DICTIONARY
ALTER TEXT SEARCH PARSER
ALTER TEXT SEARCH TEMPLATE
ALTER TRIGGER
ALTER TYPE
ALTER USER MAPPING
ALTER VIEW
CHECKPOINT
CLUSTER
COMMENT
COPY
CREATE ACCESS METHOD
CREATE AGGREGATE
CREATE CAST
CREATE COLLATION
CREATE CONVERSION
CREATE DATABASE
CREATE DOMAIN
CREATE EVENT TRIGGER
CREATE EXTENSION
CREATE FOREIGN DATA WRAPPER
CREATE FOREIGN TABLE
CREATE FUNCTION
CREATE INDEX
CREATE LANGUAGE
CREATE MATERIALIZED VIEW
CREATE OPERATOR
CREATE OPERATOR CLASS
CREATE OPERATOR FAMILY
CREATE POLICY
CREATE PROFILE
CREATE ROLE, CREATE USER, CREATE GROUP
CREATE RULE
CREATE SCHEMA
CREATE SEQUENCE
CREATE SERVER
CREATE TABLE, CREATE TABLE AS, SELECT INTO
CREATE TABLESPACE
CREATE TEXT SEARCH CONFIGURATION
CREATE TEXT SEARCH DICTIONARY
CREATE TEXT SEARCH PARSER
CREATE TEXT SEARCH TEMPLATE
CREATE TRANSFORM
CREATE TRIGGER
CREATE TYPE
CREATE USER MAPPING
CREATE VIEW
DEALLOCATE
DELETE
DISCARD ALL
DISCARD PLANS
DISCARD SEQUENCES
DISCARD TEMP
DO
DROP ACCESS METHOD
DROP AGGREGATE
DROP CAST
DROP COLLATION
DROP CONVERSION
DROP DATABASE
DROP DOMAIN
DROP EVENT TRIGGER
DROP EXTENSION
DROP FOREIGN DATA WRAPPER
DROP FOREIGN TABLE
DROP FUNCTION
DROP INDEX
DROP LANGUAGE
DROP MATERIALIZED VIEW
DROP OPERATOR
DROP OPERATOR CLASS
DROP OPERATOR FAMILY
DROP OWNED
DROP POLICY
DROP PROFILE
DROP ROLE, DROP USER, DROP GROUP
DROP RULE
DROP SCHEMA
DROP SEQUENCE
DROP SERVER
DROP TABLE
DROP TABLESPACE
DROP TEXT SEARCH CONFIGURATION
DROP TEXT SEARCH DICTIONARY
DROP TEXT SEARCH PARSER
DROP TEXT SEARCH TEMPLATE
DROP TRANSFORM
DROP TRIGGER
DROP TYPE
DROP USER MAPPING
DROP VIEW
EXECUTE
FETCH
GRANT
INSERT
MOVE
PREPARE
REASSIGN OWNED
REFRESH MATERIALIZED VIEW
REINDEX
RESET
REVOKE
SECURITY LABEL
SELECT
SET
UPDATE
TRUNCATE TABLE
VACUUM
F.40.6. Security Event Log Configuration Parameters
The pg_proaudit extension provides several configuration parameters for managing security event log files. These parameters can be set in the postgresql.conf configuration file, or with the help of the ALTER SYSTEM command. For the changes to take effect, call the pg_reload_conf() function or restart the database server. For additional configuration, the syslog_ident and syslog_facility configuration parameters can be used.
pg_proaudit.log_destination(string)Defines the method for logging security events. Possible values are:
csvlog— log security events in a CSV file.ceflog— log security events in a CEF file. CEF is an open text-based format designed for log records. It contains a standard header and a variable extension formatted as key-value pairs.syslog— log security events in syslog.cefsyslog— log security events in the CEF format in syslog.
You can specify one or more values separated by commas. Note, however, that
syslogandcefsyslogare mutually exclusive. If both are specified,cefsyslogtakes precedence andsyslogis ignored.Default:
csvlogpg_proaudit.log_catalog_access(boolean)Specifies whether to log access to system catalog objects in the
pg_catalogschema.When set to
off, no events will be logged, even if there are rules for theCATALOG RELATION,CATALOG FUNCTION, orALLobject types.It is not recommended to set the parameter to
on, if you do not plan to log events for system catalog objects. Doing otherwise may impact Postgres Pro performance, even if there are no rules for the aforementioned object types.Default:
offpg_proaudit.log_command_text(boolean)Specifies whether to log the SQL command text for security events.
Default:
onpg_proaudit.log_directory(string)Specifies the path to the directory that stores CSV and CEF log files. This can be an absolute path or a relative path to the cluster data directory (
PGDATA). This parameter is used if thecsvlogorceflogvalue is specified in the pg_proaudit.log_destination parameter.Default:
pg_proauditpg_proaudit.log_filename(string)Defines the filenames of the created security event log files. The filename template can contain %-escapes, similar to the ones listed in the
strftimespecification of the Open Group (http://pubs.opengroup.org/onlinepubs/009695399/functions/strftime.html). This parameter is used if thecsvlogorceflogvalue is specified in the pg_proaudit.log_destination parameter.Default:
postgresql-%Y-%m-%d_%H%M%S.logpg_proaudit.log_rotation_size(integer)Sets the maximum size of a log file, in kilobytes. When this size is achieved,
pg_proauditcreates a new file for logging security events. If set to0, disables size-based creation of new log files. This parameter is used if thecsvlogorceflogvalue is specified in the pg_proaudit.log_destination parameter.Default: 10MB
pg_proaudit.log_rotation_age(integer)Sets the maximum lifetime of a log file, in minutes. After this timeframe is elapsed,
pg_proauditcreates a new file for logging security events. If set to0, disables time-based creation of new log files. This parameter is used if thecsvlogorceflogvalue is specified in the pg_proaudit.log_destination parameter.Default: 1 day
pg_proaudit.log_truncate_on_rotation(boolean)Specifies whether to truncate log files when logging is switched to an existing log file. If set to
off,pg_proauditappends new log entries to the end of the file. This parameter is used if thecsvlogorceflogvalue is specified in the pg_proaudit.log_destination parameter.Default:
offpg_proaudit.max_rules_count(integer)Specifies the maximum number of rules allowed. For the parameter changes to take effect, the database server must be restarted.
Default: 500
F.40.7. Viewing Security Event Log
Security event log files are text files that can be viewed by the operating system facilities. To access log files using SQL, you can use the file_fdw extension — a foreign data wrapper for accessing files on the database server. To use this method, complete the following steps:
Install the
file_fdwand create an external server:CREATE EXTENSION file_fdw; CREATE SERVER pg_proauditlog FOREIGN DATA WRAPPER file_fdw;
Create a foreign table, specifying the columns and the absolute path to the log file. The actual log file location is determined by the
pg_proaudit.log_directoryandpg_proaudit.log_filenameparameters.CREATE FOREIGN TABLE pg_proaudit_log ( log_time timestamp(3) with time zone, current_usr_name text, database_name text, session_pid text, error_severity text, session_line_num bigint, session_line_subcommand_num bigint, event_type text, object_type text, object_name text, status text, error_message text, query_text text, query_args text, session_usr_name text, uuid text, xid text, vxid text ) SERVER pg_proauditlog OPTIONS (filename 'absolute_file_path_to_log_file.csv', FORMAT 'csv' );
Make sure that the pg_proaudit.log_destination parameter contains the csvlog value, which enables writing security event logs to CSV files.
F.40.8. Examples
As an example, let's set up logging for the following security events:
authentications/disconnections to the
postgresdatabaseall actions of the user if at least one of the user session attributes,
session_userorcurrent_user, is either explicitly set to thepostgresrole, or is directly or indirectly a member of this rolecreating, updating, and deleting any tables
all operations on the
app_tabletable that belongs to thepublicschema
All events must be logged in the CSV format and stored for a week. It is required to set up SQL access to the security event log. To complete the scenario, do the following:
In psql, check that the preliminary setup of the pg_proaudit extension is complete in the postgres database:
SHOW shared_preload_libraries;
shared_preload_libraries
--------------------------
pg_proaudit
\dx pg_proaudit
List of installed extensions
Name | Version | Schema | Description
-------------+---------+--------+---------------------------------
pg_proaudit | 2.0 | public | provides auditing functionality
Add the following lines to the postgresql.conf configuration file:
pg_proaudit.log_destination = 'csvlog' pg_proaudit.log_directory = 'audit' pg_proaudit.log_filename = 'audit-%u.csv' pg_proaudit.log_rotation_age = 1440 pg_proaudit.log_rotation_size = 0 pg_proaudit.log_truncate_on_rotation = on pg_proaudit.log_command_text = on
For the changes to take effect, run the following query:
SELECT pg_reload_conf();
Check that the following parameters are set as expected:
SHOW pg_proaudit.log_destination; SHOW pg_proaudit.log_directory; SHOW pg_proaudit.log_filename; SHOW pg_proaudit.log_rotation_age; SHOW pg_proaudit.log_rotation_size; SHOW pg_proaudit.log_truncate_on_rotation; SHOW pg_proaudit.log_command_text;
Suppose your PGDATA environment variable points to the cluster data directory. Since the pg_proaudit.log_directory defines a relative path to the log files, they will be located in the $PGDATA/audit directory. Let's create an empty file for each day of the week and make them available to their owner only:
touch $PGDATA/audit/audit-1.csv touch $PGDATA/audit/audit-2.csv touch $PGDATA/audit/audit-3.csv touch $PGDATA/audit/audit-4.csv touch $PGDATA/audit/audit-5.csv touch $PGDATA/audit/audit-6.csv touch $PGDATA/audit/audit-7.csv chmod 600 $PGDATA/audit/audit-*.csv
Create a table for reading log entries:
CREATE TABLE pg_proaudit_log ( log_time timestamp(3) with time zone, current_usr_name text, database_name text, session_pid text, error_severity text, session_line_num bigint, session_line_subcommand_num bigint, event_type text, object_type text, object_name text, status text, error_message text, query_text text, query_args text, session_usr_name text, uuid text, xid text, vxid text );
Install the file_fdw extension and create an external server:
CREATE EXTENSION file_fdw; CREATE SERVER pg_proauditlog FOREIGN DATA WRAPPER file_fdw;
Now let's create seven child foreign tables for the pg_proaudit_log table, for each day of the week:
CREATE FOREIGN TABLE pg_proaudit_log_1 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-1.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_2 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-2.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_3 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-3.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_4 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-4.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_5 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-5.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_6 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-6.csv', FORMAT 'csv'); CREATE FOREIGN TABLE pg_proaudit_log_7 () INHERITS (pg_proaudit_log) SERVER pg_proauditlog OPTIONS (filename '/path_to_PGDATA/audit/audit-7.csv', FORMAT 'csv');
To set up logging for the required security events, connect to the postgres database and execute the following commands:
SELECT pg_proaudit_set_rule (current_database(), 'AUTHENTICATE', null, null, null, 'Any authentication in the current DB'); SELECT pg_proaudit_set_rule (current_database(), 'DISCONNECT', null, null, null, 'Any disconnect from the current DB'); SELECT pg_proaudit_set_rule (current_database(), 'ALL', 'TABLE', null, null, 'Any operations with any table in the current DB'); SELECT pg_proaudit_set_rule (current_database(), 'ALL', null, null, 'postgres', 'Any operation by "postgres" user in the current DB');
Create the app_table table and enable logging for all operations on this table:
CREATE TABLE app_table (id int, name text); SELECT pg_proaudit_set_rule (current_database(), 'ALL', null, 'public.app_table', null);
Check that event logging is configured as expected:
SELECT * FROM pg_proaudit_settings; db_name | event_type | object_type | object_name | role_name | comment ----------+--------------+-------------+------------------+-----------+---------------------------------------------------- postgres | authenticate | ALL | | | Any authentication in the current DB postgres | disconnect | ALL | | | Any disconnect from the current DB postgres | ALL | table | | | Any operations with any table in the current DB postgres | ALL | ALL | | postgres | Any operation by "postgres" user in the current DB postgres | ALL | ALL | public.app_table | | (5 rows)
Save these logging rules into the pg_proaudit.conf file, so that they are not lost after the server restart:
SELECT pg_proaudit_save();
Let's run several queries on the app_table table:
INSERT INTO app_table VALUES (1, 'first'); SELECT * FROM app_table;
Check the log entries for the app_table table:
SELECT to_char(log_time, 'DD.MM.YY HH24:MI:SS') AS when, current_usr_name,
session_pid, event_type, query_text, session_usr_name
FROM pg_proaudit_log
WHERE object_name = 'public.app_table';
when | current_usr_name | session_pid | event_type | query_text | session_usr_name
-------------------+------------------+-------------+--------------+---------------------------------------------+------------------
27.09.23 12:44:27 | postgres | 2010 | CREATE TABLE | CREATE TABLE app_table (id int, name text); | postgres
27.09.23 12:45:55 | postgres | 2010 | INSERT | INSERT INTO app_table VALUES (1, 'first'); | postgres
27.09.23 12:46:00 | postgres | 2010 | SELECT | SELECT * FROM app_table; | postgres
(3 rows)
We have set up a weekly rotation of log files, with the log file switched once a day. It means that queries to the pg_proaudit_log table will return only those security events that have happened in the latest week. Older events will be automatically removed at log file rotation. To define additional access constraints for specific log entries, you can create separate views based on queries to the pg_proaudit_log table and grant read rights to such views using built-in Postgres Pro access control methods.