2

I am noticing a great deal of login attempts using the SA account from specific IP addresses on a regular basis. I would like to use a SQL Trigger or some other method to block these users from accessing the database, based on their IP addresses.

I was able to create a Database Table to collect the failed attempts via a stored procedure that I am planning to schedule to run every 10 minutes or so...

This is my database Table:

'''

USE [MASTER]
GO

CREATE TABLE [master].[dbo].[BLockedIPAddresses](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [ip] [varchar](50) NOT NULL,
    [attacked_on] [datetime2](2) NOT NULL,
    [banned_on] [datetime2](7) NOT NULL,
    [number_login_attempts] [int] NULL,
 CONSTRAINT [PK_BLockedIPAddresses] PRIMARY KEY CLUSTERED
([id] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80) ON [PRIMARY]) ON [PRIMARY]

ALTER TABLE [dbo].[BLockedIPAddresses] ADD  CONSTRAINT   [DF_BLockedIPAddresses_banned_on]  DEFAULT (getdate()) FOR [banned_on]


'''

Then, I created a Stored procedure to update and to keep the database table filled with new IPs that are attempting to login with the SA account.

'''

CREATE PROCEDURE [dbo].[sp_BLockedIPAddresses] 

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
-- [dbo].[BLockedIPAddresses]
DECLARE @T TABLE(LogDate datetime,ProcessInfo varchar(200),Text varchar(max))
    DECLARE @T2 TABLE(LogDate datetime,ProcessInfo varchar(200),IPAddress varchar(max))
    DECLARE @T3 TABLE(LogDate datetime,IPAddress varchar(max))
    DECLARE @IPAddress varchar(50),@LogDate datetime,@NumLoginAttempts int,@CmdExc varchar(300),@FailedLoginAttempts int=10

    BEGIN /* Get error log records with failed login attempt data */
        INSERT INTO @T
        EXEC sp_readerrorlog 0,1,'Password did not match that for the login provided'
        INSERT INTO @T
        EXEC sp_readerrorlog 1,1,'Password did not match that for the login provided'
        INSERT INTO @T
        EXEC sp_readerrorlog 2,1,'Password did not match that for the login provided'
        INSERT INTO @T
        EXEC sp_readerrorlog 3,1,'Password did not match that for the login provided'
        INSERT INTO @T
        EXEC sp_readerrorlog 4,1,'Password did not match that for the login provided'
        Select * from @T
        EXEC sp_readerrorlog 5,1,'Password did not match that for the login provided'
        Select * from @T
        EXEC sp_readerrorlog 6,1,'Password did not match that for the login provided'
        --Select * from @T
    END

    BEGIN /* Get the IP address from T*/
        INSERT INTO @T2
        SELECT LogDate,ProcessInfo,REPLACE(REPLACE( SUBSTRING(Text, PATINDEX ('%[0-9].%[0-9].%[0-9].[0-9]%',Text)-2,50),']',''),':','') FROM @T
    END

    BEGIN /* Get the NEW ip addresses from T2*/
        INSERT INTO @T3
        SELECT CONVERT(varchar(10),LogDate,101) LogDate,IPAddress from @T2 T
        WHERE NOT EXISTS(SELECT * FROM [master].[dbo].[BLockedIPAddresses] ai WHERE ai.ip=T.IPAddress)
        GROUP BY CONVERT(varchar(10),LogDate,101),IPAddress
        HAVING  COUNT(LogDate)>@FailedLoginAttempts
        ORDER BY IPAddress
    END

    BEGIN /* Validate that T3 has records, if not skip the firewall add */
        IF (SELECT COUNT(*) FROM @T3)=0
        BEGIN
            GOTO ExitWithoutCycle
        END
    END

    BEGIN /* Loop through T3 and add each entry to the windows firewall */
        WHILE EXISTS(SELECT * FROM @T3)
        BEGIN
            SELECT TOP(1) @LogDate=LogDate, @IPAddress=IPAddress FROM @T3
            SELECT @NumLoginAttempts=COUNT(*) FROM @T2 WHERE IPAddress=@IPAddress
                INSERT INTO [master].[dbo].[BLockedIPAddresses] (attacked_on,ip,number_login_attempts) VALUES(@LogDate,@IPAddress,@NumLoginAttempts)
                --SET @CmdExc = 'netsh advfirewall firewall add rule name="Autobanned IP - SQL Attacked '+@IPAddress+'" dir=in action=block enable="yes" remoteip='+@IPAddress+' protocol=any interfacetype=any'
                --EXEC master..xp_cmdshell @CmdExc
            DELETE @T3 WHERE IPAddress=@IPAddress
        END
    END
    /* sp_cycle_errorlog archives the current error log. */
    EXEC sp_cycle_errorlog
    ExitWithoutCycle:

END

'''

However, this approach is not working for me. I am still seeing login attempts on the database log files.

Can I get a workable approach recommendation that I can use to mitigate this Security attack on the Server?

2
  • You can't stop someone from attempting to access your server instance INSIDE your instance. That must be done OUTSIDE - using whatever network tools you have (e.g., firewall). Inside your instance, it is not clear if you want to block access (even if using valid id and password) from that address or just failed attempts. But you don't have to block failed attempts since the logon failed. If your goal is to bock any logon attempt from that address, then you need a logon trigger.
    – SMor
    Aug 7, 2019 at 18:41
  • But do what shekar suggests FIRST.
    – SMor
    Aug 7, 2019 at 18:41

2 Answers 2

6

I Like the idea, but aside from this i would recommend to do following first:

  1. Always disable sa account on production server, create separate account with sysadmin permissions on the server before disabling sa
  2. Avoid adding all logins into sysadmin role, Logins may required db_owner permissions on particular database but not on entire server.
  3. Create WMI Alert on server which notify via email whenever there is change occurred in Logins/Roles/Users. for detailed steps Creating WMI Alert on SQL Server
  4. Use non-standard ports for SQL Server and it's instances (other than 1433, 1434)
  5. Make sure unwanted user accounts NOT added into builtin\administrators group of server where SQL services running
  6. Not sure whether it applicable in your environment, but it's better to avoid exposing Database server IP accessible all over the network, as long as the application servers having access to Database server that would be enough. For the management activities user must be accessing the database server through application server's network/VLAN
1
  • Thank you for your expert guidance and advice. I read both SMor and Yours (Shekar) and implemented a new approach that I think will do the work of blocking the IP addresses that are trying to login to the Server. First, I am using the Stored Procedure to collect the SQL Server login attempts and
    – Johnny
    Aug 10, 2019 at 14:53
0

Thank you for your expert guidance and advice. I read both SMor and Yours (Shekar) and implemented a new approach that I think will do the work of blocking the IP addresses that are trying to login to the Server.

First, I moved the primary workload out of the SQL Server and coded a new PowerShell script that scans the Windows Security logs for the failed login ID and saved the IPs that have a failed attempt count of 10 to a text file.

Second, from that same PS Script, I called the Stored Procedure that performs the same work for SQL Server failed login attempts and added the found IPs to the same text file.

Third, I added a step to the PS script to launch a batch file that read the failed IPs text and calls the Firewall command line tool to create a new "block" entry for every IP address from the list.

Finally, I use the Windows Task Scheduler to schedule the PS Script to run every 10 minutes to update the Firewall with newly found IPs.

I monitored the solution for about one hour and it is working. The server still gets some attempts and they will get added to the firewall once they reach the required 10 failed attempts. BTW, I accidentally blocked my own IP address from the Server by selecting a smaller required failed attempt value of 5 :). I had to use another PC with a different IP to regain access to remove my IP and increase the requirement.

Thanks again for the guidance and recommendations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.