Security, Auditing and Operations

Article · 7:00

Logins, users and roles, row-level security, TDE and Always Encrypted, auditing, Agent, the DMVs worth watching, tempdb, and what Azure SQL changes.

Logins are server-level; users are database-level. A login authenticates to the instance; a user is a login's identity inside one database, and permissions are granted to users. The two are linked by a SID, which is why restoring a database to a different server produces orphaned users - the user exists, the login does not, and the mapping is broken.

Grant to roles, never to users. Create a database role per application function, grant object permissions to the role, and add users to it. Staff and services change; roles do not. A schema is also a permission boundary - GRANT SELECT ON SCHEMA::reporting covers every object in it, including ones added later, which is SQL Server's answer to PostgreSQL's default privileges problem.

Prefer granting EXECUTE on procedures over granting table access. Ownership chaining means a procedure can read a table the caller cannot, which gives you a genuinely narrow interface.

Row-level security applies a predicate function to every query on a table, so a tenant sees only their rows regardless of what the application's WHERE clause says. A FILTER predicate controls reads; a BLOCK predicate controls writes - and without the block predicate a tenant can insert rows belonging to another tenant.

Encryption comes in three kinds and they defend against different things. TDE encrypts the data and log files at rest, protecting against someone taking the files or the backup media; it does nothing against a user with a valid login. Always Encrypted encrypts specific columns in the client driver, so the engine never sees the plaintext - it protects against the DBA, at the cost of limited querying on those columns. TLS protects the connection. Most deployments want TDE plus TLS; Always Encrypted is for data the database operator genuinely should not see.

Auditing writes to a file or the security log. Audit what you will actually review - an audit specification that captures everything produces volume nobody reads.

tempdb deserves its own line in any production checklist: one data file per core up to eight, equally sized, with equal autogrowth, on the fastest storage available.

Azure SQL differs in ways that invalidate parts of an on-premises runbook: no Agent (use Elastic Jobs), no cross-database queries without external tables, backups managed by the platform, and sp_configure largely unavailable. Know which of your scripts will not run there.

Laboratory exercise 6 - make it defensible.

Implement least privilege for the capstone: an owner, an application role with the minimum DML, a read-only reporting role, and a procedure-only role that has EXECUTE and no table permissions. Test every denial - connect as each and prove the forbidden operations fail.

Enable row-level security on a tenant table with both a filter and a block predicate, and demonstrate a tenant failing to read and failing to insert across the boundary. Enable TDE and show the backup is unreadable without the certificate. Configure TLS and prove an unencrypted connection is refused.

Create an audit capturing failed logins and schema changes, trigger both, and read the audit back.

Deliverable: the role and policy DDL, a test script attempting every forbidden operation with its output, the TDE and TLS evidence, the audit extract, a monitoring configuration naming the metrics and thresholds you would alert on, and a deployment and cost checklist including tempdb, Agent jobs, the upgrade path, and which parts would need rewriting for Azure SQL.

-- ================= Logins, users and roles =================
CREATE LOGIN app_login WITH PASSWORD = 'Str0ng!Passw0rd',
    CHECK_POLICY = ON;                     -- server level
GO
USE SalesWorkshop;
CREATE USER app_user FOR LOGIN app_login;  -- database level
GO

-- Grant to ROLES. People and services change; roles do not.
CREATE ROLE app_write;
CREATE ROLE app_read;
CREATE ROLE app_execute_only;

GRANT SELECT, INSERT, UPDATE ON SCHEMA::sales TO app_write;
GRANT SELECT                  ON SCHEMA::sales TO app_read;
-- SCHEMA:: covers objects added LATER, which is SQL Server's answer
-- to the "new table is invisible to the role" problem.

-- The narrowest interface available: EXECUTE and nothing else.
-- Ownership chaining lets the procedure read tables the caller cannot.
GRANT EXECUTE ON SCHEMA::sales TO app_execute_only;

ALTER ROLE app_write ADD MEMBER app_user;

-- DENY beats GRANT, always, whatever the role membership:
DENY DELETE ON SCHEMA::sales TO app_write;

-- Orphaned users after restoring to another server - the login's SID
-- does not match:
SELECT dp.name, dp.type_desc
FROM sys.database_principals AS dp
LEFT JOIN sys.server_principals AS sp ON sp.sid = dp.sid
WHERE sp.sid IS NULL AND dp.type IN ('S','U','G')
  AND dp.name NOT IN ('guest','INFORMATION_SCHEMA','sys');
ALTER USER app_user WITH LOGIN = app_login;     -- the fix

-- ================= Row-level security =================
CREATE SCHEMA security_fn;
GO
CREATE OR ALTER FUNCTION security_fn.tenant_predicate(@tenant_id int)
RETURNS TABLE WITH SCHEMABINDING
AS RETURN
    SELECT 1 AS allowed
    WHERE @tenant_id = CAST(SESSION_CONTEXT(N'tenant_id') AS int)
       OR IS_MEMBER('db_owner') = 1;
GO

CREATE SECURITY POLICY security_fn.tenant_filter
    ADD FILTER PREDICATE security_fn.tenant_predicate(tenant_id)
        ON sales.customer,
    ADD BLOCK  PREDICATE security_fn.tenant_predicate(tenant_id)
        ON sales.customer AFTER INSERT
WITH (STATE = ON);
-- FILTER controls READS. BLOCK controls WRITES. Without the block
-- predicate a tenant can insert rows belonging to someone else -
-- which is the half people leave out.

EXEC sp_set_session_context @key = N'tenant_id', @value = 42;
SELECT * FROM sales.customer;     -- only tenant 42's rows

-- ================= Encryption: three kinds, three threats ==========
-- TDE - files and backups at rest. Does NOT stop a valid login.
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Str0ng!MasterKey';
CREATE CERTIFICATE TDECert WITH SUBJECT = 'TDE Certificate';
-- BACK UP THIS CERTIFICATE. Without it the backups are unreadable
-- for ever, and this has ended companies:
BACKUP CERTIFICATE TDECert TO FILE = '/backup/TDECert.cer'
  WITH PRIVATE KEY (FILE = '/backup/TDECert.key',
                    ENCRYPTION BY PASSWORD = 'Str0ng!CertKey');
GO
USE SalesWorkshop;
CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_256
    ENCRYPTION BY SERVER CERTIFICATE TDECert;
ALTER DATABASE SalesWorkshop SET ENCRYPTION ON;

SELECT DB_NAME(database_id), encryption_state_desc, percent_complete
FROM sys.dm_database_encryption_keys;

-- Always Encrypted - the client driver encrypts; the engine never
-- sees plaintext. Protects against the DBA. Costs you equality-only
-- querying on those columns, and only with deterministic encryption.

-- ================= Auditing =================
CREATE SERVER AUDIT SalesAudit TO FILE (FILEPATH = '/var/opt/mssql/audit/')
    WITH (ON_FAILURE = CONTINUE);
ALTER SERVER AUDIT SalesAudit WITH (STATE = ON);
GO
CREATE SERVER AUDIT SPECIFICATION SalesAuditSpec
FOR SERVER AUDIT SalesAudit
    ADD (FAILED_LOGIN_GROUP),
    ADD (SCHEMA_OBJECT_CHANGE_GROUP),
    ADD (DATABASE_ROLE_MEMBER_CHANGE_GROUP)
WITH (STATE = ON);
-- Audit what will actually be REVIEWED. Capturing everything produces
-- volume nobody reads, which is indistinguishable from no audit.

SELECT event_time, action_id, succeeded, server_principal_name, statement
FROM sys.fn_get_audit_file('/var/opt/mssql/audit/*.sqlaudit', NULL, NULL)
ORDER BY event_time DESC;

-- ================= What to watch =================
SELECT TOP 10 wait_type, wait_time_ms, waiting_tasks_count
FROM sys.dm_os_wait_stats
WHERE wait_type NOT IN ('CLR_SEMAPHORE','SLEEP_TASK','BROKER_TASK_STOP',
                        'XE_TIMER_EVENT','WAITFOR','CHECKPOINT_QUEUE')
ORDER BY wait_time_ms DESC;
-- PAGEIOLATCH_*  reading from disk - memory or index problem
-- LCK_M_*        blocking - consider READ_COMMITTED_SNAPSHOT
-- CXPACKET       parallelism; check cost threshold and MAXDOP
-- WRITELOG       log write latency; check the storage
-- PAGELATCH_UP on 2:x:x  tempdb allocation contention - add files

SELECT COUNT(*) AS tempdb_files FROM tempdb.sys.database_files
WHERE type_desc = 'ROWS';   -- want: one per core up to 8, equally sized

-- ================= Azure SQL differs =================
--   no SQL Agent            -> Elastic Jobs
--   no cross-database query -> external tables
--   backups are managed     -> your runbook changes entirely
--   sp_configure mostly gone, USE is not supported between databases
-- Know which of your scripts will not run there BEFORE the migration.

Discussion

No questions on this topic yet. Sign in to ask the first one.