Audit trong Sql Server 2012

Ngoài những tính năng về Audit đã có trong các phiên bản trước, SQL Server 2012 cung cấp thêm rất nhiều tính năng mới, trong đó bao gồm một số cải tiến mạnh mẽ cho khả năng giám sát (audit) SQL Server. Phần đầu của bài viết này xin khái quát lại tất cả những tính năng về audit có trong những phiên bản SQL Server trước đây, bao gồm các tính năng: • Trigger • SQL Server Audit • Change Data Capture (CDC) • Change Tracking (CT)

doc15 trang | Chia sẻ: lylyngoc | Lượt xem: 2230 | Lượt tải: 1download
Bạn đang xem nội dung tài liệu Audit trong Sql Server 2012, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
AUDIT TRONG SQL SERVER 2012 Ngoài những tính năng về Audit đã có trong các phiên bản trước, SQL Server 2012 cung cấp thêm rất nhiều tính năng mới, trong đó bao gồm một số cải tiến mạnh mẽ cho khả năng giám sát (audit) SQL Server. Phần đầu của bài viết này xin khái quát lại tất cả những tính năng về audit có trong những phiên bản SQL Server trước đây, bao gồm các tính năng: Trigger SQL Server Audit Change Data Capture (CDC) Change Tracking (CT) 1. Trigger Trigger là 1 đối tượng (object) trong database cho phép chạy thủ tục lưu trữ (stored procedure) nào đó mỗi khi có 1 thay đổi xảy ra. Có 2 loại Trigger: DDL Trigger: áp dụng cho những thay đổi liên quan đến cấu trúc của database, như: ALTER DATABASE, CREATE TABLE, … DML Trigger: áp dụng cho những thay đổi liên quan trực tiếp đến dữ liệu, như: UPDATE, INSERT, DELETE. Trigger có thể được sử dụng với nhiều mục đích khác nhau, ví dụ như: Để ngăn không cho thay đổi cấu trúc của 1 Table nào đó (DDL Trigger cho ALTER TABLE) Để định dạng lại giá trị trước khi chèn vào 1 Table nào đó (DML Trigger cho Insert với chế độ Instead hoặc After) Để log lại những thay đổi về mặc cấu trúc hay dữ liệu của 1 Table (DDL Trigger hoặc DML Trigger) Các Trigger có thể được cài đặt để log lại những thay đổi đó ở nhiều nơi: Lưu lại những thay đổi trong 1 hoặc nhiều table, thuộc 1 hoặc nhiều database khác nhau, của 1 hoặc nhiều server khác nhau (sử dụng Linked Server). Sử dụng Service Broker gửi message đến nhiều nơi khác nhau, như: file trong server, event trong Event Viewer, hay email đến người quản trị. Ví dụ sau đây sẽ tạo 1 Trigger bắt tất cả các sự kiện liên quan đến các câu lệnh DDL ở trong database Test và lưu vào trong table DDL_Log. USE Test GO -- tạo bảng DDL_Log CREATE TABLE DDL_Log ( PostTime datetime, DB_User nvarchar (100), Event nvarchar (100), TSQL nvarchar (2000) ) GO -- tạo Trigger CREATE TRIGGER myDDLTrigger ON DATABASE FOR DDL_DATABASE_LEVEL_EVENTS AS DECLARE @data XML SET @data = EVENTDATA() INSERT DDL_Log (PostTime, DB_User, Event, TSQL) VALUES ( GETDATE(), CONVERT(nvarchar(100), CURRENT_USER), @data.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'), @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(2000)') ) ; GO 2. SQL Server Audit SQL Server Audit có từ phiên bản SQL Server 2008 Enterprise. Tính năng này đơn giản hoá khả năng giám sát tự động (automatic audit) và có thể thay thế cho việc cài đặt các Trigger. SQL Server Audit có thể cấu hình giám sát ở 2 mức (level): instance và database. Các thành phần của SQL Server Audit: Audit Object: Trong mỗi Instance chúng ta có thể tạo ra nhiều audit khác nhau. Ứng với mỗi Audit sẽ phải chỉ ra 1 audit destination để ghi lại những thông tin được giám sát. Server Audit Specification: quy định cho 1 Audit cụ thể nào đó 1 tập các hành động của Instance cần giám sát, ví dụ: CREATE LOGIN, ALTER DATABASE, … . Chúng ta có thể tạo 1 server audit specification cho mỗi SQL Server Audit. Database Audit Specification: quy định cho 1 Audit cụ thể nào đó 1 tập các hành động của database object cần giám sát, ví dụ: CREATE TABLE, ALTER VIEW, … . Chúng ta có thể tạo 1 database audit specification cho mỗi SQL Server Audit. Target: chính là Audit destination được chỉ ra trong mỗi Audit. Target có thể là 1 file, 1 Windows Security event log, hay 1 Windows Application event log. Ví dụ sau đây sẽ tạo 1 Audit để log lại thông tin mỗi khi có 1 connection nào đó login bị fail (do nhiều nguyên nhân khác nhau: không đúng username, sai password, …) và lưu những thông tin đó trong Windows Application log. USE master ; GO --Tạo Audit CREATE SERVER AUDIT mySQLServerAudit TO APPLICATION_LOG WITH ( QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE); GO --Tạo Server Audit Specification và gán cho Audit CREATE SERVER AUDIT SPECIFICATION FailedLoginServerAuditSpecification FOR SERVER AUDIT mySQLServerAudit ADD (FAILED_LOGIN_GROUP); --Enable audit ALTER SERVER AUDIT mySQLServerAudit WITH (STATE = ON); GO 3. Change Data Capture (CDC) Microsoft bắt đầu cung cấp tính năng CDC từ phiên bản SQL Server 2008 để đơn giản hoá và có thể thay thế cho việc cài đặt các DML Trigger trong việc lưu lại dấu vết của những dữ liệu đã bị thay đổi. Sau khi bật và cấu hình tính năng, CDC sẽ ghi lại tất cả các thay đổi (bao gồm Insert, Update, Delete) về dữ liệu trên 1 table và lưu trữ những thay đổi đó trong các System table. CDC có thể lưu lại 1 số thông tin như sau: Update mask: chỉ ra lệnh DML tác động lên dữ liệu, trong đó: 1 = Delete, 2 = Insert, 3 = Before Update, 4 = After Update Các dữ liệu bị thay đổi Thời điểm dữ liệu bị thay đổi … Dựa vào những thông tin trên, người quản trị có thể dễ dàng kiểm tra, theo dõi những thay đổi này thông qua các Stored Procedure hoặc xem trực tiếp các system table do CDC tạo ra. Ví dụ sau đây sẽ bật tính năng CDC cho table Test và xem những thay đổi đó thông qua việc truy vấn stored procedure hay system table. --bật tính năng CDC cho database EXEC sys.sp_cdc_enable_db GO --bật tính năng CDC cho table Test EXEC sys.sp_cdc_enable_table N'dbo', N'Test',DEFAULT,DEFAULT, 1 GO /* thực hiện 1 số lệnh Insert, Update, Delete */ -- xem thông tin bằng cách truy vấn stored procedure SELECT * FROM cdc.fn_cdc_get_all_changes_dbo_TestTable (sys.fn_cdc_get_min_lsn('dbo_Test'), sys.fn_cdc_get_max_lsn(),N'all') --xem thông tin trực tiếp từ system table SELECT * FROM cdc.dbo_Test_CT 4. Change Tracking (CT) Change Tracking cho phép các ứng dụng theo dõi được những thay đổi trong các table của ứng dụng đó. Điểm khác biệt của CT so với CDC là CT không lưu lại các dữ liệu hiện hành mỗi khi có thay đổi mà chỉ lưu lại 1 số thông tin cơ bản như Primary key của dòng dữ liệu có thay đổi, số lần thay đổi của dòng dữ liệu đó, … Phải enable tính năng Change Tracking cho từng table mà bạn muốn theo dõi -- bật tính năng Change Tracking cho database ALTER DATABASE AdventureWorks2012 SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON); --bật tính năng Change Tracking cho table ALTER TABLE Test ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = ON); Sau khi bật Change Tracking, chúng ta có thể sử dụng 1 số view hoặc function để xem thông tin: --liệt kê các database trong instance có bật tính năng Change Tracking SELECT * FROM sys.change_tracking_databases --liệt kê các table trong database hiện tại có bật tính năng Change Tracking SELECT * FROM sys.change_tracking_tables /*liệt kê tất cả các dòng dữ liệu trong table Test (đã bật  tính năng Change Tracking) cùng với các thông tin về version tuơng ứng */ SELECT t.*, ct.* FROM Test t CROSS APPLY CHANGETABLE ( VERSION Test, (id), t.id ) AS ct; Với những tính năng trên, người quản trị có đủ khả năng để giám sát 1 cách chi tiết những thay đổi về cấu trúc cũng như về dữ liệu trong các database của mình . Vậy trong SQL Server 2012 sẽ có thêm những cải tiến gì? Vậy trong SQL Server 2012, sẽ có thêm những cải tiến gì trong việc Audit nói chung hay SQL Server Audit nói riêng? Câu hỏi này được rất nhiều người quản trị database quan tâm và sẽ được làm rõ thông qua các tính năng được đề cập trong Phần 2 này, bao gồm: Khả năng tạo User-defined Audit Khả năng lọc Audit (Audit Filtering) Hỗ trợ tự động khôi phục log (Audit resilience) Thêm vào đó, thay vì chỉ được cung cấp trong bản Enterprise như ở phiên bản SQL Server 2008 thì nay SQL Server Audit được tích hợp trong tất cả các bản edition của SQL Server 2012 với tốc độ được cải thiện 1 cách đáng kể cùng nhiều tính năng hơn. 1. User-Defined Audit User-Defined Audit cho phép các ứng dụng tự tuỳ biến, tạo ra các sự kiện của riêng mình và ghi thông tin audit log 1 cách linh hoạt hơn, ví dụ như: ghi vào audit log tên của các user đăng nhập vào application thay cho tên login chung được khai báo trong connection string để ứng dụng kết nối đến database. Chúng ta có thể add thêm các sự kiện (audit event) như vậy bằng việc sử dụng thủ tục (stored procedure) sp_audit_write. Khi đó tất cả các sự kiện sẽ được lưu trong group USER_DEFINED_AUDIT_GROUP. Lưu ý rằng để sử dụng được, trước đó USER_DEFINED_AUDIT_GROUP phải được enable. Ví dụ sau sẽ ghi vào audit log 1 sự kiện với id = 141 cùng 1 số thông tin tuỳ thích. EXEC sp_audit_write @user_defined_event_id =  141,   @succeeded = 0,   @user_defined_information = N'My information' ; Một số cột mới (column) được thêm vào sys.server_audits, sys.server_file_audits, và sys.fn_get_audit_file để theo dõi các user-defined audit event.. 2. Audit Filtering Trước đây, thật không dễ dàng để chỉ  lọc (theo 1 điều kiện cụ thể nào đó) những sự kiện mà người quản trị đang quan tâm. Điều này đã được khắc phục trong phiên bản SQL Server 2012 với tính năng Audit Filtering. Giờ đây, SQL Server Audit hỗ trợ khả năng lọc những sự kiện cần audit trước khi chúng được ghi vào audit log thông qua mệnh đề WHERE  trong câu lệnh CREATE SERVER AUDIT và ALTER SERVER AUDIT. 2.1. CREATE SERVER AUDIT (Transact-SQL) Syntax CREATE SERVER AUDIT audit_name { TO { [ FILE ( [ , ...n ] ) ] | APPLICATION_LOG | SECURITY_LOG } [ WITH ( [ , ...n ] ) ] [ WHERE ] } [ ; ] ::= { FILEPATH = 'os_file_path' [ , MAXSIZE = { max_size { MB | GB | TB } | UNLIMITED } ] [ , { MAX_ROLLOVER_FILES = { integer | UNLIMITED } } | { MAX_FILES = integer } ] [ , RESERVE_DISK_SPACE = { ON | OFF } ] } ::= { [ QUEUE_DELAY = integer ] [ , ON_FAILURE = { CONTINUE | SHUTDOWN | FAIL_OPERATION } ] [ , AUDIT_GUID = uniqueidentifier ] } ::= {     [NOT ]     [ { AND | OR } [NOT ] { } ]     [,...n ] } ::=     event_field_name { = | | ! = | > | > = | < | < = } { number | ' string ' } Arguments TO { FILE | APPLICATION_LOG | SECURITY_LOG } Determines the location of the audit target. The options are a binary file, The Windows Application log, or the Windows Security log. SQL Server cannot write to the Windows Security log without configuring additional settings in Windows. For more information, see Write SQL Server Audit Events to the Security Log. FILEPATH ='os_file_path' The path of the audit log. The file name is generated based on the audit name and audit GUID. MAXSIZE = { max_size } Specifies the maximum size to which the audit file can grow. The max_size value must be an integer followed by MB, GB, TB, or UNLIMITED. The minimum size that you can specify for max_size is 2 MB and the maximum is 2,147,483,647 TB. When UNLIMITED is specified, the file grows until the disk is full. Specifying a value lower than 2 MB will raise the error MSG_MAXSIZE_TOO_SMALL. The default value is UNLIMITED. MAX_ROLLOVER_FILES ={ integer | UNLIMITED } Specifies the maximum number of files to retain in the file system in addition to the current file. The MAX_ROLLOVER_FILES value must be an integer or UNLIMITED. The default value is UNLIMITED. This parameter is evaluated whenever the audit restarts (which can happen when the instance of the Database Engine restarts or when the audit is turned off and then on again) or when a new file is needed because the MAXSIZE has been reached. When MAX_ROLLOVER_FILES is evaluated, if the number of files exceeds the MAX_ROLLOVER_FILES setting, the oldest file is deleted. As a result, when the setting of MAX_ROLLOVER_FILES is 0 a new file is created each time the MAX_ROLLOVER_FILES setting is evaluated. Only one file is automatically deleted when MAX_ROLLOVER_FILES setting is evaluated, so when the value of MAX_ROLLOVER_FILES is decreased, the number of files will not shrink unless old files are manually deleted. The maximum number of files that can be specified is 2,147,483,647. MAX_FILES =integer Specifies the maximum number of audit files that can be created. Does not rollover to the first file when the limit is reached. When the MAX_FILES limit is reached, any action that causes additional audit events to be generated will fail with an error. RESERVE_DISK_SPACE = { ON | OFF } This option pre-allocates the file on the disk to the MAXSIZE value. It applies only if MAXSIZE is not equal to UNLIMITED. The default value is OFF. QUEUE_DELAY =integer Determines the time, in milliseconds, that can elapse before audit actions are forced to be processed. A value of 0 indicates synchronous delivery. The minimum settable query delay value is 1000 (1 second), which is the default. The maximum is 2,147,483,647 (2,147,483.647 seconds or 24 days, 20 hours, 31 minutes, 23.647 seconds). Specifying an invalid number will raise the error MSG_INVALID_QUEUE_DELAY. ON_FAILURE = { CONTINUE | SHUTDOWN | FAIL_OPERATION } Indicates whether the instance writing to the target should fail, continue, or stop SQL Server if the target cannot write to the audit log. The default value is CONTINUE. CONTINUE SQL Server operations continue. Audit records are not retained. The audit continues to attempt to log events and will resume if the failure condition is resolved. Selecting the continue option can allow unaudited activity which could violate your security policies. Use this option, when continuing operation of the Database Engine is more important than maintaining a complete audit. SHUTDOWN Forces a server shut down when the server instance writing to the target cannot write data to the audit target. The login issuing this must have the SHUTDOWN permission. If the logon does not have this permission, this function will fail and an error message will be raised. No audited events occur. Use the option when an audit failure could compromise the security or integrity of the system. FAIL_OPERATION Database actions fail if they cause audited events. Actions which do not cause audited events can continue, but no audited events can occur. The audit continues to attempt to log events and will resume if the failure condition is resolved. Use this option when maintaining a complete audit is more important than full access to the Database Engine. AUDIT_GUID =uniqueidentifier To support scenarios such as database mirroring, an audit needs a specific GUID that matches the GUID found in the mirrored database. The GUID cannot be modified after the audit has been created. predicate_expression Specifies the predicate expression used to determine if an event should be processed or not. Predicate expressions are limited to 3000 characters, which limits string arguments. event_field_name Is the name of the event field that identifies the predicate source. Audit fields are described in sys.fn_get_audit_file (Transact-SQL). All fields can be audited except file_name and audit_file_offset. number Is any numeric type including decimal. Limitations are the lack of available physical memory or a number that is too large to be represented as a 64-bit integer. ' string ' Either an ANSI or Unicode string as required by the predicate compare. No implicit string type conversion is performed for the predicate compare functions. Passing the wrong type results in an error. Examples A. Creating a server audit with a file target The following example creates a server audit called HIPPA_Audit with a binary file as the target and no options. CREATE SERVER AUDIT HIPAA_Audit TO FILE ( FILEPATH ='\\SQLPROD_1\Audit\' ); B. Creating a server audit with a Windows Application log target with options The following example creates a server audit called HIPPA_Audit with the target set for the Windows Application log. The queue is written every second and shuts down the SQL Server engine on failure. CREATE SERVER AUDIT HIPAA_Audit TO APPLICATION_LOG WITH ( QUEUE_DELAY = 1000, ON_FAILURE = SHUTDOWN); C. Creating a server audit containing a WHERE clause The following example creates a database, schema, and two tables for the example. The table named DataSchema.SensitiveData will contain confidential data and access to the table must be recorded in the audit. The table named DataSchema.GeneralData does not contain confidential data. The database audit specification audits access to all objects in the DataSchema schema. The server audit is created with a WHERE clause that limits the server audit to only the SensitiveData table. The server audit presumes a audit folder exists at C:\SQLAudit. Transact-SQL CREATE DATABASE TestDB; GO USE TestDB; GO CREATE SCHEMA DataSchema; GO CREATE TABLE DataSchema.GeneralData (ID int PRIMARY KEY, DataField varchar(50) NOT NULL); GO CREATE TABLE DataSchema.SensitiveData (ID int PRIMARY KEY, DataField varchar(50) NOT NULL); GO -- Create the server audit in the master database USE master; GO CREATE SERVER AUDIT AuditDataAccess     TO FILE ( FILEPATH ='C:\SQLAudit\' )     WHERE object_name = 'SensitiveData' ; GO ALTER SERVER AUDIT AuditDataAccess WITH (STATE = ON); GO -- Create the database audit specification in the TestDB database USE TestDB; GO CREATE DATABASE AUDIT SPECIFICATION [FilterForSensitiveData] FOR SERVER AUDIT [AuditDataAccess] ADD (SELECT ON SCHEMA::[DataSchema] BY [public]) WITH (STATE = ON); GO -- Trigger the audit event by selecting from tables SELECT ID, DataField FROM DataSchema.GeneralData; SELECT ID, DataField FROM DataSchema.SensitiveData; GO -- Check the audit for the filtered content SELECT * FROM fn_get_audit_file('C:\SQLAudit\AuditDataAccess_*.sqlaudit',default,default); GO 2.2. ALTER SERVER AUDIT (Transact-SQL) Syntax ALTER SERVER AUDIT audit_name {     [ TO { { FILE ( [, ...n] ) } | APPLICATION_LOG | SECURITY_LOG } ]     [ WITH ( [ , ...n] ) ]     [ WHERE ] } | REMOVE WHERE | MODIFY NAME = new_audit_name [ ; ] ::= {       FILEPATH = 'os_file_path'     | MAXSIZE = { max_size { MB | GB | TB } | UNLIMITED }     | MAX_ROLLOVER_FILES = { integer | UNLIMITED }     | MAX_FILES = integer     | RESERVE_DISK_SPACE = { ON | OFF } } ::= {       QUEUE_DELAY = integer     | ON_FAILURE = { CONTINUE | SHUTDOWN | FAIL_OPERATION }     | STATE = = { ON | OFF } } ::= {     [NOT ]     [ { AND | OR } [NOT ] { } ]     [,...n ] } ::=     event_field_name { = | | ! = | > | > = | < | < = } { number | ' string ' } Arguments TO { FILE | APPLICATION_LOG | SECURITY } Determines the location of the audit target. The options are a binary file, the Windows application log, or the Windows security log. FILEPATH = 'os_file_path' The path of the audit trail. The file name is generated based on the audit name and audit GUID. MAXSIZE =max_size Specifies the maximum size to which the audit file can grow. The max_size value must be an integer followed by MB, GB, TB, or UNLIMITED. The minimum size that you can specify for max_size is 2 MB and the maximum is 2,147,483,647 TB. When UNLIMITED is specified the file grows until the disk is full. Specifying a value lower than 2 MB will raise the error MSG_MAXSIZE_TOO_SMALL. The default value is UNLIMITED. MAX_ROLLOVER_FILES =integer | UNLIMITED Specifies the maximum number of files to retain in the file system. When the setting of MAX_ROLLOVER_FILES=0 there is no limit imposed on the number of rollover files that will be created. The default value is 0. The maximum number of files that can be specified is 2,147,483,647. MAX_FILES =integer Specifies the maximum number of audit files that can be created. Does not rollover to the first file when the limit is reached. When the MAX_FILES limit is reached, any action that causes additional audit events to be generated will fail with an error. RESERVE_DISK_SPACE = { ON | OFF } This option pre-allocates the file on the disk to the MAXSIZE value. Only applies if MAXSIZE is not equal to UNLIMITED. The default value is OFF. QUEUE_DELAY =integer Determines the time in milliseconds that can elapse before audit actions are forced to be processed. A value of 0 indicates synchronous delivery. The minimum settable query delay value is 1000 (1 second), which is the default. The maximum is 2,147,483,647 (2,147,483.647 seconds or 24 days, 20 hours, 31 minutes, 23.647 seconds). Specifying an invalid number will raise the error MSG_INVALID_QUEUE_DELAY. ON_FAILURE = { CONTINUE | SHUTDOWN | FAIL_OPER