Skip to content

SQL Server query (mssql_query) ​

Connects to a Microsoft SQL Server instance, runs one read-only query of your own and reports how long it took, how many rows it returned and one value from the first row, as postgres_query does for PostgreSQL. The channels, the limits, expected, max_rows, the TLS parameters and the credential are the same, and that page describes them in full and says why there is one kind for each engine. This page covers what is different here: two kinds of login, and a query that nothing on the server keeps from writing.

What it looks like ​

The page of an mssql_query sensor in the light theme

The sensor's page after a few polls, counting the user sessions of a SQL Server 2022 instance. In the dark theme: the sensor's page. The form for adding it, with its parameters filled in: light, dark.

Who can attach it ​

Only administrators, as for postgres_query.

What keeps it read-only ​

SQL Server has no read-only transaction, so here the account and the check carry the whole weight.

  1. The account. The only protection that cannot be got around. Create a login that has db_datareader in the databases the query reads and, for the dynamic management views, VIEW SERVER STATE; see the setup. Never give the sensor a login that can write.
  2. The check. The query must be one SELECT or WITH statement. A T-SQL batch can run a second statement without any separator (SELECT 1 DELETE FROM t), so the sensor reads the query the way SQL Server does (strings, [bracketed] and "quoted" names, nested comments) and refuses every keyword that changes something or controls the batch, wherever it appears outside those: INSERT, UPDATE, DELETE, MERGE, DROP, ALTER, CREATE, TRUNCATE, GRANT, REVOKE, DENY, EXEC, EXECUTE, BEGIN, COMMIT, ROLLBACK, SET, DECLARE, IF, WHILE, USE, WAITFOR, OPENROWSET, OPENQUERY, OPENDATASOURCE, BULK and a few others, and INTO, which makes a SELECT create a table. A column called update has to be written [update]. This is a guard against mistakes, not against an attacker who is allowed to write queries: only an administrator can set it, and the account is the real limit.
  3. The batch. The query runs inside BEGIN TRANSACTION with SET XACT_ABORT ON and a LOCK_TIMEOUT of the poll's timeout, and the transaction is rolled back at the end whatever happened. When the sensor gives up, it closes the connection, and SQL Server cancels the query and rolls the transaction back.

Channels ​

As for postgres_query. The value is a number for integers, decimal, numeric, float, real, money and bit columns, and unknown for text and dates, which expected can still compare as text.

Parameters ​

As for postgres_query, with these differences:

ParameterDefaultMeaning
authsqlsql: a SQL Server login. windows: a Windows account over NTLM.
databasethe login's defaultThe database to open.
port1433TCP port. Named instances need their port set here; the SQL Server Browser service is not asked.

Credential: a secret whose value is user:password. For auth: sql the user is the login name. For auth: windows it is DOMAIN\user (the NetBIOS domain) or a plain user for a local account, so the secret reads GREEN\svc-monitor:the-password. A password may contain colons. The existing Windows credential kind is for the WinRM and WMI sensors and is not used here, so that SQL logins and Windows accounts take the same route through inheritance and the vault.

tls works the way the SQL Server client settings do: required is Encrypt=True, so the whole conversation is encrypted; optional encrypts when the server offers it; off asks for no encryption, and a server that insists on it (Force Encryption) is refused with a message that says so. With off a SQL login's password crosses the network only obfuscated, which anyone on the path can undo; use it on a network you trust, or not at all. A server that encrypts only the login packet is refused when tls is required. The TLS used is 1.2; a server that only speaks TLS 1.0 or 1.1 cannot be monitored encrypted.

Not supported: Kerberos (Windows authentication is NTLM only, so an environment that has switched NTLM off needs a SQL login), Microsoft Entra ID tokens, named instances through the Browser service, and the old text, ntext, image, sql_variant and CLR types in a result (the failure names the column; CAST it in the query).

Examples ​

User sessions, with a SQL login:

json
{
  "query": "SELECT COUNT(*) AS sessions FROM sys.dm_exec_sessions WHERE is_user_process = 1",
  "value_name": "User sessions",
  "tls": "required",
  "tls_fingerprint": "AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89"
}

The number of databases that are not online, with a Windows account, Down when it is not 0:

json
{
  "auth": "windows",
  "query": "SELECT COUNT(*) FROM sys.databases WHERE state <> 0",
  "expected": 0
}

On the server ​

For a SQL login (the server must allow mixed mode authentication, which needs a restart of the service after changing it):

sql
CREATE LOGIN pwmonitor WITH PASSWORD = '...', CHECK_POLICY = ON;
GRANT VIEW SERVER STATE TO pwmonitor;                       -- sys.dm_* views
USE app;
CREATE USER pwmonitor FOR LOGIN pwmonitor;
ALTER ROLE db_datareader ADD MEMBER pwmonitor;              -- only for queries on user tables

For a Windows account, create the login [GREEN\svc-monitor] the same way, with FROM WINDOWS. A domain account and an NTLM-capable path to the server are all it needs; no probe has to be joined to the domain.

Failures ​

The ones that are the same as for postgres_query (the timeout, max_rows, the refused query, the certificate rules, a refused connection), and:

MessageMeaning
the server refused the login (Login failed for user ...) (kind auth_failed)Wrong user or password, a disabled or locked login, or a Windows account the server does not know. SQL Server hides the reason from the client; it is in the server's error log.
the account cannot open the database (...) (kind config)database names none, or the login has no user in it.
the account may not read what the query reads (...) (kind config)Missing SELECT or VIEW SERVER STATE.
SQL Server said: ... (error 207), 208, 102 (kind config)An unknown column or table, a syntax error.
the query waited longer than N ms for a lock (kind timeout)Another session holds a lock the query needs.
the server requires encryption; set tls to optional or required for this sensor (kind config)Force Encryption is on and tls is off.
the server does not support encryption; ..., the server encrypts only the login, ... (kind config)tls is required and the server cannot do it.
NTLM: ... (kind protocol)The server did not offer NTLMv2 with session security, or the exchange broke.
column "x" is a text, ntext or image column, which the sensor cannot read; CAST it ... (kind config)See above.

Verification ​

Run against a real SQL Server 2022 Developer instance (16.0.1000) on Windows Server 2022, with a SQL login that has db_datareader and VIEW SERVER STATE only and with a domain administrator over NTLM: a value and its column names, a count of rows, no rows, NULL, the row limit, a wrong password (SQL login and Windows account), a database that does not exist, a syntax error, a query cut off by the timeout, a refused address, @@TRANCOUNT showing the transaction, a row of every common type (decimal, money, bit, float, bigint, tinyint, varchar(max), nvarchar with an accented letter, varbinary, uniqueidentifier, date, time(3), datetime, smalldatetime, datetime2 and datetimeoffset), a 20,000-character string, 500 rows across several packets, encryption without verification, refusal of an untrusted certificate with its fingerprint, a wrong pin and the right one, and a poll with encryption off. The value decoding is also tested against byte sequences written from the protocol specification.

Not seen: SQL Server 2016 to 2019, Azure SQL, an instance that has Force Encryption on, Extended Protection for Authentication, a login that must change its password, sql_variant and CLR types, availability group listeners.

Testing it yourself ​

PROBEWARD_TEST_MSSQL_ADDR (host:port), PROBEWARD_TEST_MSSQL_USER and PROBEWARD_TEST_MSSQL_PASSWORD for a SQL login, PROBEWARD_TEST_MSSQL_WINDOWS_USER (DOMAIN\user) and PROBEWARD_TEST_MSSQL_WINDOWS_PASSWORD for a Windows account, and PROBEWARD_TEST_MSSQL_TLS=1 for a server whose certificate is not trusted. Each part runs when its variables are set and says so when it does not. The tests only run SELECTs of constants and of system views, with the account the variables name, so a login that may only read is enough.

AGPL-3.0-only