DBA Scripts: Get Login Security Audit

🔧Part of the DBA-Tools Project, copy/paste SQL Server scripts and health checks.In: Security

An audit is coming, or someone has just asked which SQL logins are unsafe, and you need the answer before the meeting. These read-only scripts give it back in the order I would check it myself: which logins have a guessable password or no policy behind them, who has been failing to log in and from where, and who holds sysadmin and is connected right now. Each grid comes with what the columns mean and the ALTER LOGIN that fixes the finding.


Which Logins Have a Weak Password or Policy

Run this one first. It is the only script here that can prove a password is guessable, and it sorts the worst finding to the top.

TipRun it as sysadmin or with CONTROL SERVER. PWDCOMPARE reads sys.sql_logins.password_hash, which any other login sees as NULL, so without that permission both password tests return 0 and nothing raises an error. A clean grid is not a clean instance until you know who you ran it as.
✓ Verified
  • Tested on: SQL Server 2025 (RTM CU8) 17.0.4075.5
  • Last verified: 2026-10-28, every script run on the lab
  • Permissions: VIEW SERVER STATE, VIEW ANY DEFINITION, EXECUTE on xp_readerrorlog, and CONTROL SERVER for the password tests
  • Safety: read-only, impact low
/*
Script Name : Get-WeakLoginSettings
Category    : security-and-permissions
Purpose     : Identify SQL logins with weak security settings: a blank password, a password equal
              to the login name, sa enabled, password policy off, or expiration off.
              risk_flag is the highest-severity finding for the login; all_risks lists every
              finding it has, because a login is usually weak in more than one way at once.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-login-security-audit/)
Requires    : VIEW ANY DEFINITION; CONTROL SERVER or sysadmin (password_hash and LOGINPROPERTY)
HealthCheck : Yes
Notes       : PWDCOMPARE reads sys.sql_logins.password_hash, which is visible only to a login
              with CONTROL SERVER. Without it the blank/equals-name tests silently return 0.
*/
-- SAFE:ReadOnly
-- IMPACT:Low
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;

WITH flags AS (
    SELECT
        sl.name,
        sl.is_disabled,
        sl.is_policy_checked,
        sl.is_expiration_checked,
        sl.default_database_name,
        sl.create_date,
        sl.modify_date,
        CAST(LOGINPROPERTY(sl.name, 'PasswordLastSetTime') AS DATETIME) AS password_last_set,
        CAST(LOGINPROPERTY(sl.name, 'IsLocked') AS BIT)                 AS is_locked,
        CAST(LOGINPROPERTY(sl.name, 'IsMustChange') AS BIT)             AS must_change_password,
        /* No password literal appears in this script: PWDCOMPARE hashes the candidate itself. */
        CASE WHEN sl.password_hash IS NOT NULL AND PWDCOMPARE(N'', sl.password_hash) = 1
             THEN 1 ELSE 0 END AS pw_blank,
        CASE WHEN sl.password_hash IS NOT NULL AND PWDCOMPARE(sl.name, sl.password_hash) = 1
             THEN 1 ELSE 0 END AS pw_equals_name,
        CASE WHEN sl.name = 'sa' AND sl.is_disabled = 0 THEN 1 ELSE 0 END AS sa_enabled
    FROM sys.sql_logins AS sl
    WHERE sl.name NOT LIKE '##%'
)
SELECT
    f.name AS login_name,
    f.is_disabled,
    f.is_policy_checked,
    f.is_expiration_checked,
    f.password_last_set,
    f.is_locked,
    f.must_change_password,
    f.default_database_name,
    f.create_date,
    f.modify_date,
    CASE
        WHEN f.pw_blank = 1                 THEN 'BLANK_PASSWORD'
        WHEN f.pw_equals_name = 1           THEN 'PASSWORD_EQUALS_NAME'
        WHEN f.sa_enabled = 1               THEN 'SA_ENABLED'
        WHEN f.is_policy_checked = 0        THEN 'PASSWORD_POLICY_OFF'
        WHEN f.is_expiration_checked = 0    THEN 'EXPIRATION_OFF'
        ELSE 'OK'
    END AS risk_flag,
    STUFF(
          CASE WHEN f.pw_blank = 1              THEN ',BLANK_PASSWORD'       ELSE '' END
        + CASE WHEN f.pw_equals_name = 1        THEN ',PASSWORD_EQUALS_NAME' ELSE '' END
        + CASE WHEN f.sa_enabled = 1            THEN ',SA_ENABLED'           ELSE '' END
        + CASE WHEN f.is_policy_checked = 0     THEN ',PASSWORD_POLICY_OFF'  ELSE '' END
        + CASE WHEN f.is_expiration_checked = 0 THEN ',EXPIRATION_OFF'       ELSE '' END
        , 1, 1, '') AS all_risks
FROM flags AS f
ORDER BY
    CASE
        WHEN f.pw_blank = 1              THEN 0
        WHEN f.pw_equals_name = 1        THEN 1
        WHEN f.sa_enabled = 1            THEN 2
        WHEN f.is_policy_checked = 0     THEN 3
        WHEN f.is_expiration_checked = 0 THEN 4
        ELSE 5
    END,
    f.name;
Get-WeakLoginSettings: logins ranked worst first, BLANK_PASSWORD then PASSWORD_EQUALS_NAME then SA_ENABLED then PASSWORD_POLICY_OFF, with all_risks listing every finding per login

What the Columns Decide

risk_flag
all_risks
The worst finding for the login, then every finding it has. Read all_risks: a login is usually weak in more than one way at once.Act when BLANK_PASSWORD or PASSWORD_EQUALS_NAME appears. Both are guessable on the first attempt.
is_policy_checked
is_expiration_checked
0 means the Windows password policy, or password expiry, is not enforced on this login. Policy off is rarely deliberate; expiry off on an application login often is, because an expired password takes the application down with it.Act when policy is 0 on a login a person uses. Nothing stops them choosing a password the policy would have rejected.
password_last_set
must_change_password
is_locked
When the password was last changed, whether the login has to change it at the next connect, and whether lockout is in force right now.Act when password_last_set is years old and policy is off. Nothing has ever forced that password to change.
is_disabled
default_database_name
A disabled login still appears, so you can see what it would be if someone re-enabled it. A default database that has since been dropped turns every connection for that login into error 4064.

What To Fix First

BLANK_PASSWORD
ALTER LOGIN [name] WITH PASSWORD = N'<new>' MUST_CHANGE, CHECK_POLICY = ON, CHECK_EXPIRATION = ON;Act when an application owns the login. The connection string breaks the second you run this, so warn the owner first, and drop MUST_CHANGE.
PASSWORD_EQUALS_NAME
The same statement, then check your other instances for the same login, because the pair was almost certainly scripted onto more than one.
SA_ENABLED
Confirm a named sysadmin login works, then ALTER LOGIN [sa] DISABLE;.Act when no other sysadmin works. Read Locked Out of SQL Server before you disable anything.
PASSWORD_POLICY_OFF
ALTER LOGIN [name] WITH CHECK_POLICY = ON;. The current password is not revalidated, so nothing breaks now.
EXPIRATION_OFF
ALTER LOGIN [name] WITH CHECK_POLICY = ON, CHECK_EXPIRATION = ON; in one statement. Expiration on its own fails with Msg 15122, below.
Two of these statements will not run on their ownMessages pane, SQL Server 2025 CU8
Msg 15122, Level 16, State 1, Server HPAI01, Line 1 The CHECK_EXPIRATION option cannot be used when CHECK_POLICY is OFF. Msg 15099, Level 16, State 1, Server HPAI01, Line 1 The MUST_CHANGE option cannot be used when CHECK_EXPIRATION is OFF.

Who Has Been Failing to Log In

A bad password and a database the login cannot open both land in the error log as error 18456, so the count alone proves nothing. The reason column is the error log’s own words, and it is the only thing separating a bad password from a database the login cannot open, which the client sees as 4060 or 4064.

/*
Script Name : Get-FailedLoginSummary
Category    : security
Purpose     : Aggregated failed login analysis from the SQL Server error log and current
              lockout state per SQL login. Surfaces brute-force patterns and locked accounts.
              Complements Get-WeakLoginSettings (which checks policy configuration), this
              checks what is actually happening.
              Note: SQL Server 2025 does not write 18456 events to RING_BUFFER_SECURITY_ERROR;
              xp_readerrorlog is the reliable cross-version source for login failures.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-login-security-audit/)
Requires    : VIEW SERVER STATE, sysadmin (for LOGINPROPERTY on other logins), EXECUTE on xp_readerrorlog
HealthCheck : Yes
Notes       : The reason column is the literal text after "Reason: " in the error log entry.
              Read it before the mapped error_description: every one of these entries is logged
              as 18456 and only the reason separates a bad password from a missing default
              database, which the client sees as 4064.
*/
-- SAFE:ReadOnly
-- IMPACT:Low
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;

-- INSERT...EXEC cannot be used inside a CTE so materialise to a temp table first
DROP TABLE IF EXISTS #failed_logins;
CREATE TABLE #failed_logins (
    log_date DATETIME,
    process_info NVARCHAR(100),
    log_text NVARCHAR(MAX)
);

-- Filter to current error log (log# 0), type 1 (SQL Server log), login failure messages only
INSERT INTO #failed_logins
EXEC xp_readerrorlog 0, 1, N'Login failed';

WITH parsed AS (
    SELECT
        -- Login name sits between the first pair of single quotes. Some entries carry no
        -- name at all (18452 "untrusted domain" is logged as "Login failed. The login is
        -- from..."), so guard the SUBSTRING or one such line fails the whole run (Msg 537).
        CASE
            WHEN CHARINDEX('''', log_text) > 0
             AND CHARINDEX('''', log_text, CHARINDEX('''', log_text) + 1) > 0
            THEN SUBSTRING(
                log_text,
                CHARINDEX('''', log_text) + 1,
                CHARINDEX('''', log_text, CHARINDEX('''', log_text) + 1) - CHARINDEX('''', log_text) - 1
            )
            ELSE NULL
        END AS login_name,
        -- Client IP/host is in the trailing [CLIENT: ...] tag
        CASE
            WHEN CHARINDEX('[CLIENT: ', log_text) > 0
             AND CHARINDEX(']', log_text, CHARINDEX('[CLIENT: ', log_text)) > 0
            THEN SUBSTRING(
                log_text,
                CHARINDEX('[CLIENT: ', log_text) + 9,
                CHARINDEX(']', log_text, CHARINDEX('[CLIENT: ', log_text))
                    - CHARINDEX('[CLIENT: ', log_text) - 9
            )
            ELSE NULL
        END AS client_host,
        -- The log's own words: everything after "Reason: " up to the [CLIENT: tag
        CASE
            WHEN CHARINDEX('Reason: ', log_text) > 0
            THEN RTRIM(SUBSTRING(
                log_text,
                CHARINDEX('Reason: ', log_text) + 8,
                CASE
                    WHEN CHARINDEX('[CLIENT: ', log_text) > CHARINDEX('Reason: ', log_text)
                    THEN CHARINDEX('[CLIENT: ', log_text) - CHARINDEX('Reason: ', log_text) - 8
                    ELSE 4000
                END
            ))
            ELSE NULL
        END AS reason,
        -- Map reason text to the canonical error code
        CASE
            WHEN log_text LIKE '%untrusted domain%' THEN 18452
            WHEN log_text LIKE '%only administrators%' THEN 18451
            WHEN log_text LIKE '%account is disabled%' THEN 18470
            WHEN log_text LIKE '%password of the account has expired%' THEN 18487
            WHEN log_text LIKE '%password of the account must be changed%' THEN 18488
            WHEN log_text LIKE '%explicitly specified database%' THEN 4060
            WHEN log_text LIKE '%default database%' THEN 4064
            WHEN log_text LIKE '%specified in the login properties%' THEN 4064
            WHEN log_text LIKE '%password did not match%' THEN 18456
            WHEN log_text LIKE '%error occurred while evaluating the password%' THEN 18456
            WHEN log_text LIKE '%could not find a login%' THEN 18456
            ELSE 18456
        END AS error_code,
        log_date
    FROM #failed_logins
),
aggregated AS (
    SELECT
        login_name,
        client_host,
        error_code,
        reason,
        COUNT(*) AS failure_count,
        MIN(log_date) AS first_failure,
        MAX(log_date) AS last_failure
    FROM parsed
    GROUP BY login_name, client_host, error_code, reason
)
SELECT
    agg.login_name,
    agg.client_host,
    agg.error_code,
    CASE agg.error_code
        WHEN 18456 THEN 'Login failed (bad password or login does not exist)'
        WHEN 18452 THEN 'Login from untrusted domain or cannot use Windows auth'
        WHEN 18451 THEN 'Login failed, only admin connections are allowed'
        WHEN 18470 THEN 'Account is disabled'
        WHEN 18487 THEN 'Password has expired'
        WHEN 18488 THEN 'Password must be changed'
        WHEN 4060 THEN 'Credentials are valid, the requested database could not be opened'
        WHEN 4064 THEN 'Credentials are valid, the default database is not usable'
        ELSE 'Error ' + CAST(agg.error_code AS VARCHAR(10))
    END AS error_description,
    agg.reason,
    agg.failure_count,
    agg.first_failure AS first_failure_approx,
    agg.last_failure AS last_failure_approx,
    CASE
        WHEN sl.name IS NOT NULL
        THEN CAST(LOGINPROPERTY(sl.name, 'IsLocked') AS BIT)
        ELSE NULL
    END AS is_currently_locked,
    CASE
        WHEN sl.name IS NOT NULL
        THEN CAST(LOGINPROPERTY(sl.name, 'BadPasswordCount') AS INT)
        ELSE NULL
    END AS bad_password_count,
    CASE
        WHEN agg.error_code IN (4060, 4064)
        THEN 'CONFIG - valid credentials, database not usable (' + CAST(agg.failure_count AS VARCHAR) +
             ' in log); fix the database or the default database, not the password'
        WHEN agg.failure_count >= 10
        THEN 'WARN - ' + CAST(agg.failure_count AS VARCHAR) + ' failures for login [' +
             ISNULL(agg.login_name, '(unknown)') + '] in the current error log; baseline is under 10' +
             ', check client_host for a stale application password or brute force'
        ELSE 'INFO'
    END AS status
FROM aggregated AS agg
LEFT JOIN sys.sql_logins AS sl ON sl.name = agg.login_name
ORDER BY agg.failure_count DESC;

DROP TABLE #failed_logins;
Get-FailedLoginSummary: the Agent service account failing with 4060 on a missing database, Lab1028_ls_failed with 12 bad-password failures, and a 4064 for a login whose default database is gone

On the lab the biggest group is not an attack: a service account that cannot open a database, which the script grades CONFIG. Fix that database or the login’s default database, not the password.

Reading the Failed Login Grid

reason
error_code
error_description
The text after Reason: in the log entry, mapped to the error number the client would have seen. Read reason before the mapping.Act when a high count carries a database reason. That is a broken connection string or a dropped default database, not an attack.
failure_count
status
Failures grouped by login, client host and reason, worst count first. status is CONFIG for a database reason, WARN at 10 or more failures in the current error log, INFO below that. The grades are operational heuristics, not Microsoft levels.Act when WARN sits on a login that exists. Brute force, or an application with a stale password retrying forever, and client_host tells you which.
client_host
The address from the [CLIENT: ...] tag. One host, one login and hundreds of failures is a misconfigured application. Many hosts for one login is the pattern worth looking harder at.
is_currently_locked
bad_password_count
Live lockout state from LOGINPROPERTY, NULL for Windows logins because they are not in sys.sql_logins.Act when a login a person uses is locked. The owner is locked out and probably does not know it yet.

Who Holds sysadmin and Who Is Connected Now

SQL Server records no last login time without a Server Audit, or a capture like the Login Activity Session. This script reads the sessions connected right now, so active_sessions of 0 means nothing is connected at this moment, not that the login is unused.

/*
Script Name : Get-LoginLastActivity
Category    : monitoring
Purpose     : All SQL and Windows logins with current session status, connection details, and
              disabled state, plus sysadmin and securityadmin membership.
              Note: SQL Server does not record "last login time" natively without a SQL Server
              Audit configured. This script shows what is available: current active sessions
              and login metadata.
              For historical last-login tracking, enable a Server Audit with LOGIN action group.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-login-security-audit/)
Requires    : VIEW SERVER STATE, VIEW ANY DEFINITION
Notes       : Role membership is read from sys.server_role_members AND IS_SRVROLEMEMBER, not
              from IS_SRVROLEMEMBER alone. IS_SRVROLEMEMBER returned 0 for a virtual service
              account that sys.server_role_members shows as a direct sysadmin (SQL Server 2025
              CU8), so the catalog is the primary source and the function adds Windows group
              membership the catalog cannot see.
              is_securityadmin additionally excludes sysadmins: IS_SRVROLEMEMBER returns 1 for
              every role when the principal is a sysadmin, which reported 14 logins as
              securityadmin on a lab instance whose catalog holds only 4. Without that
              exclusion the column means "sysadmin or securityadmin", not securityadmin.
*/
-- SAFE:ReadOnly
-- IMPACT:Low
SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;

WITH role_direct AS (
    SELECT
        rm.member_principal_id,
        MAX(CASE WHEN r.name = 'sysadmin'      THEN 1 ELSE 0 END) AS in_sysadmin,
        MAX(CASE WHEN r.name = 'securityadmin' THEN 1 ELSE 0 END) AS in_securityadmin
    FROM sys.server_role_members AS rm
    JOIN sys.server_principals  AS r ON r.principal_id = rm.role_principal_id
    WHERE r.name IN ('sysadmin', 'securityadmin')
    GROUP BY rm.member_principal_id
)
SELECT
    sp.name AS login_name,
    sp.type_desc AS login_type,
    sp.is_disabled,
    sp.create_date,
    sp.modify_date,
    /* Current session info, 0 and NULL when not connected right now */
    COUNT(s.session_id) AS active_sessions,
    MIN(s.login_time) AS earliest_current_session,
    MAX(s.login_time) AS latest_current_session,
    /* Connection detail across the login's current sessions */
    MAX(c.client_net_address) AS last_client_ip,
    MAX(s.host_name) AS last_host_name,
    MAX(s.program_name) AS last_program_name,
    MAX(c.auth_scheme) AS auth_scheme,
    /* Permission summary: catalog membership first, function second */
    CAST(CASE WHEN ISNULL(rd.in_sysadmin, 0) = 1
                OR ISNULL(IS_SRVROLEMEMBER('sysadmin', sp.name), 0) = 1
              THEN 1 ELSE 0 END AS BIT) AS is_sysadmin,
    CAST(CASE WHEN ISNULL(rd.in_securityadmin, 0) = 1
                OR (ISNULL(IS_SRVROLEMEMBER('securityadmin', sp.name), 0) = 1
                    AND ISNULL(IS_SRVROLEMEMBER('sysadmin', sp.name), 0) = 0)
              THEN 1 ELSE 0 END AS BIT) AS is_securityadmin
FROM sys.server_principals AS sp
LEFT JOIN role_direct AS rd ON rd.member_principal_id = sp.principal_id
LEFT JOIN sys.dm_exec_sessions AS s
       ON s.login_name = sp.name AND s.is_user_process = 1
LEFT JOIN sys.dm_exec_connections AS c
       ON c.session_id = s.session_id
WHERE sp.type IN ('S', 'U', 'G') /* SQL login, Windows user, Windows group */
  AND sp.name NOT LIKE '##%'     /* exclude internal system logins */
GROUP BY sp.name, sp.type_desc, sp.is_disabled, sp.create_date, sp.modify_date,
         sp.principal_id, rd.in_sysadmin, rd.in_securityadmin
ORDER BY active_sessions DESC, sp.is_disabled, sp.name;
Get-LoginLastActivity results in SSMS: one row per login with type, disabled flag, active sessions and the earliest and latest current session

Reading the Activity Grid

active_sessions
earliest_current_session
latest_current_session
Sessions connected at this instant, per login, and when the oldest and newest of them logged in.Act when you are about to disable a login. 0 here is not proof. Prove it is unused from an audit or its owner.
last_client_ip
last_host_name
last_program_name
auth_scheme
Where the current sessions come from, what program opened them, and whether Windows logins arrived over Kerberos or NTLM.
is_sysadmin
is_securityadmin
Catalog membership first, IS_SRVROLEMEMBER second, because neither is complete alone. is_securityadmin excludes sysadmins: on the lab the function alone reported 14 securityadmin logins where the catalog holds 4. Remove a member nobody owns with ALTER SERVER ROLE sysadmin DROP MEMBER [name];.Act when a name nobody owns appears. Service accounts there are expected, and still a route in.

How To Run From The Repo

# Clone dba-tools repo:
git clone https://github.com/peterwhyte-lgtm/dba-tools

# Initialize environment:
cd dba-tools
.\Initialize-Environment.ps1

# Failed login patterns and lockout state:
.\run.ps1 Get-FailedLoginSummary

# Current session status and connection details per login:
.\run.ps1 Get-LoginLastActivity

# Weak password policy, expiration, and sa status:
.\run.ps1 Get-WeakLoginSettings

# Any of these against a remote sql server:
.\run.ps1 Get-WeakLoginSettings -ServerInstance SQLSERVER01

MS Docs: sys.sql_logins · ALTER LOGIN · sys.dm_exec_sessions · sys.dm_exec_connections · sys.server_role_members


Frequently Asked Questions

Get-WeakLoginSettings found no blank passwords. Can I trust that?

Only if you ran it with CONTROL SERVER or as a sysadmin. PWDCOMPARE reads sys.sql_logins.password_hash, which only CONTROL SERVER can see; without it the hash reads NULL, both password tests return 0, and nothing raises an error. On the lab instance as sysadmin: 41 hashes, 1 blank password. As an ordinary SQL login: 0 hashes, no password finding even for a login whose password is its own name, and no error.

Why read the error log instead of RING_BUFFER_SECURITY_ERROR?

The ring buffer does not hold login failures. On the lab instance it held 85 records and not one mentioned 18456; it carries Windows security API failures, with an APIName and a Windows error code instead of a login name.

Why does is_sysadmin disagree with IS_SRVROLEMEMBER?

Neither source is complete. IS_SRVROLEMEMBER returned 0 for a virtual service account that sys.server_role_members lists as a direct sysadmin, and it returns 1 for every role when the principal is a sysadmin, which inflated a naive securityadmin check to 14 logins where the catalog holds 4.


Related Scripts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *