Auditing and Connection Logging

To answer "who deleted this table and when" or "where do the failed logins keep coming from", recording must be turned on in advance. Turning it on after the fact does not help. In all three databases you decide what to record (the policy) and where to write it (the destination), and because records keep accumulating, you also decide retention and cleanup. Recording every statement is costly in performance and space, so start with logins, privilege and account changes, DDL, and changes to critical tables.

Oracle

Required privileges: the AUDIT_ADMIN role to manage policies; AUDIT_VIEWER or AUDIT_ADMIN to query records.

Unified Auditing status and enabled policies

Unified Auditing in 12c+ gathers all audit records into the single UNIFIED_AUDIT_TRAIL. The 19c default is mixed mode, where Unified policies and the legacy method (the AUDIT_TRAIL parameter) work together.

SELECT value FROM v$option WHERE parameter = 'Unified Auditing';   -- TRUE means pure Unified mode

SELECT policy_name, enabled_option, entity_name, entity_type, success, failure
FROM audit_unified_enabled_policies
ORDER BY policy_name;
  • ORA_SECURECONFIG (privilege and account changes, etc.) and ORA_LOGON_FAILURES (failed logins) are enabled by default.
  • View a policy's contents with SELECT policy_name, audit_option, object_schema, object_name FROM audit_unified_policies WHERE policy_name = 'ORA_SECURECONFIG';.

Creating and enabling policies

-- changes to a critical table
CREATE AUDIT POLICY orders_dml_pol
  ACTIONS INSERT ON sales.orders, UPDATE ON sales.orders, DELETE ON sales.orders;
AUDIT POLICY orders_dml_pol EXCEPT app_batch;      -- exclude the batch account

-- DDL and use of powerful privileges
CREATE AUDIT POLICY ddl_pol
  PRIVILEGES DROP ANY TABLE, ALTER ANY TABLE
  ACTIONS CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE TABLE;
AUDIT POLICY ddl_pol;

-- logins (failures only, since recording successes produces a large volume)
CREATE AUDIT POLICY logon_pol ACTIONS LOGON;
AUDIT POLICY logon_pol WHENEVER NOT SUCCESSFUL;

-- disable
NOAUDIT POLICY orders_dml_pol;
  • Enable a policy only for specific users with AUDIT POLICY ... BY user1, user2, or exclude specific users with EXCEPT. The two cannot be combined.
  • A policy applies from sessions that connect after it is enabled (object-level policies apply immediately).

WARNING Auditing SELECT or frequently run DML writes a record for every statement, so the SYSAUX tablespace grows quickly and performance drops. Narrow the target tables and users when enabling.

Querying audit records

SELECT event_timestamp, dbusername, os_username, userhost, client_program_name,
       action_name, object_schema, object_name, return_code,
       unified_audit_policies, SUBSTR(sql_text, 1, 100) AS sql_text
FROM unified_audit_trail
WHERE event_timestamp > SYSTIMESTAMP - INTERVAL '1' DAY
ORDER BY event_timestamp DESC;
  • A return_code of 0 means success; otherwise it is the error number.
  • This view is slow when large. Always add an event_timestamp condition.

Failed logins

SELECT dbusername, userhost, client_program_name, return_code,
       COUNT(*) AS failures, MAX(event_timestamp) AS last_failure
FROM unified_audit_trail
WHERE action_name = 'LOGON' AND return_code <> 0
  AND event_timestamp > SYSTIMESTAMP - INTERVAL '7' DAY
GROUP BY dbusername, userhost, client_program_name, return_code
ORDER BY failures DESC;
  • 1017 means wrong user name or password, and 28000 means the account is locked. Repeated 1017 from one host indicates an application holding an old password, or a brute-force attempt.

Cleaning up audit records (DBMS_AUDIT_MGMT)

BEGIN
  DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP(
    audit_trail_type  => DBMS_AUDIT_MGMT.AUDIT_TRAIL_UNIFIED,
    last_archive_time => SYSTIMESTAMP - INTERVAL '90' DAY);
  DBMS_AUDIT_MGMT.CLEAN_AUDIT_TRAIL(
    audit_trail_type        => DBMS_AUDIT_MGMT.AUDIT_TRAIL_UNIFIED,
    use_last_arch_timestamp => TRUE);
END;
/

WARNING Deleted audit records cannot be restored. If you have a retention obligation, export them first and then pass that time as last_archive_time. With use_last_arch_timestamp => FALSE, all records are deleted. For regular cleanup, create a job with DBMS_AUDIT_MGMT.CREATE_PURGE_JOB.

PostgreSQL

Required privileges: changing log settings requires superuser (or a role granted the ALTER SYSTEM privilege, 15+). Reading server log files requires superuser or pg_read_server_files.

PostgreSQL has no dedicated audit store; all records go to the server log file. Decide together how logs are collected and retained (file retention, a log collector).

Connection and statement logging (built-in parameters)

ALTER SYSTEM SET log_connections = on;
ALTER SYSTEM SET log_disconnections = on;           -- also records session duration
ALTER SYSTEM SET log_statement = 'ddl';             -- none | ddl | mod | all
ALTER SYSTEM SET log_line_prefix = '%m [%p] %q%u@%d from %h app=%a ';
SELECT pg_reload_conf();
  • log_statement = 'mod' records DDL plus INSERT/UPDATE/DELETE/TRUNCATE and so on. Statements executed inside a function are not recorded.
  • log_connections applies from sessions that connect afterward.
  • For more detail on specific roles only: ALTER ROLE admin_user SET log_statement = 'all';
  • To make the log machine-readable, use log_destination = 'csvlog' or 'jsonlog' (15+).

WARNING log_statement = 'all' records every statement, so the log grows very quickly. It also records passwords in plain text for statements such as ALTER ROLE ... PASSWORD '...'. Have users change passwords with psql's \password.

Finding failed logins

Authentication failures are written to the server log as FATAL regardless of settings.

SELECT pg_current_logfile();   -- the log file currently in use (10+)
FATAL:  password authentication failed for user "app"
FATAL:  no pg_hba.conf entry for host "10.0.5.17", user "app", database "sales", no encryption
  • Search the log file for the phrases above. log_line_prefix must include %h for the connecting host to be known.
  • PostgreSQL does not store each user's last login time. If you need it, extract it from the log_connections log.

The pgaudit extension

log_statement filters only by statement. To filter by object or kind of operation and record in an audit format, use pgaudit (installed separately). Install the pgaudit version that matches your PostgreSQL major version.

-- postgresql.conf: shared_preload_libraries = 'pgaudit'  (restart required)
CREATE EXTENSION pgaudit;

ALTER SYSTEM SET pgaudit.log = 'ddl, role, write';   -- read, write, function, role, ddl, misc, misc_set, all
ALTER SYSTEM SET pgaudit.log_relation = on;           -- one line per table the statement touched
ALTER SYSTEM SET pgaudit.log_parameter = off;
SELECT pg_reload_conf();
  • Records go to the server log in the form AUDIT: SESSION,....
  • To audit only specific tables, use object auditing. Only operations that overlap with the privileges granted to the audit role are recorded.
CREATE ROLE auditor NOLOGIN;
ALTER SYSTEM SET pgaudit.role = 'auditor';
SELECT pg_reload_conf();
GRANT SELECT, UPDATE, DELETE ON sales.orders TO auditor;   -- only these operations are recorded as AUDIT: OBJECT

WARNING Enabling pgaudit.log = 'all' or 'read' globally greatly increases log volume and I/O. With log_parameter = on, bind values (including personal information) are written to the log.

SQL Server

Required privileges: server audits and server audit specifications require ALTER ANY SERVER AUDIT (or CONTROL SERVER); database audit specifications require ALTER ANY DATABASE AUDIT. Reading audit files requires CONTROL SERVER.

SQL Server Audit has three parts. The server audit (where to write: a file, the Windows Security/Application log), the server audit specification (server-level actions such as logins), and the database audit specification (actions such as table operations). Database audit specifications are available in all editions from 2016 SP1+.

Creating an audit

USE master;
CREATE SERVER AUDIT audit_main
  TO FILE (FILEPATH = N'D:\Audit\', MAXSIZE = 256 MB, MAX_ROLLOVER_FILES = 40)
  WITH (QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE);
ALTER SERVER AUDIT audit_main WITH (STATE = ON);

CREATE SERVER AUDIT SPECIFICATION audit_server_spec
  FOR SERVER AUDIT audit_main
  ADD (FAILED_LOGIN_GROUP),
  ADD (SERVER_ROLE_MEMBER_CHANGE_GROUP),
  ADD (SERVER_PRINCIPAL_CHANGE_GROUP),
  ADD (AUDIT_CHANGE_GROUP)
  WITH (STATE = ON);

USE sales;
CREATE DATABASE AUDIT SPECIFICATION audit_sales_spec
  FOR SERVER AUDIT audit_main
  ADD (INSERT, UPDATE, DELETE ON OBJECT::dbo.orders BY public),
  ADD (SCHEMA_OBJECT_CHANGE_GROUP),
  ADD (DATABASE_ROLE_MEMBER_CHANGE_GROUP)
  WITH (STATE = ON);
  • BY public means all users.
  • To record successful logins too, add SUCCESSFUL_LOGIN_GROUP. For applications without connection pooling, the volume is very large.
  • The audit file path must be writable by the SQL Server service account.

WARNING With ON_FAILURE = SHUTDOWN, the instance stops when it cannot write the audit file (disk full, etc.). FAIL_OPERATION makes the audited operation fail. Use these only when regulations require it, and in that case monitor the audit disk space.

Audit status

SELECT a.name, a.is_state_enabled, a.on_failure_desc, s.status_desc, s.audit_file_path
FROM sys.server_audits a
LEFT JOIN sys.dm_server_audit_status s ON s.audit_id = a.audit_id;

SELECT name, is_state_enabled FROM sys.server_audit_specifications;
SELECT name, is_state_enabled FROM sys.database_audit_specifications;   -- in each database

Reading audit records

SELECT event_time, action_id, succeeded, server_principal_name, database_name,
       schema_name, object_name, client_ip, application_name, LEFT(statement, 200) AS statement
FROM sys.fn_get_audit_file(N'D:\Audit\audit_main*.sqlaudit', DEFAULT, DEFAULT)
WHERE event_time > DATEADD(DAY, -1, SYSUTCDATETIME())
ORDER BY event_time DESC;
  • event_time is in UTC.
  • The client_ip and application_name columns exist in 2017+.
  • action_id is a short code (LGIF failed login, DL DELETE, etc.). Look up the names in sys.dm_audit_actions.

Viewing failed logins without Audit (error log)

If the server property "Login auditing" is at its default (failed logins only), failures are written to the SQL Server error log.

EXEC sys.sp_readerrorlog 0, 1, N'Login failed';   -- 0: current log file, 1: SQL Server error log
  • Use the State in the message's Error: 18456, State: N to tell the cause apart. 5 login does not exist, 8 wrong password, 38 the specified database cannot be opened, 58 SQL login attempted on a server that allows only Windows authentication.
  • Changing the "Login auditing" level takes effect only after a service restart.

WARNING To have the act of turning auditing off (STATE = OFF) or dropping an audit specification recorded too, include AUDIT_CHANGE_GROUP. Audit files are overwritten starting with the oldest once MAX_ROLLOVER_FILES is exceeded, so if the retention period is long, move files elsewhere periodically.