Read + Write + Report
Home | Start a blog | About Orble | FAQ | Sites | Writers | Advertise | My Orble | Login

SQL Server 2005 SysAdmin Login Auditing

November 15th 2008 12:19
SQL Server 2005 SysAdmin Login Auditing


Problem
I want to audit whenever a member of the sysadmin role logs on to my SQL Server. Auditing all successful logins provides that information, however, it logs every connection. The sysadmin logins are being lost amidst all the noise. How can I just track the sysadmin logins to my SQL Server instance?

Solution
In SQL Server 2005 Service Pack 2, Microsoft introduced logon triggers into the core functionality. Like DDL and DML triggers, these triggers fire on particular events, in this case, whenever a logon to the SQL Server instance occurs. We can use a logon trigger to audit when members of a particular role, such as the syadmin fixed server role, logs on.


In order to audit for members of the sysadmin fixed server role, we will need to use two system views: sys.server_role_members and sys.server_principals. We will join these views when a logon event occurs to determine if the logon is a member of the sysadmin role or not. We can get the members by joining these two views together as shown below:

SELECT sp.principal_id
FROM sys.server_role_members srm
INNER JOIN sys.server_principals sp
ON srm.member_principal_id = sp.principal_id
WHERE srm.role_principal_id = (
SELECT principal_id
FROM sys.server_principals
WHERE [Name] = 'sysadmin')

This query will be the basis for our logon trigger. By adding an AND clause in our final set of code, we will be able to test whether or not the incoming logon is a member of the sysadmin fixed server role.

We will also need to some place to record the event when it occurs. One of the easiest ways to do this is to use a table created for this purpose in a work database. For the purposes of this example, I am going to assume the table can be stored in a DBA database by the name of DBAWork. Here is the associated code:


CREATE TABLE dbo.AuditSysAdminLogin
(AuditEventId INT IDENTITY(1,1) NOT NULL,
EventTime DATETIME NOT NULL,
ServerLogin NVARCHAR(100) NOT NULL,
CONSTRAINT PK_AuditSysAdminLogin PRIMARY KEY CLUSTERED (AuditEventID));
GO

Once we have the audit table, we can create our logon trigger. The basic syntax for a logon trigger is similar to a DDL trigger as shown below:

CREATE TRIGGER <trigger name>
ON ALL SERVER
FOR LOGON
AS
<SQL Statements>

Following this format and using the query identified above to help identify who is a member of the SysAdmin role, the only aspect we are missing is a way to identify the logon. There is a system function, ORIGINAL_LOGIN(), which provides that information. Putting it all together, here is our logon trigger:

USE master;
GO

CREATE TRIGGER trigLogon_CheckForSysAdmin
ON ALL SERVER
FOR LOGON
AS
BEGIN
IF EXISTS (
SELECT sp.principal_id
FROM sys.server_role_members srm
JOIN sys.server_principals sp
ON srm.member_principal_id = sp.principal_id
WHERE role_principal_id = (
SELECT principal_id
FROM sys.server_principals
WHERE NAME = 'sysadmin')
AND ORIGINAL_LOGIN() = sp.NAME)
BEGIN
INSERT INTO DBAWork.dbo.AuditSysAdminLogin
(EventTime, ServerLogin)
VALUES
(GETDATE(), ORIGINAL_LOGIN())
END;
END;
GO



12
Vote
   


Junior SQL Server DBA Interview Questions


Problem
My organization is in the process of hiring a junior SQL Server DBA to add to our team. What are some fair questions to ask as a portion of the interview process? I want to make sure we hire someone who has a good base of knowledge. I am concerned are Senior SQL Server DBAs are looking to stump the candidates which is not really my goal. Do you have any suggestions?

Solution
Trying to assess any technical person's skill set can be difficult. An interview process with appropriate questions for your environment and the correct skill set are key. In some respects understanding what a candidate knows and does not know could be equally beneficial. What is meant by that is you want to know what knowledge someone has on day one and what you will need to teach them overtime. As such, here are a baseline set of questions for a junior SQL Server DBA:

Backup and Recovery

Question 1 - What are 2 options to validate whether or not a backup will restore successfully?
Restore the backup as a portion of a testing process or log shipping.
Restore the backup with the Verify Only option.
Additional information - Verifying Backups with the RESTORE VERIFYONLY Statement

Question 2 - How can you issue a full backup and not interrupt the LSN's?
Issue a copy only backup.
Additional information - COPY_ONLY Backups with SQL Server 2005

Performance Tuning

Question 1 - Name as many native SQL Server performance monitoring and tuning tools that you know of and their associated value.
System objects - System objects such as sp_who2, sp_lock, fn_get_sql, etc. provide a simple means to capture basic metrics related to locking, blocking, executing code, etc.
Additional information - SQL Server Command Line Tools To Manage Your Server
Profiler - In a nutshell, Profiler provides the lowest common denominator of activity on a SQL Server instance. Profiler captures per session code with the ability to filter the data collection based on database, login, host name, application name, etc. in order to assess the IO, CPU usage, time needed, etc.
Additional information - SQL Server Performance Statistics Using a Server Side Trace
Perfmon - Perfmon is responsible for macro level metrics related to processes and sub systems.
Additional information - Free Microsoft Tools to Help Setup and Maintain PerfMon
Dynamic Management Views and Functions - New to SQL Server 2005, the Dynamic Management Views and Functions offer a real time view into the SQL Server sub systems.
Additional information - Dynamic Management Views and Functions in SQL Server 2005
TYPEPERF.EXE - TYPEPERF.EXE is a command line tool included with the Windows operating system that writes performance data to the command window or to a file. It is necessary to capture performance data whenever you are trying to diagnose performance issues on a server. Performance data provides information on the server's utilization of the processor, memory, and disk, as well as SQL Server-specific performance data.
Additional information - How To Collect Performance Data With TYPEPERF.EXE
SQL Server Management Studio Built-in Performance Reports - As part of the installation of SQL Server 2005 a number of performance-related reports are installed. To get to these reports open the SQL Server Management Studio (SSMS) and connect to a SQL Server 2005 instance. If you don't have an instance of Reporting Services installed then the icon will be disabled.
Additional information - Built-In Performance Reports in SQL Server 2005

Question 2 - How do you go about tuning a SQL Server query?
Identify the query causing the issue.
Review the query plan by issuing SHOWPLAN_TEXT, SHOWPLAN_ALL, Graphical Query Plan or sys.dm_exec_query_stats.
Review the individual query components to determine which components of the query have the highest cost.
Outline options to improve the query such as moving from cursor based logic to set based logic or vice versa, changing the JOIN order, WHERE clause or ORDER BY clause, adding indexes, removing indexes, creating covering indexes, etc.
Test the options to determine the associated performance improvement.
Implement the solution.
Additional information - Query Plans in SQL Server 2000 vs SQL Server 2005

Maintenance

Question 1 - What are the three options in SQL Server 2005 to rebuild indexes?
CREATE INDEX with DROP_EXISTING
DROP INDEX and CREATE INDEX
ALTER INDEX
Additional information - Index Rebuilds in SQL Server 2000 vs SQL Server 2005

Question 2 - Name 3 or more DBCC commands and their associated purpose.
DBCC CACHESTATS - Displays information about the objects currently in the buffer cache.
DBCC CHECKDB - This will check the allocation of all pages in the database as well as check for any integrity issues.
DBCC CHECKTABLE - This will check the allocation of all pages for a specific table or index as well as check for any integrity issues.
DBCC DBREINDEX - This command will reindex your table. If the indexname is left out then all indexes are rebuilt. If the fillfactor is set to 0 then this will use the original fillfactor when the table was created.
DBCC PROCCACHE - This command will show you information about the procedure cache and how much is being used. Spotlight will also show you this same information.
DBCC MEMORYSTATUS - Displays how the SQL Server buffer cache is divided up, including buffer activity.
DBCC SHOWCONTIG - This command gives you information about how much space is used for a table and indexes. Information provided includes number of pages used as well as how fragmented the data is in the database.
DBCC SHOW_STATISTICS - This will show how statistics are laid out for an index. You can see how distributed the data is and whether the index is really a good candidate or not.
DBCC SHRINKFILE - This will allow you to shrink one of the database files. This is equivalent to doing a database shrink, but you can specify what file and the size to shrink it to. Use the sp_helpdb command along with the database name to see the actual file names used.
DBCC SQLPERF - This command will show you much of the transaction logs are being used.
DBCC TRACEON - This command will turn on a trace flag to capture events in the error log. Trace Flag 1204 captures Deadlock information.
DBCC TRACEOFF - This command turns off a trace flag.
Additional information - SQL Server Command Line Tools To Manage Your Server

Database Design

Question 1 - What happens when you add a column in the middle of a table (dbo.Test1) in Management Studio?
Management Studio creates a temporary table called dbo.Tmp_Test1 with the new structure.
If there is data in the original table dbo.Test1 this data is inserted into the new temp table dbo.Tmp_Test1 (now you have two sets of the same data).
The original table dbo.Test1 is dropped.
The new table dbo.Tmp_Test1 is renamed to dbo.Test1.
If the table has indexes all of the indexes are recreated.
Additional information - Modifying SQL Server database tables and keeping like columns together

Question 2 - What are included columns with respect to SQL Server indexing?
A new type of index was developed in SQL Server 2005 that assists in covering queries: Indexes With Included Columns. Indexes with Included Columns are nonclustered indexes that have the following benefits:
Columns defined in the include statement, called non-key columns, are not counted in the number of columns by the Database Engine.
Columns that previously could not be used in queries, like nvarchar(max), can be included as a non-key column.
A maximum of 1023 additional columns can be used as non-key columns.
Additional information - Improve Performance with SQL Server 2005 Covering Index Enhancements

SQL Server Business Intelligence

Question 1 - Name some new features from DTS to SSIS.
SSIS checkpoints.
SSIS logging.
SSIS package configurations.
SSIS Breakpoint.
Dynamic flat file connections.
SSIS batch processing.
MERGE JOIN.
Additional information - SQL Server Integration Services

Question 2 - How do you backup Analysis Services databases?
Create the XML statement to backup the Analysis Services databases, then create a SQL Server Agent Job to perform the task on a daily basis.
Additional information - Automating Backups for SQL Server 2005 Analysis Services Databases

16
Vote
   


An alternative to SQL Server email alerts


Problem
In a tip on How to setup SQL Server alerts and email operator notifications, you have seen how you can configure email alert notifications in your SQL Server instance. There are cases where we cannot use SQL Server alerts like in a SQL Server 2005 Express instance or a clustered SQL Server 2000 instance as the MAPI interface used by SQL Mail is not cluster-aware. What other alternatives do we have for sending email alert notifications?

Solution
Sending email alert notifications is one way of letting Database Administrators (DBAs) know of the status of an automated job. We use it to let us know if a database backup failed, an ETL job did not complete in time and similar other scenarios. SQL Server uses SQL Server Agent to do this task together with SQL Mail in SQL Server 2000 and Database Mail in SQL Server 2005. But without SQL Server Agent, like in SQL Server 2005 Express, we will not be able to use Database Mail. What we can do is use VBScripts or PowerShell scripts that can send emails using SMTP. We can then call these scripts from inside our stored procedures or from automated jobs using Windows Task Scheduler to enable us to send email alert notifications. Below is an example of a VBScript that can be used to send out emails. Save the file as sendEmailSMTP.vbs.

VBScript file that sends out email using SMTP

'Accept input parameters
Dim jobType

'first parameter
jobType= Wscript.Arguments.Item(0)

Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Message Alert from SQL Server: " & jobType & " job failed"
objMessage.From = "admin@domain.local"
objMessage.To = "sqladmin@domain.local"
objMessage.TextBody = "The " & databaseName & " " & jobType & " job running in the SQL Server instance failed on " & Now() & vbCrLF & vbCrLf & "Please look at this problem ASAP " & vbCrlf & vbCrlf & vbCrlf & vbCrlf & "- The SQL Server Administrator/DBA -"

'This section provides the configuration information for the remote SMTP
'server.Normally you will only change the server name or IP.
Really Long Link = 2

'Name or IP of Remote SMTP Server
Really Long Link = "smtp.domain.local"

'Server port number(typically 25)
Really Long Link = 25

objMessage.Configuration.Fiel ds.Update

objMessage.Send
Set objMessage = Nothing


The script accepts a parameter which you can customize which is the job type. You can customize the script with your own message, subject, sender and recipient addresses as well as the SMTP server address. An example of using this script would be to send email alerts in case a daily backup job failed as highlighted in the Automating SQL Server 2005 Express Backups and Deletion of Older Backup Files tip. You can generate an output file with the sqlcmd.exe utility and read the results of the output file. The call to the sqlcmd.exe utility would look something like this:

sqlcmd -S<INSTANCENAME>-E -i"E:\SQL_Backup\scripts\back upDB.sql" -o"E:\SQL_Backup\scripts\outp ut.txt"


Below is the VBScript code to read the output file and sends an email alert should the output file contain a specific error message pertaining to backup database command failing. It looks for the existence of the phrase "BACKUP DATABASE successfully processed" in the output file and, if not found, calls the VBScript file to send the email alert notification. Save the file as checkErrorLog.vbs.

VBScript file to read the output file and send email notifications

strFileNameResults="E:\SQL_Ba ckup\scripts\output.txt"
strParentFolder="E:\SQL_Backu p\scripts\"

Const ForReading = 1

Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileS ystemObject")
Set objFile = objFSO.OpenTextFile(strFileNa meResults, ForReading)
strContents = objFile.ReadAll

'The value=0 means that it cannot find the phrase RESTORE LOG successfully
'processed and thus means an error
If Instr(strContents,"BACKUP DATABASE successfully processed")=0 Then
objShell.Run(strParentFolder & "scripts\sendEmailSMTP.vbs BACKUP ")
End If

objFile.Close

Set objFSO=Nothing
Set objFile=Nothing
Set objShell=Nothing



You can then add a call to this VBScript file in your automated SQL Server job - be it a Scheduled Task in Windows or a call using xp_cmdshell.

24
Vote
   


Using the FORFILES Command to Delete SQL Server Backups


[ Click here to read more ]
14
Vote
Shared on
   


Replacing OPENXML with the XML nodes() Function in SQL Server 2005


[ Click here to read more ]
19
Vote
Shared on
   


SQL Server for Network Administrators

October 16th 2008 11:39
SQL Server for Network Administrators


[ Click here to read more ]
33
Vote
Shared on
   


SQL Server Cursor Examples

October 8th 2008 10:34
SQL Server Cursor Examples


[ Click here to read more ]
25
Vote
Shared on
   


How to find a SQL Server DBA Job

October 7th 2008 12:19
How to find a SQL Server DBA Job


[ Click here to read more ]
38
Vote
Shared on
   




Disaster Recovery Procedures in SQL Server 2005 Part 1


[ Click here to read more ]
40
Vote
Shared on
   


Disabling a Trigger for a Specific SQL Statement or Session


[ Click here to read more ]
32
Vote
Shared on
   


More Posts
4 Posts
5 Posts
7 Posts
51 Posts dating from May 2008
Email Subscription
Receive e-mail notifications of new posts on this blog:

Siddharth sood's Blogs

34 Vote(s)
0 Comment(s)
1 Post(s)
68 Vote(s)
0 Comment(s)
2 Post(s)
36 Vote(s)
0 Comment(s)
1 Post(s)
46 Vote(s)
0 Comment(s)
1 Post(s)
26 Vote(s)
0 Comment(s)
1 Post(s)
64 Vote(s)
0 Comment(s)
2 Post(s)
130 Vote(s)
0 Comment(s)
4 Post(s)
178 Vote(s)
1 Comment(s)
5 Post(s)
24 Vote(s)
0 Comment(s)
1 Post(s)
23 Vote(s)
0 Comment(s)
1 Post(s)
Moderated by Siddharth sood
Copyright © 2006 2007 2008 On Topic Media PTY LTD. All Rights Reserved. Design by Vimu.com.
On Topic Media ZPages: Sydney |  Melbourne |  Brisbane |  London |  Birmingham |  Leeds     [ Advertise ] [ Contact Us ] [ Privacy Policy ]