-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_logon_trigger.sql
More file actions
97 lines (77 loc) · 2.65 KB
/
Copy pathcreate_logon_trigger.sql
File metadata and controls
97 lines (77 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
SA-Block — Step 2 of 2
*/
USE [master];
GO
CREATE OR ALTER TRIGGER [TR_SA_Block_RestrictedLogins]
ON ALL SERVER
WITH EXECUTE AS N'sa' -- lets the trigger write the audit row
-- even when the connecting login (Administrator)
-- has no rights on the audit table
FOR LOGON
AS
BEGIN
SET NOCOUNT ON;
DECLARE @LoginName sysname = ORIGINAL_LOGIN();
IF @LoginName NOT IN (N'sa', N'Administrator')
RETURN;
DECLARE @ClientHost nvarchar(128) =
EVENTDATA().value('(/EVENT_INSTANCE/ClientHost)[1]', 'nvarchar(128)');
DECLARE @WorkstationName nvarchar(128) = HOST_NAME();
DECLARE @IsAllowed bit = 0;
/* ----------------------------------------------------------
ALLOWLIST — edit this section.
Local connections + your trusted static IPs.
---------------------------------------------------------- */
IF @ClientHost IS NULL
OR @ClientHost IN
(
N'<local machine>', -- shared memory / local named pipes
N'127.0.0.1', -- local TCP (IPv4)
N'::1', -- local TCP (IPv6)
/* ==== YOUR TRUSTED IPs — EDIT BELOW ==== */
N'192.168.1.50', -- example: app server
N'192.168.1.51' -- example: admin workstation
/* ======================================= */
)
BEGIN
SET @IsAllowed = 1;
END;
IF @IsAllowed = 0
AND @WorkstationName IN
(
/* YOUR TRUSTED HOSTNAMES — EDIT BELOW */
N'www.google.com', -- example: your laptop
N'APP-SERVER-01' -- example: app server
)
BEGIN
SET @IsAllowed = 1;
END;
IF @IsAllowed = 1
BEGIN
/* Allowed: log it, but NEVER let a logging failure
block a legitimate login. */
BEGIN TRY
INSERT INTO SABlockAudit.dbo.LoginAudit
(LoginName, ClientHost, AppName, HostName, Spid, WasBlocked)
VALUES
(@LoginName, @ClientHost, APP_NAME(), HOST_NAME(), @@SPID, 0);
END TRY
BEGIN CATCH
-- swallow logging errors on the allow path
END CATCH;
RETURN;
END;
ROLLBACK;
BEGIN TRY
INSERT INTO SABlockAudit.dbo.LoginAudit
(LoginName, ClientHost, AppName, HostName, Spid, WasBlocked)
VALUES
(@LoginName, @ClientHost, APP_NAME(), HOST_NAME(), @@SPID, 1);
END TRY
BEGIN CATCH
END CATCH;
END;
GO
PRINT 'Logon trigger TR_SA_Block_RestrictedLogins is installed.';
GO