DBAtlas · Database operations atlas

Set up SQL Server Audit: logins, permission changes and table access

SQL ServerSecurity

Command

USE master;
CREATE SERVER AUDIT [Audit_DBA]
TO FILE (FILEPATH = N'D:\Audit\', MAXSIZE = 256 MB, MAX_ROLLOVER_FILES = 20, RESERVE_DISK_SPACE = OFF)
WITH (QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE);
ALTER SERVER AUDIT [Audit_DBA] WITH (STATE = ON);

-- Server-wide (covers all databases):
CREATE SERVER AUDIT SPECIFICATION [AuditSpec_Server]
FOR SERVER AUDIT [Audit_DBA]
    ADD (FAILED_LOGIN_GROUP),
    ADD (SERVER_ROLE_MEMBER_CHANGE_GROUP),
    ADD (DATABASE_ROLE_MEMBER_CHANGE_GROUP),
    ADD (SERVER_PRINCIPAL_CHANGE_GROUP),
    ADD (DATABASE_PRINCIPAL_CHANGE_GROUP),
    ADD (SERVER_PERMISSION_CHANGE_GROUP),
    ADD (DATABASE_PERMISSION_CHANGE_GROUP),
    ADD (AUDIT_CHANGE_GROUP)
WITH (STATE = ON);

-- Database: access to a sensitive table:
USE [Musteri];
CREATE DATABASE AUDIT SPECIFICATION [AuditSpec_Musteri]
FOR SERVER AUDIT [Audit_DBA]
    ADD (SELECT, INSERT, UPDATE, DELETE ON OBJECT::[dbo].[Siparis] BY [public])
WITH (STATE = ON);

-- Read:
SELECT event_time, action_id, succeeded, server_principal_name, database_name,
       schema_name, object_name, LEFT(statement, 200) AS stmt, client_ip, application_name
FROM   sys.fn_get_audit_file(N'D:\Audit\Audit_DBA_*.sqlaudit', DEFAULT, DEFAULT)
WHERE  event_time >= DATEADD(HOUR, -24, SYSUTCDATETIME())
ORDER BY event_time DESC;

What it does

Creates a server audit that writes to file; records failed logins, role membership, principal and permission changes server-wide and SELECT/DML access to a chosen table at database level, and reads the records with T-SQL.

When to use it

For audit/compliance requirements (GDPR, PCI, SOX), for "who read/changed this table" questions, or when privilege escalation is suspected.

Caution

SELECT auditing on a busy table generates records very fast and costs performance; narrow it by object and principal. ON_FAILURE = SHUTDOWN stops the server when the audit cannot be written; use it only when mandated. The audit folder must be writable by the SQL Server service account and not deletable by non-DBAs. event_time is UTC. A database audit specification is restored with the database but stays orphaned if the server audit GUID does not match.

Open in DBAtlas →

Related