Esta semana mientras trabajaba en Bolivia escuché al personal de seguridad de un cliente discutir sobre las opciones que podían utilizar para auditar las transacciones realizadas a las tablas de una base de datos. Los interrumpí y les pregunté si habían escuchado a cerca de la configuración de auditorías en SQL Server 2008 y me dijeron que no. Así que aproveché el tema para escribir el siguiente artículo.
La primera pregunta que nos surge es: ¿Porque auditamos?
Revisando la literatura de auditoría de seguridad, los autores coinciden en que el tener políticas de seguridad es un factor crítico para mantener los datos seguros. La auditoría también nos ayuda a identificar lo que accedió un intruso en el evento de que un ataque sea exitoso.
En SQL 2005 el enfoque estaba orientado a asegurarse de que el usuario no tuviera privilegio mayores a los que necesitaba y que los cambios fueran realizados por el personal autorizado. La herramienta que se promovía para auditar los cambios a la base de datos era el SQL Profiler ya que podía auditar cambios al esquema, operaciones de insertar, actualizar o eliminar registros; y eventos relacionados con cambios de permisos o la creación de nuevos Logins.
Una de las mejoras que trajo SQL Server 2008 Enterprise es un incremento en la capacidad de auditoría a través del uso del SQL Server Audit. A través de esta funcionalidad se puede rastrear y registrar de forma automática los eventos que ocurren a nivel del servidor o a nivel de la base de datos. Esto es posible a través del uso del objeto Audit. Veamos entonces como crear una auditoría, como crear y habilitar una especificación de auditoría a nivel de Servidor o a nivel de base de datos y como visualizar los registros de auditoría.
Crear una Auditoría
Un objeto de auditoría es una colección de una o más acciones individuales o un grupo de acciones que podrán ser rastreadas. Por ejemplo, se puede configurar un objeto de auditoría para identificar todos los logins fallidos. Los eventos se escriben en la localización que se especifique. Se pueden almacenar en un archivo, la bitácora de eventos de aplicaciones o la bitácora de eventos de seguridad.
El objeto de auditoría se puede crear a través del Management Studio (SSMS) o utilizando T-SQL. Desde SSMS se debe presionar el botón de la derecha del mouse sobre la opción New Audit localizada en la carpeta de auditoría bajo el árbol de Seguridad, como se muestra a continuación:
En la pantalla Create Audit se debe ingresar el nombre del objeto de auditoría, y se debe especificar el destino. Si se indica que el destino será un archivo, hay que especificar la ruta donde será almacenado. Finalmente se debe presionar el botón OK para crear el objeto de auditoría.
Para propósitos de este ejemplo cree un segundo objeto de auditoría e ingrese el nombre “AuditarConsultasTablaEmpleado”. Seleccione como destino un archivo e indique la ruta donde desee almacenarlo. Ambos objetos estarán localizados bajo la carpeta Audits, como se muestra a continuación. Este objeto de auditoría se utilizará para rastrear las transacciones SELECT realizadas contra la tabla HumanResources.Employee de la base de datos AdventureWorks2008R2.
Si desea crear un objeto de auditoría a través de T-SQL lo puede hacer utilizando el comando CREATE SERVER AUDIT. La siguiente consulta crea el objeto “AuditarConsultasTablaEmpleado”. Esta operación fue realizada anteriormente a través de SSMS.
USE master
CREATE SERVER AUDIT [AuditarConsultasTablaEmpleado]
TO FILE (FILEPATH = N'C:\TEMP');
Crear y habilitar una especificación de auditoría a nivel de Servidor
Una vez se ha creado los objetos de auditoría, el siguiente paso es crear las especificaciones apropiadas de auditoría. Las especificaciones de auditoría le indican al objeto de auditoría lo que debe rastrear. En el caso del objeto de auditoría llamado “AuditarLoginsFallidos”, debemos crear una especificación que busque los logins que no son exitosos. Para lograrlo debemos seleccionar el botón de la derecha del mouse sobre la carpeta “Server Audit Specifications” ubicada bajo el árbol de Seguridad.
Asigne a la especificación de auditoría el nombre: “EspecificacionAuditoriaServidor-LoginsFallidos”. Bajo audit seleccione la opción “AuditarLoginsFallidos”. Esto asignará la especificación de auditoría “EspecificacionAuditoriaServidor-LoginsFallidos” al objeto de auditoría “AuditarLoginsFallidos”. Seleccione el tipo de acción para auditar: “FAILED_LOGIN_GROUP” y presione OK para crear y asignar el objeto de auditoría.
Presione el botón de la derecha del mouse sobre “EspecificacionAuditoriaServidor-LoginsFallidos” para habilitar la especificación a través de la opción: “Enable Server Audit Specification”
Finalmente debe habilitar el objeto de auditoría presionando el botón de la derecha del mouse sobre “AuditarLoginsFallidos” para habilitar la auditoria a través de la opción Enable Audit como se muestra en la siguiente figura.
Si desea crear una especificación de auditoría a nivel de servidor, a través de T-SQL, lo puede hacer utilizando el comando CREATE SERVER AUDIT SPECITICATION. La siguiente consulta crea la especificación de auditoría “EspecificacionAuditoriaServidor-LoginsFallidos”. Esta operación fue realizada anteriormente a través de SSMS.
CREATE SERVER AUDIT SPECIFICATION [EspecificacionAuditoriaServidor-LoginsFallidos]
FOR SERVER AUDIT [AuditarLoginsFallidos]
ADD (FAILED_LOGIN_GROUP) WITH (STATE = ON)
GO
Crear y habilitar una especificación de auditoría a nivel de base de datos
Para crear y habilitar una especificación de auditoría a nivel de base de datos debe expandir la base de datos, en este ejemplo utilice AdventureWorks2008R2, y seleccione con el botón de la derecha del mouse la opción “Audit Specifications” bajo el árbol de seguridad de la base de datos. Seleccione la opción “New Database Audit Specification” y asigne un nombre (para propósito de este ejemplo asignaremos el nombre: “EspecificacionAuditoriaDB-ConsultasTablaEmpleado”)
Como se muestra en la siguiente figura, seleccione la opción “AuditarConsultasTablaEmpleado” Bajo audit. Esto asignará la especificación de auditoría “EspecificacionAuditoriaDB-ConsultasTablaEmpleado” al objeto de auditoría “AuditarConsultasTablaEmpleado”.
Nota: La clase de objeto se utiliza para indicar lo que se quiere auditar. Las opciones son: Objeto, Base de datos o Esquema. Seleccione objeto para auditar Tablas, Funciones, Procedimientos Almacenados o Vistas. El nombre del Principal son entidades que pueden solicitar recursos de SQL Server.
Para propósitos de este ejemplo, seleccione “SELECT” en el tipo de acción para auditar; en la clase del objeto seleccione “OBJECT”; en el nombre del objeto ingrese [HumanResources].[Employee]; en el nombre del Principal ingrese [public] y presione OK para crear y asignar el objeto de auditoría.
Esto permite rastrear las consultas con SELECT que realizan todos los usuarios a la tabla [HumanResources].[Employee].
Presione el botón de la derecha del mouse sobre “EspecificacionAuditoriaDB-ConsultasTablaEmpleado” para habilitar la especificación a través de la opción: “Enable Database Audit Specification”
Finalmente debe habilitar el objeto de auditoría presionando el botón de la derecha del mouse sobre “AuditarConsultasTablaEmpleado” para habilitar la auditoria a través de la opción Enable Audit como se muestra en la siguiente figura.
Si desea crear una especificación de auditoría a nivel de base de datos, a través de T-SQL, lo puede hacer utilizando el comando CREATE DATABASE AUDIT SPECITICATION. La siguiente consulta crea la especificación de auditoría “EspecificacionAuditoriaDB-ConsultasTablaEmpleado”. Esta operación fue realizada anteriormente a través de SSMS.
CREATE DATABASE AUDIT SPECIFICATION [DatabaseAuditSpec-EmployeesTable]
FOR SERVER AUDIT [Audit-EmployeeQueries]
ADD (SELECT ON OBJECT::[HumanResources].[Employee] BY [public])
WITH (STATE = ON)
Visualizar los registros de auditoría
Los registros de auditoría pueden ser accedidos a través la opción “View Audit Logs” o a través de la bitácora de eventos de aplicaciones o de seguridad, dependiendo de dónde se especificó que se almacenaría la auditoría.
Los resultados pueden ser filtrados o inclusive hasta exportados en los siguientes formatos: log, csv y txt
Conclusión
La auditoría en SQL 2008 Enterprise es muy poderosa y flexible ya que permite crear auditorías a nivel de servidor o a nivel de base de datos. La configuración es sencilla ya que solo se requiere especificar donde se almacenará la auditoría (en un archivo, la bitácora de eventos de aplicaciones o la bitácora de eventos de seguridad), que objeto se desea auditar (Base de datos, Esquema, Tablas, Funciones, Procedimientos Almacenados o Vistas) y para cual Principal (entidades que pueden solicitar recursos de SQL Server).
Everyone that Works with SQL Server have needed to move a SQL database from one Instance to another in some point in their live, and probably has needed to deal with tapes, CDs or another media to copy the databases when it’s not possible to do it through the network. The files will most probably be placed on a SQL instance using a RESTORE operation or attaching the files (sp_attach_db).
There are some specific circumstances on which you don’t want a database to be modified. You can try to do this by removing the write permissions on the tables but this can be overcome by a sysadmin login. However there is a way to move the data while been protected, this can be done by using removable databases, this databases are mostly read databases that normally have historical data that it’s not going to be change,
When you create a removable database on SQL Server three types of file are created:
The log file and the file that contain the system tables need to be placed on a read/write unit.
Remember that a database could be expended on more than one storage unit, all this unit should be available when this database are online, so if a database needs 2 DVDs, the server would need to have to DVD Drives and have the to medias inserted,
Create a Removable Database
The process to create a removable database differs from the standard process, you should not use the CREATE DATABASE syntax, instead you should use a store procedure named sp_create_removable, and you will need to be part of the sysadmin server role to execute it.
sp_create_removable [ @dbname = ] 'dbname' , [ @syslogical = ] 'syslogical' , [ @sysphysical = ] 'sysphysical' , [ @syssize = ] syssize , [ @loglogical = ] 'loglogical' , [ @logphysical = ] 'logphysical' , [ @logsize = ] logsize , [ @datalogical1 = ] 'datalogical1' , [ @dataphysical1 = ] 'dataphysical1' , [ @datasize1 = ] datasize1 , [ @datalogical16 = ] 'datalogical16' , [ @dataphysical16 = ] 'dataphysical16' , [ @datasize16 = ] datasize16 ]
The @...16 parameters are used when the database use more tan one media (with a maximum of 16)
Example:
sp_create_removable 'BD_Removible',
'Rem_Sys', 'X:\DATA\remsys.mdf', 2,
'Rem_Log', ' X:\DATA \remlog.ldf', 2,
'Rem_Data', ' X:\DATA \remdata.ndf', 50
With this we created a database named BD_Removible (this is what you’ll see on management studio) y the files the comprise it are: system tables (2M), log file (2MB) and data file (50MB).
Once the database is created, you can use it as a regular database, create tables, reference, users and load the data.
When the database is ready to be copied to a media for its distribution, you need to use the store procedure sp_certify_removable. It works consist on update the statistics, check for possible problems, mask the data file-groups as read only and set the database as offline
Syntax:
sp_certify_removable [ @dbname = ] 'dbname' [ , [ @autofix = ] 'auto' ]
The System Administrator (SA) should be the owner of the Database and all the objects in it; this is because the SA will exist on all SQL installations and it will be used to the post administration and manipulation of rights, this is why it’s convenient to execute the store procedure with the autofix parameter for it to make the recommended changes. If you don’t use it any problem will stop the process and report the error.
sp_certify_removable BD_Removible, AUTO
If the store procedure runs without problems, the database will be put on an offline state.
Distributing the Removable database
The process is simple; you need to copy the files that compose the database to the media you are using to distribute it. To put online this Database you will need to attach it to the Servers (sp_attach_db or SQL Server Management Studio). You will need to have all the removable media where the files are, you only need to do this on time, now you just put it online or offline.
Remember that the log file and the system tables need to be copied to read/write unit, and you need to remove the read-only attribute.
The sp_certify_removable y sp_atach_db store procedures are mark on SQL Server 2008 as deprecated and will be discontinued on future releases, but thi could be useful for some situations on versions from SQL Server 7.0 to SQl Server 2008.
Saludos Comunidad,
Entregando para ustedes un resumen simple del proceso de migración a SharePoint 2010 desde una granja de MOSS 2007, debido a que muchos usuarios de SharePoint se encuentran en este proceso y de pronto leer tanta documentación es un poco complicado por el tiempo que consume la operación diaria, espero les sea de utilidad:
Partiendo del diagrama abajo mostrado resumiremos las actividades propias de la migración:
Aprendizaje:
- Determinar cuáles son los requerimientos para la migración, por ejemplo tener instalado Service Pack 2 para SharePoint Technologies
- Preupgradecheck para determinar cuáles pueden ser los posibles problemas que pudiéramos enfrentar (psconfig -cmd preupgradecheck, solo disponible en SP2)
- Que método de migración escogeremos, Inplace, DB Attach o Hybrid (http://technet.microsoft.com/en-us/library/cc263447.aspx)? Tengo los recursos para realizar un Hybrid y minimizar el tiempo de la migración?
- Identificar problemas comunes en el proceso de migración como el ambiente nuevo de SharePoint 2010 no esta preparado correctamente o bien no hay un Capacity Planning.
- Formas soportadas para la migración:
Preparación:
- Inventario completo: Customizaciones (Master Page, Temas), Definiciones de Sitios, Plantillas, Paquetes de Soluciones (wsp), Codigo personalizado (Web.Config), SPSFarmReport (http://spsfarmreport.codeplex.com/ - Mini Inventario)
- Las personalizaciones deben ser probadas y aprobadas en un ambiente de SP2010 que no será el de producción
- La migración contempla reestructuración de Sitios, Colecciones de Sitios, Aplicaciones Web, Listas, Bibliotecas de documentos?
- Se usan web parts de terceros que no están soportadas en SP2010, hay elementos Flash? Si fuera el caso se requiere soporte para las web parts y convertir los objetos Flash a Silverlight (Usar herramientas de terceros es una opción). Revisar también (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.silverlightwebpart(office.14).aspx)
- Generar plan de capacidades (http://technet.microsoft.com/en-us/library/ff758645.aspx) para la nueva granja de SharePoint 2010, que servicios se brindaran y cuales deberán permanecer apagados
Pruebas:
Una vez determinado lo anterior y revisados cada uno de los elementos que componen la granja actual es necesario comenzar la fase de pruebas
- Construir una granja de SharePoint 2010 de pruebas y utilizar bases de datos de producción para realizar las pruebas
- Evaluar técnicas de migración, por ejemplo es necesario usar Central Administration para montar las bases de datos o es preferible PowerShell, ambas alternativas son útiles, pero es preferible usar PowerShell
- Usar Test-SPContentDatabase (http://technet.microsoft.com/en-us/library/ff607941.aspx) para validar que las bases de datos de contenido pueden ser migradas exitosamente y no existen elementos no instalados en la nueva granja de SharePoint 2010
- Adjuntar las bases de datos utilizando Visual Upgrade (-updateuserexperience / http://technet.microsoft.com/en-us/library/ff607813.aspx / http://technet.microsoft.com/en-us/library/ff607581.aspx)
Implementación
Habiendo superado todos los pasos anteriores entonces se habrá de crearla nueva granja de SharePoint 2010 que será la definitiva
- Basado en el plan de capacidades previo: generar la nueva topología y arquitectura de SharePoint 2010, servidores virtuales o físicos, si son virtuales revisar el modelo de virtualización para SharePoint 2010 (http://technet.microsoft.com/en-us/sharepoint/ff602849.aspx; http://technet.microsoft.com/en-us/library/ff621103.aspx)identificando que roles pueden ser virtualizados y cuales no es recomendado
- Instalar e implementar todas las customizaciones previamente identificadas
- Una vez que se determinaron los posibles problemas, el tiempo de baja del servicio podrá ser reducido, es posible utilizar AAM Redirection en conjunción con READ-ONLY para las bases de datos (http://technet.microsoft.com/en-us/library/ee720448.aspx / http://technet.microsoft.com/en-us/library/dd793608(office.12).aspx)
- Monitorear el proceso de migración puede llegar a ser extenuante, por lo que se sugiere establecer un grupo de monitoreo para la migración donde se asignen tareas especificas
Validación
Al final es importante revisar
- Logs de migración y ULS
- Revisar cada elemento mediante la interface gráfica para garantizar que todo esta OK
- Validar que la información migrada es efectivamente la información que existía en la granja de SharePoint 2007
Suerte
Hey SharePoint community,
Once more writting for you a new post about SharePoint 2010 upgrade and migration, since many of our customers are in the middle of this process and several cuestions come up about it, I wrote a summary of the entire process and some additional information you should be aware of, hope this help you in your migration process.
Starting with the diagram below I'll make a summary of the migration activities:
Learn:
- Determine which ones are the pre-requisites for a SharePoint 2010 migration, for example you must have SharePoint Products and Technologies 2007 Service Pack 2 installed
- Preupgradecheck tool to identify possible issues during migration (psconfig -cmd preupgradecheck, ONLY available in SP2)
- Which approach we will choose, Inplace, DB Attach o Hybrid (http://technet.microsoft.com/en-us/library/cc263447.aspx)? Do I have the hardware or vitual resources to pick Hybrid and minimize downtime?
- Identify common issues in a migration process, for example the new SharePoint 2010 infrastructure is ready for a migration, did I do a Capacity Planning?
- Supported upgrade paths
Prepare:
- Full inventory: Customizations (Master Page, Theme), Site definitios, Templates, Solution packages (wsp), Custom code (Web.Config, GAC. BIN), SPSFarmReport (http://spsfarmreport.codeplex.com/ - small inventory)
- Customization must be tested and approved in a SharePoint 2010 test farm
- Does the migration includes Site Collection, sites, web applications, lists, document library re-organization? Is this a good time to do it?
- Am I using third-party web parts, are they supported in SP 2010, Do I have flash? If I have one or both of them, ask for support to your web part vendors or convert your flahs files to silverlight (Using third-party tools to convert flash files is always an option). Take a look at (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.silverlightwebpart(office.14).aspx)
- Create a Capacity plan (http://technet.microsoft.com/en-us/library/ff758645.aspx) for the new SharePoint 2010 farm, which SharePoint 2010 services I will provide in my new farm, which others must be off or not deployed
Test:
Once we covered the last 2 steps and double check every objects that belongs to our new SharePoint 2010 farm, we will need a test phase
- Build a new SharePoint 2010 farm, physical or virtual, but use always REAL data for testing (Content Databases backup/restore)
- Evaluate migration migration techniques, example Do I use Central Administration site to attach content databases or I will use PowerShell, both should work, from my point of view PowerShell is better
- Use Test-SPContentDatabase (http://technet.microsoft.com/en-us/library/ff607941.aspx) in order to make sure that content will be upgraded successfully and there are no customizations missing over the new SharePoint 2010 farm
- Attach content databases using Visual Upgrade (-updateuserexperience / http://technet.microsoft.com/en-us/library/ff607813.aspx / http://technet.microsoft.com/en-us/library/ff607581.aspx)
Implement
Now is time to start the real migration
- Based on the Capacity planning we already defined: create the new SharePoint 2010 topology and architecture, virtual or physical servers, if you will use virtual environment please validate which SharePoint 2010 server roles are recommended to be virtualized (http://technet.microsoft.com/en-us/sharepoint/ff602849.aspx; http://technet.microsoft.com/en-us/library/ff621103.aspx)
- Install and deploy all the identified customizations on the Preparation phase
- Once you met all the possible problems during the migration on test phase, downtime will be minimized, you can use AAM Redirection and READ-ONLY databases (http://technet.microsoft.com/en-us/library/ee720448.aspx / http://technet.microsoft.com/en-us/library/dd793608(office.12).aspx)
- Monitor the whole migration process because this can be completely exhausting, therefore create migration groups in your ITPROs team to complete the process using monitoring schedules
Validate
To finish, review all your work is important
- Upgrade, ULS, Error and Event Viewer logs have to be reviewed
- Check all your content surfing over your Site Collections and sites
- Double checking the information is a must, compare the information in your old MOSS 2007 farm against your new SharePoint 2010 farm
Good luck!!!
This week while I was working on Bolivia, I overheard the security staff discussing about options they can use to audit transactions done on the database tables. I interrupted and asked them if they knew about the SQL Audit configuration on SQL 2008, and they told me they didn’t. So wrote this post.
The first question is: Why do we audit?
Reviewing some audit security books, the authors agree on that having security policies is a critical factor to maintain data secure. Audit will help us to identify what an intruder access in case he succeeded on a security breach.
On SQL 2005 we were oriented to be sure the users only had the specific privilege that they needed to do their jobs and changes can be only made be authorized staff. The tool that we proposed to have some kind of audit was a SQL trace, because it can track changes on the schema, insert update and delete operations and events related to permissions or the creation of new logins.
One of the enhancements on SQL Server 2008 Enterprise is the capacity to audit actions through SQL Server Audit. With this functionality you can track and log automatically the events on the SQL Server or per SQL Database, this is possible using and Audit Object. Will see how to create an Audit, how to create and enable an Audit Specification at the Server and Database level and how to visualize the Audit records.
Create an Audit
An audit object is a collection of one or more activities, or a group of activities that can be track. For example, you can configure and audit object to identify all the failed logins. The events are written on the specified location, it can be store on a file, on the Windows Application Log or the Windows Security Log.
The Audit Object can be created through SQL Server Management Studio (SSMS) or T-SQL. Using SSMS you should click over the New Audit option located on the Audit folder under the Security Tree, as shown here:
On the Create Audit screen you need to introduce the name for the Audit Object, and specify the location. If you choose a file as the location, you will need to specify the file path. Finally click OJ to create the object.
For propose of the example I have created a second audit object with the name “AuditarConsultasTablaEmpleado”. The location is a file on a specific path. Both objects are located on the Audits Folder, as shown on the figure. This audit object is going to be used to track the SELECT transactions executed against the HumanResources.Employee table on the AdventureWorks2008R2 database.
If you want to create an audit object trough T-SQL you can do it using the CREATE SERVER AUDIT comand. The following query creates the object “AuditarConsultasTablaEmpleado”. This was already done using SSMS.
Create and enable an Audit Specification at the Server level
Once that you create the audit object, the following step, is to create the appropriate specifications for the audit. The audit specifications tell the audit object what it needs to track. For the audit object “AuditarLoginsFallidos”, we need to create a specification the looks for failed logins. To accomplish this we can right click on the Server Audit Specifications folder on the security tree.
Provide the audit specification name, like “EspecificacionAuditoriaServidor-LoginsFallidos”. On the Audit option select “AuditarLoginsFallidos”. This will assign the audit specification “EspecificacionAuditoriaServidor-LoginsFallidos” to the audit object “AuditarLoginsFallidos”. Select the type of action to audit: “FAILED_LOGIN_GROUP” and press OK to create and assign the object.
Right click on the “EspecificacionAuditoriaServidor-LoginsFallidos” to enable the specification through the option: “Enable Server Audit Specification”.
Finally you need to enable the audit object by right clicking on the “AuditarLoginsFallidos” to enable the audit object through the Enable Audit option as shown on the figure.
If you want to create an audit specification at the server level trough T-SQL, you can do it using the command CREATE SERVER AUDIT SPECIFICATION. The following statement creates the specification audit “EspecificacionAuditoriaServidor-LoginsFallidos”. This was already done through SSMS.
Create and Enable an Audit specification at the Database level:
To create and enable an audit specification at the Database level you should expand the database, on this example we are using AdventureWorks2008R2, and right click on the “Audit Specifications” under de security tree of the database and select the option “New Database Audit Specification”, them assign a name (for this example we are using the name “EspecificacionAuditoriaDB-ConsultasTablaEmpleado”)
As shown on the figure, select the option “AuditarConsultasTablaEmpleado” on Audit. This will assign the audit specification “EspecificacionAuditoriaDB-ConsultasTablaEmpleado” to the audit object “AuditarConsultasTablaEmpleado”.
Note: The object Class indicate what do you want to audit, the options are: Object, Database or Schema. Select Object to audit Tables, Functions, Store Procedures or Views. The principal name is the entity that can access the SQL Server resources.
For the purpose of the example, use “SELECT” on the type of action to audit; on the object class use “OBJECT”; on the object schema and name use [HumanResources].[Employee]; on the Principal name use [public] an press OK to create and assign the audit object.
This will allow to track the select queries done by all users to the [HumanResources].[Employee] table.
Right click on “EspecificacionAuditoriaDB-ConsultasTablaEmpleado” to enable the audit specification using the option: “Enable Database Audit Specification”
Finally to enable the audit right click on “AuditarConsultasTablaEmpleado” to enable the audit trough the option Enable Audit as shown on the figure.
If you wish to create the audit specification at the database level using T-SQL, you can do it using the command CREATE DATABASE AUDIT SPECIFICATION. The following query creates the specification audit “EspecificacionAuditoriaDB-ConsultasTablaEmpleado”. This was already done through SSMS.
Visualizing the Audit Logs
The audit logs can be Access through the “View Audit Logs” option or through the Application or Security event log, depending where you specified to store the audit.
Results can be filter or exported on the following formats: log, csv and txt
Conclusion
The SQL Server 2008 Enterprise Audit options are pretty powerful and flexible; this will allow you to create audits at the server or database level. The configuration is pretty simple because you only need to specify where the audit is going to be stored (on a file, Windows Application Log or Security Log), what object you want to audit (Server, Database, Table, Schema, Function, Store Procedures and Views) and for which Principal (entities that can access the SQL Server resources).
Todos los que trabajan con SQL Server han necesitado en algún momento, y en mayor o menor medida, trasladar datos de un servidor a otro. Todos han tenido entonces que lidiar con cintas, DVD u otro tipo de media, cuando no es posible copiar los archivos por una conexión de red. Estos luego son colocados en el Servidor SQL mediante una operación de restauración (RESTORE) o de acoplamiento de la BD (sp_attach_db).
Hay situaciones particulares en las cuales se desea que una base de datos no sea modificada mientras se hace el proceso de mudanza. Si bien es posible quitar los permisos de escritura en las tablas la base de datos no está protegida totalmente, ya que alguien con permisos de sysadmin podrá alterar los datos. Sin embargo existe una forma de distribuir los datos de manera protegida mediante la creación de bases de datos removibles. Estas bases son generalmente solo lectura y normalmente son datos históricos que no sufrirán operaciones de actualización. Esta opción está disponible desde SQL Server 7.0 hasta SQL Server 2008.
Cuando se genera una base de datos removible SQL Server se crearan tres tipos de archivos:
El archivo de log y el archivo de las tablas del sistema se deben colocar en una unidad en la que se pueda escribir.
Es necesario aclarar que los archivos de data de una base de datos puede ocupar más de una media removible (CD, DVD) en forma simultánea, todas ellas deberán estar disponibles a la vez cuando esa base esté operativa. Es decir, si los archivos de data de una base de datos necesita 2 DVDs, se necesitara tener 2 unidades de DVDs y ambos DVDs insertados al momento de usarla.
Crear una BD removible:
La creación de una base de datos de este tipo es diferente al proceso standard. No se deberá utilizar la sintaxis de CREATE DATABASE sino un stored procedure llamado sp_create_removable. solo los miembros de sysadmin podrán ejecutar esto. Este stored procedure tiene unos parámetros que se detallan a continuación:
Los parámetros @....16 se utilizan cuando la base de datos ocupa más de una media (hasta un máximo de 16).
Un ejemplo de esta instrucción:
'Rem_Log',' X:\DATA \remlog.ldf', 2,
Con el comando anterior creamos una base de datos llamada BD_Removible (es el nombre que se verá en el Management Studio) y sus archivos componentes que son: tablas de sistema (2 MB), archivo de log (2 MB) y archivo de datos (50 MB).
Una vez hecho esto, se procede a manipularla como una base de datos común y corriente. Se crean sus tablas, sus referencias, sus usuarios, se cargan los datos, etc. Es decir, se la deja lista para usarla.
Cuando la base de datos está lista para ser copiada a una media para su distribución, se deberá usar el stored procedure sp_certify_removable. El trabajo que realiza consiste en actualizar las estadísticas de las tablas, chequear posibles problemas, marcar los data file-groups como de solo-lectura (de forma tal que se puedan copiar a un soporte de solo-lectura) y setear la base como ‘off-line’.
La sintaxis completa es:
El System Administrator (SA) deberá ser el owner de la base de datos y de todos los objetos que hubiere en ella. Esto es así dado que el SA existirá en todas las instalaciones de SQL Server y, es con este usuario, que se hará la posterior administración y manipulación de derechos. Por ello, es conveniente ejecutar este stored procedure para que el segundo parámetro (@AutoFix = ‘AUTO’) se encargue de todo esto. Si no se especifica esto, hará el proceso igual, pero si encuentra algún inconveniente lo reportará y detendrá el proceso.
Ejemplo:
De no estar ningún usuario conectado y no generarse problemas, la base de datos quedará en estado ‘off-line’ para ser copiada.
Distribuir la Base de Datos removible
El proceso ahora es sencillo: se deberán copiar los archivos componentes de la base de datos a la media que usaras para distribuirla. Cuando se necesite poner en producción la base de datos removible se deberá acoplar la misma al servidor (sp_attach_db o utilizar el Management Studio). Se deberán insertar todas las medias usadas por la base de datos. Esto se hace por única vez. De aquí en adelante se la pone ‘on-line’ u ‘off-line’ para poder usarla o no.
Es conveniente aclarar que el archivo de log y el de tablas del sistema se deberán copiar a una unidad de lectura y escritura y quitarle a los archivos el atributo de read-only.
El stored procedures sp_certify_removabley sp_atach_db está marcados en SQL Server 2008 como deprecados y serán descontinuados en futuras, pero esta capacidad está disponible desde SQL Server 7.0 hasta SQL Server 2008 y puede ser útil en diferentes situaciones.
“Las opiniones e ideas expresadas en este blog son las de los Autores y no necesariamente declaran o reflejan la opinión de Microsoft”. Este material tambien lo podras acceder en http://blogs.technet.com/b/sql_pfe_latam/