September 09, 2010

Block IP Addresses to SQL Server using a Logon Trigger




We were testing a scenario and wanted to block SQL Server connection through certain IP addresses. Here’s how we solved the requirement using a Logon Trigger

CREATE TRIGGER AllowLocalOnly
ON ALL SERVER
FOR LOGON
AS
BEGIN
DECLARE @IP Varchar(500)
SET @IP = EVENTDATA().value
('(/EVENT_INSTANCE/ClientHost)[1]', 'varchar(500)')
IF @IP
IN ('172.16.255.11', '172.20.254.1', '172.26.254.12')
BEGIN
Print 'There I caught you ' + @IP
ROLLBACK TRANSACTION
END
END
GO

If the user tries to login through any of these I.P. addresses, the Logon trigger will fire after the authentication phase of logging, but before the user session is actually established, and rollback the transaction. This will restrict Login to SQL Server.

If there is an attempt to login from any of these I.P. Addresses, you can find out by searching the SQL Server error log for something similar to – ‘There I caught you 172.16.255.11 ’. Although I haven’t tried but you can also send an email instead of just printing the error in the error log.

Note: Logon Triggers are available only from SQL Server 2005 SP2 onwards.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

2 Responses to "Block IP Addresses to SQL Server using a Logon Trigger"
  1. Anonymous said...
    April 8, 2011 at 4:21 AM

    well
    nice post
    just copied from

    http://www.shirmanov.com/2010/09/block-ip-addresses-to-sql-server-using.html

    try to write something by yourself

  2. Suprotim Agarwal said...
    April 8, 2011 at 5:54 AM

    Although this is a lame comment from you (whoever you are), next time try to check the post dates :).

    Mine was on the 9th of September and the link you posted was on the 25th of Sept. So probably using a little brain, anybody will know who copied whom!

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions