Dec 7, 2009

SCCM 2007 SQL Server Cluster Issues


How to Configure an SPN for SQL Server Site Database Servers:
http://technet.microsoft.com/en-us/library/bb735885.aspx
Kerberos Event ID: 529 is logged when you use a local user account to verify security access or group membership on a Windows Server 2003-based Kerberos client:
http://support.microsoft.com/kb/890477
Kerberos Authentication for SQL Cluster:
http://technet.microsoft.com/en-us/library/cc738070.aspx
How to make sure that you are using Kerberos authentication when you create a remote connection to an instance of SQL Server 2005:
http://support.microsoft.com/default.aspx/kb/909801
Allow a User to be trusted for delegation:
http://technet.microsoft.com/en-us/library/cc739474.aspx
Kerberos Authentication - Tools and Settings:
http://technet.microsoft.com/en-us/library/cc738673.aspx
SQL Protocols:
http://blogs.msdn.com/sql_protocols/archive/2006/12/02/understanding-kerberos-and-ntlm-authentication-in-sql-server-connections.aspx
RTFM - Edited for brevity, pivotal info could be omitted : )

You can use Kerberos authentication with Microsoft SQL Server 2005 stand-alone instances or with failover cluster instances running on a virtual server The following section describes how to connect to a server that is running Microsoft Internet Information Services (IIS) to make a Kerberos connection to a server that is running SQL Server


Prerequisites
Before you perform the Setup procedure, download the Kerbtray.
SQL Server only uses Kerberos if the client uses the TCP/IP protocol to connect to SQL Server. Connect to a server that is running Microsoft Internet Information Services and make a Kerberos connection to SQL Server 2005
Step 1: Configure the domain controller
In Active Directory Users and Computers: Trust this computer for delegation
. If the computer that is running SQL Server is what appears to be the last computer contacted but that computer has a linked server, it must also granted delegation permissions. If it is not the last computer in the chain, all the computers that are intermediaries must be trusted for delegation.
Grant delegation permission to the SQL Server service account domain user account. You must have a domain user account for clustered SQL Server installations (this step is not required for computers that are running SQL Server that are using a local system account):
In the Users folder, right-click the user account, and then click Properties.
In the user account properties dialog box, click the Account tab.
Under Account Options, click to select the Account is Trusted for Delegation check box. Make sure that the Account is sensitive and cannot be delegated check box is cleared for this account.

Step 2: Configure the IIS services server
Replace the default Web site Wwwroot files with the sample .asp files. To create the sample .asp files, use the code that is provided in the "ASP test script for SQL Server data retrieval" section.
Add the file to the Wwwroot folder. To do so, use the sample code in the "ASP Test Script for SQL Server Data Retrieval" section. Save the file as Default.asp.
Reconfigure the Web server to use Integrated Windows Authentication only:
Right-click the default Web server, and then click the Security folder.
In the Security folder, make the correct changes, and then click to clear anonymous access.
From a command prompt, run this command:cscript C:\Inetpub\Adminscripts\adsutil.vbs get w3svc/NTAuthenticationProvidersIf Negotiate is enabled, the following is returned: NTAuthenticationProviders : (STRING) Negotiate,NTLMFor additional information on configuring IIS to support both Kerberos and NTLM authentication, see the Knowledge Base article, "How to Configure IIS to Support Both Kerberos and NTLM Authentication."
Note:
You must install Microsoft Data Access (MDAC) 2.8 SP1, or later, on the IIS Services server. To do so (and to make the tools available for testing).

Verify that the HKLM\SW\MS\MSSQLSERVER\Client\DSQUERY value is present in the registry. If the value is not displayed, add it as DSQUERY:Reg_SZ:DBNETLIB.
Use the Kerbtray.exe utility to verify that Kerberos tickets were received from the domain controller and host:


Right-click the Kerbtray icon in the notification area, and then click purge tickets.Wait for the green Kerbtray icon to change from green to yellow. As soon as this occurs, open a command prompt window and run this command:net session* /dThis will drop the existing sessions, and force a new session to be established and a Kerberos ticket received.


Step 3: Create an SPN for SQL Server
If you have multiple instances of SQL Server on a computer, you must configure a Server Principal Name (SPN) for each instance of SQL Server because each instance of SQL Server uses a unique TCP-IP port.
Important:
If the SQL Server service runs under a domain user account, you must manually configure an SPN. To do so, follow these steps.
Note the domain user account that the instance of SQL Server is running under. In the following examples, this account is named . You must have the fully qualified domain name (FQDN) of the computer that is running SQL Server. To determine the FQDN of the computer that is running SQL Server, use the ping utility. To do so, follow these steps:
Ping the computer that is running SQL Server to determine its IP address:



C:\>ping MySQLServer


Pinging MySQLServer.MyDomain.com [10.10.10.10] with 32 bytes of data:


Reply from 10.10.10.10: bytes=32 time=1ms TTL=128
Use ping -a to perform a reverse lookup of the IP address to make sure that the FQDN is correctly returned by the Domain Name System (DNS) protocol:



C:\>ping -a 10.10.10.10Pinging MySQLServer.MyDomain.com [10.10.10.10] with 32 bytes of data:


Reply from 10.10.10.10: bytes=32 time<1ms ttl="128">
Ping the virtual SQL Server name to obtain the IP address, and then run ping -a to make sure that the FQDN is correctly returned by the DNS.
Note:
If you are using SQL Server failover clustering, you use the FQDN for the virtual SQL Server. Note the exact TCP/IP port that the instance of SQL Server uses. To determine this information, open SQL Server Configuration Manager on the computer that is running SQL Server, click the instance of SQL Server, and then view the properties for the TCP/IP protocol (default port).
You must be a member of the Domain Administrators group to run the SETSPN command.
If you are using SQL Server failover clustering, run the following SETSPN command:



setspn -A MSSQLSvc/


For example, if MySQLServer.MyDomain.com is running under the domain user account SQLSVC, where MySQLServer.MyDomain.com is the name of the instance of SQL Server 2005 that is clustered, run the following command:


setspn -A MSSQLSvc/MySQLServer.MyDomain.com SQLSVC
For both clustered and non-clustered computers that are running SQL Server, run the following SETSPN command to register an SPN for the port that the computer that is running SQL Server is using:


setspn -A MSSQLSvc/:


Run SETSPN -L to list all the SPNs that are registered to the domain user account that the instance of SQL Server is running under
If you are using SQL Server failover clustering, you must register a SPN without the port number and another SPN with the port number. With a typical, non-clustered computer that is running SQL Server, you only have to register the SPN with the port number. However, if you have an additional SPN without the port number, it will not cause any problems with non-clustered computers.
Step 4: Configure the client computers
For each client that will connect, verify that Microsoft Internet Explorer is configured to use Windows Authentication:
In Internet Explorer, on the Tools menu, click Internet Options.
Click the Advanced tab.Under Security, click to select Enable Integrated Windows Authentication (requires restart), and then click OK.
Step 5: Test the configuration
For each computer that is involved:
Log on to the computer, and then use Kerbtray.exe to verify that the computer can obtain a valid Kerberos ticket from the domain controller.
Use Kerbtray.exe to remove all tickets on the computer.
Create and connect to the Web page that returns the SQL Server data.
Note:
Replace SQLSERVERNAME with the name of the computer that is running SQL Server:
If data is returned, this page displays the authentication type Negotiate, and the SQL Server data for the result of the sp_helpdb stored procedure that should return a list of the databases on the server that is being connecting to through the .ASP page.
If you have auditing turned on in SQL Server, in the Application log you will see that the connection is "trusted".

Инвентаризация общих папок


Чтобы получить отчёт по общим папкам на компьютерах домена, нужно просто найти в файле \Microsoft Configuration Manager\inboxes\clifiles.src\hinv\sms_def.mof найти строку SMS_Group_Name ("Shares") и заменить FALSE на TRUE:




[ SMS_Report (TRUE),
SMS_Group_Name ("Shares"),
SMS_Class_ID ("MICROSOFT|SHARE|1.0") ]

class Win32_Share : SMS_Class_Template
{
[SMS_Report (TRUE), SMS_Units("DecimalString")]
uint32 AccessMask;
[SMS_Report (TRUE) ]
boolean AllowMaximum;
[SMS_Report (TRUE) ]
string Caption;
[SMS_Report (TRUE) ]
string Description;
[SMS_Report (TRUE) ]
datetime InstallDate;
[SMS_Report (TRUE) ]
uint32 MaximumAllowed;
[SMS_Report (TRUE), key]
string Name;
[SMS_Report (TRUE) ]
string Path;
[SMS_Report (TRUE) ]
string Status;
[SMS_Report (TRUE), SMS_Units("DecimalString")]
uint32 Type;
};


После перекомпилирования файла и прохождения цикла инвентаризации на клиентах, в базе SCCM появится таблица v_GS_SHARE.

Затем можно строить запрос:

SELECT TOP (100) PERCENT dbo.v_R_System.Netbios_Name0 AS Компьютер, dbo.v_GS_SHARE.Name0 AS [Имя папки], dbo.v_GS_SHARE.Path0 AS Путь
FROM dbo.v_R_System INNER JOIN
dbo.v_GS_SHARE ON dbo.v_R_System.ResourceID = dbo.v_GS_SHARE.ResourceID
WHERE (dbo.v_GS_SHARE.Name0 <> 'C$') AND (dbo.v_GS_SHARE.Name0 <> 'D$') AND (dbo.v_GS_SHARE.Name0 <> 'E$') AND (dbo.v_GS_SHARE.Name0 <> 'F$') AND
(dbo.v_GS_SHARE.Name0 <> 'G$') AND (dbo.v_GS_SHARE.Name0 <> 'ADMIN$') AND (dbo.v_GS_SHARE.Type0 <> '1') AND (dbo.v_GS_SHARE.Name0 <> 'IPC$') AND
(dbo.v_GS_SHARE.Name0 <> 'print$')
ORDER BY Компьютер

Dec 1, 2009

Second Site Saver


System Center Configuration Manager 2007 is a multitalented animal for distributing software, and with the branch distribution point option you may not need a secondary site server in branch offices

Microsoft’s System Center Configuration Manager 2007 (ConfigMgr) introduces many site server roles. In this article, we look at the branch distribution point.

First, we need to define the term “branch office”. Microsoft defines it as a location with fewer than 10 workstations. When managing clients at remote locations connected via wide area network (WAN) links with Microsoft’s Systems Management Server (SMS), you had a choice of four options:
  • Do nothing Simply let SMS use bandwidth as required. This wasn’t a good choice as the SMS-related traffic would be sent uncompressed and at random times with no control. This could impact other applications and users’ ability to do their job.
  • Use Background Intelligent Transfer Services (BITS) Better than doing nothing, a Group Policy Object (GPO) was defined to control how much bandwidth was used by BITS and during what hours.
  • Install a distribution point at the branch office The benefit of this was that the package content was only sent once across the WAN rather than each time a client requested it. The problem was, an SMS site assumed that any of its site systems were installed on machines with LAN-speed connections to the site server. As a result you had no control over when SMS sent the packages and the traffic was not compressed in any way.
  • Install a secondary site Microsoft’s recommendation whenever you had clients to manage over a WAN. Installing a secondary site allowed the SMS-related traffic to be controlled in terms of the amount of bandwidth used and during which hours. And any traffic sent between SMS sites was compressed to further reduce bandwidth consumption.
Out of all these options, installing a secondary site was typically the best solution for managing branch office clients. However, many companies questioned why in such small locations they needed to go to the expense of installing and managing a secondary site where there wasn’t space to physically secure it or to house local IT support staff.

With ConfigMgr you still have the same four options as you had with SMS, plus a fifth option in the shape of a branch distribution point (BDP).

RAISON D'ETRE
The prime purpose of a BDP is to reduce the need to install a secondary site server in branch office locations. To achieve this, a workstation (or server) can be configured to host the BDP role. The BDP downloads any ConfigMgr packages in a controlled manner and then makes them available to any clients in its location, thus eliminating the need for a secondary site.
At a high level, a BDP functions in the same way as a standard DP but with some key differences, as shown in Table 1. Although it directly communicates with the site server, a BDP isn’t like all other site system roles. The BDP relies on a standard DP to provide its content (Figure 1).

For a standard DP, the Distribution Manager component is responsible for creating the DP and managing its content on an ongoing basis. In the case of a BDP, all Distribution Manager does is to initiate the creation of a policy that tells the BDP it has content to copy. At the next Policy refresh cycle, the BDP connects to a BITS-enabled standard DP in the same ConfigMgr site and initiates a pull via BITS of the relevant package(s).

Second Site Saver 01
Figure 1: Branch distribution point overview

BITS AND BANDWIDTH
It’s important to note that the package files are not compressed before the BDP pulls them from the standard DP (unlike when traffic is sent between ConfigMgr sites); the files are simply pulled using BITS. Even though BITS is used, you have control over when and how much bandwidth is used because a GPO for BITS exists.

Under Computer Configuration | Administrative Templates | Network | Background Intelligent Transfer Service select “Maximum network bandwidth that BITS uses” (for BITS 2.0) or “Maximum network bandwidth for BITS background transfers” (for BITS 3.0). Set the transfer rate value (in kilobits per second) you want BITS to use (10 by default), and the times during which you want this limit to apply (set at 08:00 – 17:00 by default). Limits that apply outside of these hours can also be set (the default being to “Use all available unused bandwidth”).
Table 2 highlights the bandwidth control options available for various package-sending scenarios.

Standard DP vs BDP
Bandwidth Control

WHICH BDP TO USE
It’s important to understand the process clients go through to determine which BDP/DP to use to pull their content from (the process is the same whether it’s a BDP or DP), as this can have serious implications for your design. Once a client receives a policy to inform it to download content, the client sends a content location request to a management point (MP). The MP then runs through various checks before returning a list of available BDPs/DPs to the client.

On receipt of the list, the client first looks at those flagged as “local” (based on the client’s location), giving preference to BDPs/DPs on the same subnet first, then those in the same AD site, and finally any others. If no local BDPs/DPs are available, the client will run through the same process for any remote BDPs/DPs. In all cases, the client will prefer to connect to a BITS-enabled BDP/DP.

Once the client determines which BDP(s)/DP(s) are the best to retrieve the content from, it chooses one at random which gives a degree of load balancing. The client then attempts a connection. If the connection is successful, but the client experiences any transient errors at any time, it will keep retrying the connection for up to eight hours, after which it will move onto the next BDP/DP on the list.

If the connection is unsuccessful, the client tries the next BDP/DP on the list. If there is only one BDP/DP on the list, the client will retry for up to eight hours before it fails.
Any client that is running SMS 2003 SP2 or later that is assigned to a ConfigMgr site can access any BDPs contained within that site. In the same way, any SMS 2003 SP2 or later client that roams to a ConfigMgr site can access any BDPs contained within that site.

WHAT YOU NEED
Once you’ve configured at least one BITS-enabled standard DP in the same ConfigMgr site as that where you want to create the BDP, the machine you wish to become a BDP has to be:
  • A ConfigMgr client The BDP software is integrated into the ConfigMgr client as standard.
  • A member of a domain Although the machine needs to be a member of a domain, it is possible for machines that are not a member to retrieve content from the BDP.
  • Running Windows XP SP2 or a later operating system
  • The BDP doesn’t necessarily have to run a workstation OS and in some cases you may decide you don’t want the limit that these operating systems have of only allowing 10 simultaneous incoming connections. Nominating a machine running a server-class OS such as Windows Server (Standard, Advanced or Enterprise) with SP1 or a later OS is fully supported.
INSTALLATION ISSUES
To install a BDP, first load the ConfigMgr Administrator console. Navigate to System Center Configuration Manager | Site Database | Site Management | | Site Settings. Right-click Site Systems and select New | Server from the Context menu. (Remember a BDP cannot be installed on a server share in the same way a standard DP can.)

Next run through the New Site System Server Wizard to create the BDP. On the System Role Selection page, you need to select the Distribution Point checkbox; there is no checkbox for a BDP. Select the “Enable as a branch distribution point” radio button on the Distribution Point page (Figure 2). On this page you can also set the drive to host the BDP content and to reserve a specific amount of disk space for non-BDP content on the target machine.

Second Site Saver 02
Figure 2: Configuring a branch distribution point

If the “Enable as a branch distribution” radio button is not available (ie greyed out), make sure there is a matching client record for the target machine in the ConfigMgr site database.
Once you’ve installed the BDP, you’ll probably want to determine which clients on which boundaries can use it (see the “How do I Protect a DP?” article on FAQShop for details of how to do this).

Microsoft does not recommend creating a BDP (or DP for that matter) on any Internet-based clients as doing so increases your risk of surface attack.

MANAGEMENT TASKS
Once the BDP is installed and running, the next task is to manage the packages you send to it. (Once installed, a BDP appears under System Status where you can monitor its status.)
Content that can be provisioned (in other words, loaded onto) a BDP is the same as a regular DP (in other words, software distribution packages, patches, Operating System Deployment images and task sequences, and the like).

There are three key ways of actually provisioning the content onto a BDP:

  • Administrator provisioned
  • “On-demand” package distribution
  • Manual content provisioning
Administrator provisioned
This is the typical way content is distributed whereby the ConfigMgr administrator selects the BDP on which the content is to be copied in exactly the same way as for a standard DP:
  • From within the ConfigMgr console go to System Center Configuration Manager | Site Database | Computer Management | Software Distribution | Packages.
  • Right-click on the package you want to distribute to the BDP and select “Manage Distribution Points” to run the Manage Distribution Points wizard.
  • Choose the target BDP.
Once a BDP is added to a package, a policy is sent to the BDP telling it to download the content. During the next policy update cycle (60 minutes by default), the BDP retrieves the policy and automatically starts downloading the package from a BITS-enabled standard DP in the same ConfigMgr site.

If you have lots of packages you need to send to the BDP, rather than having to go to each package to manually add the BDP, from within the ConfigMgr console go to System Center Configuration Manager | Site Database | Computer Management | Software Distribution. Right-click Packages. Select Copy Packages which will start the Copy Packages Wizard. The wizard allows you to choose which DP/BDP to copy to and the package(s) you want to copy.

Note that by default the Copy Packages functionality only copies the node type that you right-clicked, so if you right-clicked on an item under the Software Distribution node, you can only copy software distribution packages. If you want to copy other package types, such as Software Updates or Operating System Deployment, you need to right-click on the relevant folder in the ConfigMgr console and run the wizard from there.

“On-demand” package distribution
This is a new ConfigMgr content provisioning method that applies to BDPs only. Rather than having to send all of your packages to all of your DPs just in case a client needs it, you can now decide not to distribute packages to your BDPs; in other words, you don’t add the BDP to the list of DPs in the relevant package(s).

The first time a client connects to a BDP and requests a package that has not been distributed to that BDP, the BDP contacts a standard DP in the same ConfigMgr site and automatically starts downloading the package (the process is almost the same as when you add a BDP to the list of DPs for a package). “On demand” package distribution works through the properties of the package and is controlled using package creation or post-package creation.

With package creation, at the time you create a package using the New Package wizard, you select the “Make this package available on protected distribution points when requested by clients within the protected boundaries” checkbox on the Distribution Settings page (rather than the default option, “Branch distribution points automatically download this package when they receive the advertisement”).

You use post-package creation if you add a new BDP but decide you don’t want to automatically host the content there. In this case you need to go to the Properties of the package and click the Distribution Settings tab. From there make sure you’ve clicked both the radio button titled “Branch distribution points automatically download this package when they receive the advertisement” and the checkbox titled “Make this package available on protected distribution points when requested by clients within the protected boundaries”.

Manual content provisioning
With this method, rather than copying content across the WAN to get it to the BDP, you might decide to manually copy it there. To do this, first ensure you have configured the target machine as a BDP (otherwise the rest of this process will fail).

Create the SMSPKG $ directory and share it on the BDP. For example, if you want the BDP content to be hosted on the D: drive of the target machine you’d create and share the SMSPKGD$ directory.

Copy the Packages from the source DP to the SMSPKG $ directory on the BDP (for example, copy them to CD, transfer the CD to the BDP’s location and load them into the same directory on the BDP).

On the BDP go to Control Panel | Configuration Manager and click on the Actions tab. Select the “Branch Distribution Maintenance Task” then click the Initiate Action button. This task verifies that the pre-staged package is valid and then updates the list of DPs for the package on the source site server to include the BDP.

THE RESTORATION
The contents of a BDP are not backed up automatically by ConfigMgr (which applies to standard DPs as well). To back up a BDP, first disconnect any users from the SMSPKG$ share. Then back it and its contents up to backup media.
To restore a BDP:

  • Reinstall the ConfigMgr client and reconfigure the machine as a BDP if it has been rebuilt.
  • Create the SMSPKG $ directory and share it.
  • Restore the packages to the SMSPKG$ directory.
  • Go to Control Panel | Configuration Manager and click the Actions tab.
  • Select the “Branch Distribution Maintenance Task” then click the Initiate Action button. This task verifies that the restored packages are valid, re-downloading any that aren’t.
FACTORS TO CONSIDER
As with anything ConfigMgr-related, whether you actually implement BDPs in your environment depends on a number of things that are unique to each environment and need to be considered carefully.

If the current level of service you offer to your branch offices is acceptable, maybe you don’t need to install a BDP. You need to weigh up the cost of procuring, installing and managing a BDP versus the cost of simply upgrading the WAN link. If there are other applications using the WAN link, maybe the owners of those apps would be open to sharing the cost of upgrading the WAN link for mutual benefit versus you installing a BDP.
Although installing a BDP may negate the need to install a secondary site, a BDP does not give you as much bandwidth control as a secondary site does. Sure, you can limit the amount of data and times during which data is copied from the standard DP to the BDP using a GPO, but you lose the benefit of content being compressed before it is sent which you have when data is sent between ConfigMgr sites.

Loss of control
Also bear in mind that if you decide to install one or more BDPs in a location with a couple of hundred machines, you only have control over the software distribution traffic. Again, what you lose by not having a secondary site is compression and the ability to control all ConfigMgr-related traffic, not just software distribution-related (for example, all the data that needs to be sent up the hierarchy from the client to its site server, such as inventory data, status messages, etc). OK, most of this traffic is small in nature, but when it’s multiplied over a couple of hundred machines and then sent totally randomly across a saturated WAN link, it could present problems.

Note also that protected boundaries only control which clients can access DP/BDP content; they play no part in determining which standard DP a BDP will obtain its content from.
BDPs cannot be installed on server shares like regular DPs, although when you create the BDP you do have the option (which I’d strongly recommend you take advantage of), of specifying which drive should be used to host the BDP and its content.

Choose wisely
Remember also that workstation operating systems such as XP can only accept 10 simultaneous incoming connections. If you have more than 10 machines at a BDP location that will need to simultaneously download content, either consider installing more than one BDP or use a server OS on the BDP to overcome this limit.

Ensure you have sufficient disk space to accommodate your packages. Disk space is typically more abundant (and easier to expand) on a server than a workstation.

DO'S AND DONT'S
Don’t install the BDP on a laptop. It may sound obvious, but there is little point installing a BDP on a machine that is likely to go off-site from the branch office and impact software distribution there.

Don’t install BDPs on Internet-based clients. Although you can do this, Microsoft strongly advises against it as it greatly increases your attack surface. Only create BDPs on machines inside your intranet or perimeter network.
If you decide to host the BDP on a user’s workstation make sure they are aware that if they switch off their machine it could affect their colleagues’ ability to receive content. This could be disastrous if you have service level agreements in place for distributing software.

BDP content (like standard DP content) is not encrypted. If the user has local admin rights, they can access the BDP content directly, which is not desirable.

You might want to consider creating more than one BDP at each location to provide failover in the event of a BDP failing. Distribution
Although “on-demand” package distribution may sound wonderful, the biggest drawback is that the user will need to wait for the package to be downloaded to the BDP before they can install it. This may be fine for small packages/patches, but if the package is something large or urgent, there will be a delay while it is downloaded. (Also bear in mind that if the package request is made during the day, you may not want a large amount of network traffic traversing your WAN links, or because of limits you’ve set for BITS a download during restricted hours could take significantly longer than one during unrestricted hours.)
Remember also:
  • On-demand provisioning is controlled on a per-package basis.
  • For on-demand provisioning to work, the BDP needs to be protected and the target client needs to be within the protected boundaries of the BDP. If either of these isn’t true, it won’t work.
  • If you have multiple BDPs in the same protected boundary, when a client requests a package that has been configured for on-demand provisioning, it will be downloaded to all BDPs in that boundary, not just the BDP the requesting client has contacted. Again this could have a severe impact on your WAN link.
If you decide to host a BDP at a location, I’d recommend investing in a dedicated machine for this purpose that is physically secured as if it were a server to avoid as many of these potential issues as possible.

IN SUMMARY
With the new Branch Distribution Point Site System role in ConfigMgr 2007, you no longer need to either install a secondary site or have to rely on other methods to limit the impact of your clients on your WAN when it comes to software distribution.

It is now possible and supported to configure a workstation machine in a remote location and use this to host content to service local ConfigMgr client needs.
System Center Configuration Manager is an ever-increasing beast in terms of both functionality and complexity. However, with an understanding of how BDPs work and the potential issue and gotchas they present, BDPs can be a valuable addition to any ConfigMgr solution.

FURTHER READING
Configuration Manager and Content Location (Package Source Files) http://technet.microsoft.com/en-us/library/bb632366.aspx

How do I protect a DP? http://www.faqshop.com/configmgr2007/instconfig/idps/how%20protect%20dp.htm

Why is the “Enable as a branch distribution point” checkbox greyed out/unavailable? http://www.faqshop.com/configmgr2007/trobshoot/bdps/enable%20as%20bdp%20unavail.htm

How to configure on-demand package distribution to a BDP http://technet.microsoft.com/en-us/library/bb632933.aspx

How to prestage packages on a branch distribution point http://technet.microsoft.com/en-us/library/bb681046.aspx

Усовершенствования Windows Server 2008 R2: сервер DHCP


Сервер DHCP (Dynamic Host Configuration Protocol) предоставляет одну из наиболее востребованных функций в IP-сетях любого масштаба и развитости – функцию предоставления клиентам параметров конфигурации протокола IP и других параметров, необходимых клиентам для обнаружения и взаимодействия с сетевыми службами. Новая версия операционной системы Windows Server 2008 R2 привносит в свою реализацию сервера DHCP не только некоторые улучшения функционала ранних версий, но, что удивительно, и новый функционал.




Производительность.
Служба DHCP в Windows Server использует Microsoft Extensible Storage Engine (ESE, также известный как база данных JET) в качестве посредника хранения данных (конфигурации, списков резервирования, журналов аренды и пр.). Одной из возможностей ESE является возможность кэширования, позволяющая размещать в оперативную память избранные страницы или всю базу данных целиком, что существенно уменьшает время выборки и нивелирует зависимость между обращением к файлам базы и очереди к накопителю данных. Служба DHCP в Windows Server 2008 R2 использует эту возможность по умолчанию, задействовав режим «autotune cache», который указывает ESE, по возможности, загружать как можно больше страниц базы данных DHCP в оперативную память.
Такой механизм работы вызывает увеличение потребления оперативной памяти процессом, ассоциированным с сервером DHCP, например, в моменты обращения к журналу аренды с целью поиска соответствия или создания в этом журнале новой записи. В ситуации, когда сервер DHCP обслуживает запросы сотен клиентов в минуту и обладает журналом аренды для тысяч клиентов[i], размер оперативной памяти, выделяемой под эти нужды, может достигать сотен мегабайт. С целью предотвращения излишне агрессивного использования ресурса оперативной памяти, предусмотрена возможность определения максимально допустимого размера (в МБ), выделяемого для кэширования базы данных сервера DHCP: в разделе системного реестра, хранящего параметры службы DHCP[ii], можно задать параметр «JetDatabaseMaxCacheSize» (тип DWORD).
MAC-фильтрация.
Windows Server 2008 R2 привносит новый функционал в службу DHCP – фильтрацию клиентов по MAC адресам (MAC Based Filtering). Этот функционал предоставляет дополнительную возможность администраторам контролировать распределение адресного пространства по запросу от клиентов на основе протокола DHCP без необходимости обновления коммутирующего или клиентского оборудования.
В основе механизма MAC-фильтрации лежат разрешающий и запрещающий списки соответствия MAC адресов («issuance» и «denial» списки). Список может содержать как полностью определенный MAC адрес (конкретного сетевого адаптера), так и маску MAC адреса[iii], что позволяет управлять разрешениями обобщенно.
Как это работает?
Сервер DHCP обращается к спискам MAC фильтра при получении им сообщений (инспекции подвержены сообщения “Discover”, “Inform”, “Renew” и “Rebind”) от клиентов. В случае если сообщение исходит от клиента с MAC адресом, подпадающим под запись в запрещающем списке, DHCP сервер не выполняет обслуживание этого клиента (не отвечает ему). Если клиент подпадает под действие запрещающего списка на основе маски, но запись с его MAC адресом содержится в списке разрешающем, то обслуживание клиента осуществляется. В случае если MAC адрес клиента явно указан в запрещающем списке, то обслуживание клиента не осуществляется, вне зависимости от наличия соответствующей записи в списке разрешающем, т.е. явный запрет имеет абсолютный приоритет.
dhcpfilter-pic01
Как это использовать?
Важно понимать, что фильтрация на основе MAC адреса на сервере DHCP не может считаться действенным механизмом защиты доступа к сети! Данный функционал оправдан и рекомендован к использованию лишь как вспомогательное средство в сценариях, предполагающих применение ограничения в обслуживании службой DHCP доверенных узлов сети.
Управлять функционалом MAC-фильтрации можно из консоли управления сервером DHCP («DHCP Server», «dhcpmgmt.msc»): узел «Filters» («Фильтры»), а наблюдать за ее работой можно в журнале событий[iv].
Материалы по теме.
Основные сведения о протоколе DHCP
[i] Такой сценарий типичен, например, для распределенных множественных точек доступа к сети, предоставляющих своим клиентам возможности авто-конфигурирования их сетевых интерфейсов с помощью центрального сервера DHCP.
[ii] Путь в системном реестре:
«HKLM\SYSTEM\CurrentControlSet\Services\DHCPServer\Parameters».
[iii] Маска может содержать лишь один и только завершающий «wildcard».
Пример: «1A-2B-3C-*».
[iv] Event Viewer: Applications and Services Logs\ Microsoft\ Windows\ DHCP Server.

AppLocker — укрепляем безопасность вашей сети


Ваши пользователи запускают сомнительное ПО? Вы не в состоянии проконтролировать каждого пользователя? Научитесь предотвращать потенциальные угрозы атак опасного ПО штатными инструментами.

Вопросы безопасности компьютерных сетей были, есть и будут актуальны во все времена, поскольку именно от них зависит успех вашего бизнеса. Одной из самых больших и трудноразрешимых проблем безопасности является злонамеренное ПО. Компьютерные вирусы существуют уже не один десяток лет, и столько же времени идёт неустанная борьба с ними.

Этот вопрос может стать актуальным, когда сотрудник вашей фирмы по выпечке пирожков получает письмо от конкурентов с приложенным файлом. После запуска этого файла (ведь пока его не запустишь — не узнаешь, что там внутри) новый секретный рецепт фирменных пирожков вашей компании уходит к конкурентам. Другая опасность связана с тем, что зловредное ПО нарушает нормальную работу ПК — в связи с чем сотрудники не смогут полноценно выполнять свои задачи, и им приходится бороться с симптомами заражения. Поверьте, клиенты не станут ждать, пока вы решите свои проблемы, а просто уйдут к другим поставщикам.
На сегодняшний день существуют десятки специализированных программ и решений, которые предназначены для защиты от компьютерных вирусов, троянских модулей и другого опасного ПО. Однако, в действительности эффективность подобного подхода остаётся крайне низкой, поскольку чаще всего борьба ведётся лишь с уже известными производителю антивирусной программы версиями зловредного ПО. Когда антивирус обнаруживает угрозу, система зачастую уже скомпрометирована и бороться с последствиями уже бесполезно. Учитывая эту проблему, некоторые поставщики предлагают продукты, которые подходят к решению с другой стороны — пытаются устранить даже потенциальную возможность заражения. В 2001 году Microsoft выпустила первый вариант своей технологии, которая называлась Software Restrition Policies или просто SRP (о ней вы можете прочитать в статье «На страже безопасности — Sotware Restriction Policies» в номере 9/2008 журнала «Системный администратор»). За восемь лет существования этой технологии она по различным причинам так и не смогла завоевать широкую популярность. Практика показала, что управление SRP было далеко не простым, а сама реализация имела известные критические недостатки.
С выходом Windows 7 и Windows Server 2008 R2 Micosoft предлагает другое — более гибкое, удобное и ещё более надёжное средство защиты — AppLocker. Фактически AppLocker является новой архитектурной реализацией того же принципа, который был представлен в SRP. Наиболее заметным изменением стало то, что политика теперь работает не в пользовательском окружении, а в системном. Это практически лишает пользователей возможностей по обходу запретов AppLocker.

Начало работы

Для того, чтобы начать работу с AppLocker, вы должны открыть оснастку редактора групповой политики в секции Computer Configuration → Policy → Windows Settings → Security SettingsApplication control Policies AppLocker.
внешний вид консоли AppLocker
Рис. 1 — внешний вид консоли AppLocker
В дереве консоли вы увидите несколько дочерних элементов, в которых вы сможете создавать и редактировать правила. Они сгруппированы по типам.
  • Executable Rules — могут содержать правила для файлов типов «Application» (с расширением «exe») и «MS-DOS Application» (с расширением «com»). В действительности к данной категории относятся и файлы типа «Screen saver» (с расширением «scr»), так что правила будут применяться и к ним. Однако создавать отдельные правила для этих файлов вы не можете.
  • Windows Installer Rules — могут содержать правила для файлов типов «Windows Installer Package» (с расширением «msi») и «Windows Installer Patch» (с расширением «msp»).
  • Script Rules — могут содержать правила для файлов типов «Windows Batch File» (с расширением «bat»), «Windows Command Script» (с расширением «cmd»), «Jscript Script File» (с расширением «js»), «PS1 File» (сценарий Windows PowerShell с расширением «ps1») и «VBScript Script File» (с расширением «vbs»).
В основном окне вы можете управлять применением правил, а также видите сводную информацию по их количеству. Чтобы изменить режим применения политики, щёлкните по ссылке «Configure rule enforcement». Для каждого типа правил можно выбрать один из двух режимов работы.
  • Enforced — правила принудительно применяются к пользователям. И любой файл, для которого нет подходящего правила, будет заблокирован для запуска;
  • Audit Only — режим аудита. Он полезен для определения списка ПО, которое используется пользователями. Когда включен этот режим, политики AppLocker не ограничивают запуск приложений. Но если для запускаемого файла (сценария или приложения) задано правило в политике, в журнал событий AppLocker будет добавлена соответствующая запись. Этот журнал можно просмотреть через оснастку «Event Viewer» по адресу Applications and Service logs → Microsoft → Windows → AppLocker.
окно управления режимом работы политики для каждой категории правил
Рис. 2 — окно управления режимом работы политики для каждой категории правил
На вкладке «Advanced» того же окна вы можете отдельно настроить применение политик AppLocker к файлам типа «Application extension» — динамически загружаемым библиотекам с расширением «dll». Однако используйте эту функцию с осторожностью, так как после её включения вам придётся создавать отдельные правила для файлов библиотек. А в результате проверки всех библиотек на соответствие правилам скорость работы системы может существенно снизиться.

Рис. 3 — окно управления проверкой файлов библиотек на соответствие правилам
Обратите внимание, что для применения правил в системе должна быть запущена служба «Application Identity». Для создания и редактирования правил это не требуется.

Создание правил

После краткого обзора консоли управления политикой мы можем приступать к созданию правил. К этой задаче существуют три подхода.
  • Создание правил вручную;
  • автоматическая генерация правил;
  • автоматическое создание правил по умолчанию.
Image42
Рис. 4 — создание новых правил из контекстного меню каждого типа
В большинстве случаев я рекомендую комбинировать ручное создание правил с автоматической генерацией правил по умолчанию. Это позволит сразу создать относительно безопасную среду Для этого нажмите правой кнопкой на каждой категории и выберите элемент «Create Default Rules», после чего система создаст несколько правил по умолчанию. Пример результата для типа «Executable Files» показан на рис.5.
Image5
Рис. 5 — правила, созданные по умолчанию
Правила по умолчанию позволяют всем пользователям запускать любые исполняемые файлы из каталогов «Windows» и «Program Files». А локальным администраторам разрешают запускать вообще всё. Это достаточно щадящие правила, которые впоследствии могут быть отредактированы под ваши нужды. Так же здесь хочу отметить один достаточно важный момент — пока в конкретной категории правил политики нет ни одного правила, вы можете запускать любые файлы, которые подпадают под эту категорию. Создав хоть одно правило, вы сможете запускать только те файлы, которые подпадают под разрешения в созданных правилах.
В результате, если мы работаем под учётной записью обычного пользователя, нам будет разрешено запускать файлы только из системных каталогов. Это относится только к тем расширениям, которые проверяются политикой. Но очень часто этого будет недостаточно, именно поэтому придётся создавать и свои правила. Для этого в контекстном меню нужной категории выберите пункт «Create New Rule...», после чего вы увидите окно создания нового правила. Правила создаются пошаговым мастером, поэтому разобраться в них будет достаточно просто.
Рис. 6
Рис. 6 — окно мастера создания правил
В секции «Before You Begin» вы можете прочитать вступление к мастеру и основные инструкции. В секции «Permissions» вы можете задать действие для правила — разрешить или запретить запуск подходящих файлов, а также выбрать группу безопасности, на которую это правило будет распространяться. Это намного удобнее, чем механизм применения политик в SRP. Теперь мы можем создать всего одну политику на уровне домена вместо того, чтобы иметь несколько отдельных политик и управлять их применением с помощью Security Filtering. Важно знать, что политики AppLocker не действуют на служебные учётные записи, например, LocalSystem. Дальше, в секции «Conditions» вы выбираете тип правила. Прежде, чем выбрать что-то из этого списка, следует рассмотреть каждый тип правил.

Правила пути

Правила пути достаточно простые, но их нужно использовать осторожно. Правила этого типа следует использовать только для тех путей, по которым пользователи не имеют права на запись. Ни в коем случае не допускается создание правил путей для каталогов, в которые пользователи могут записывать свои файлы. Ведь в результате им ничего не будет стоить подменить легитимные файлы своими и запускать их. Правила пути обычно используются для приложений, которые установлены не в стандартный каталог (Program Files), а находятся по другому адресу — например, в сетевой папке или на другом томе. Вы можете использовать подстановочные знаки — такие, как «?» и «*», а также специальные переменные окружения.
Переменная пути в AppLocker Аналог переменной окружения в Windows Пример
%WinDir% %WinDir%, %SystemRoot% “C:\Windows\”
%System32% n/a “C:\Windows\System32\”
%OSDrive% %SystemDrive% “C:\”
%ProgramFiles% %ProgramFiles%,%ProgramFiles (x86)% “C:\Program Files”,“C:\Program Files (x86) ”
%Removable% n/a CD or DVD (съёмные накопители)
%Hot% n/a Накопители USB (носители данных с «горячим» подключением)
Несмотря на синтаксическое совпадение с некоторыми системными переменными окружения, они таковыми не являются. К сожалению, мы лишены возможности использования системных переменных окружения во избежание их подмены. Например, при настройке SRP системные администраторы в качестве пути к сценариям входа в систему зачастую использовали такие переменные как %LogonServer% (в конструкции вроде «%LogonServer%\NetLogon\Scripts»). Это даёт гарантию подключения к сетевой папке «NetLogon» работающего контроллера домена. Сейчас же для создания подобных правил придётся использовать абсолютные пути вместо относительных.
Но это неудобство было немного компенсировано другой полезной особенностью — теперь мы можем использовать отдельные переменные для съёмных и оптических носителей.

Правила хешей

Это один из наиболее популярных типов правил как в SRP, так и в AppLocker. Правило хеша просто создаёт хеш для файла (с использованием алгоритма SHA256) и записывает его в правило. Данный тип правил следует использовать для файлов, которые расположены в разрешённых для записи пользователям каталогах. Действительно, некоторые программы для корректной работы требуют прав на создание файлов в той же папке, в которой находится сам исполняемый модуль. Для таких сценариев целесообразно использовать правило хеша. В этом случае при повреждении файла, подмены, заражения вирусом — его хеш будет также изменён, и файл окажется заблокирован для запуска. Однако, при частом обновлении программ вам с такой же периодичностью придётся обновлять и соответствующие правила хеша.

Правила издателей

Правила издателей — это следующая ступень эволюции классических правил сертификатов в SRP, которая привнесла несколько удобных нововведений. Правило издателей вы можете создавать просто указав файл с цифровой подписью. При этом следует учесть, что для этого файл должен иметь целостную подпись, а корневой сертификат подписи должен быть помещён в контейнер «Trusted Root Certification Authorites». Если хоть одно из этих условий не выполняется, то создать правило издателя не получится.
Рис. 7
Рис. 7— окно со свойстами правила издателя
Если посмотреть на примере Microsoft Office, то мы видим достаточно информации, чтобы достоверно идентифицировать приложение. Такое правило включает поле «Subject» сертификата цифровой подписи, сведения о продукте, внутреннее имя файла и внутреннюю версия файла. Используя ползунок, мы можем задать и более общее правило, которое, например, будет разрешать запускать любой подписанный файл с указанным полем «Subject» (в правиле это поле называется «Publisher») и внутренним именем без ограничения по версии. Или даже любой файл, который подписан таким сертификатом. Также вы можете использовать и вовсе произвольные настройки правил издателей. Для этого установите флажок «Use custom Values» — и все поля станут доступны для редактирования вручную. В том числе, вы можете указывать степень соответствия версии файла как «Exact match», «And above» и «And below». Это можно использовать, когда вы хотите запретить использовать любые версии Excel младше, чем Excel 2003. Тогда вы указываете версию 11.0.0.0 и степень соответствия выставляете в «And above». В таком случае запустятся только версии Excel 2003 и более новые.
Правила издателей удобны для часто обновляемых программных файлов (например, бизнес-приложения или ваши собственные подписанные сценарии). В случае, если после обновления файлы проходят повторный процесс подписывания, они подпадут под уже существующее правило и будут запускаться.

Много правил в одном правиле

Следующим достаточно большим удобством является то, что при использовании правил путей или правил хеша, вы можете добавлять не только по одному файлу, но и группу файлов в одном каталоге. Технологически вы не имеете возможность добавить группу файлов на основе правила издателя, поскольку правило издателей не опирается на физическое местоположение файлов, а их целостность проверяется только при запуске. Когда вы выбрали правило пути или правило хеша, в следующем окне мастера вы можете нажать «Browse Folders», и тогда для правила пути мастер разрешит запускать всё из указанного каталога (это будет заметно по символу подстановки — «*» в конце пути). А для правила хеша мастер найдёт все подходящие файлы в указанной папке и подсчитает для них хеш. При этом важно отметить, что поиск не будет рекурсивным (т.е. не станет включать файлы во вложенных каталогах).
Если вы хотите исключить какие-то файлы из полученного списка, достаточно выделить нужные файлы и нажать кнопку «Remove». Вы не можете использовать отдельные исключения для правила хеша, поскольку любой хеш уникально идентифицирует конкретный файл. Иными словами под одно правило хеша может подпадать только один файл. А добавляя несколько файлов (например, все файлы в каталоге), вы создаёте целый набор отдельных правил хеша. Это следующий положительный момент в организации правил в AppLoker, поскольку эти составляющие правила вы можете группировать по какому-либо принципу. Например, создать одно общее правило хеша, которое будет называться «Microsoft Office», и внутри этого правила добавить по хешу несколько исполняемых файлов из программного пакета. Зачастую бизнес-приложения так же состоят из нескольких исполняемых модулей. Таким образом значительно повышается читабельность политик, удобство управления правилами и снижается вероятность ошибки.
Я рекомендую именно такой сценарий группировки правил — по типу приложений. Для каждого приложения вы создаёте свою коллекцию правил, в которую включаете все необходимые исполняемые модули. Таким образом, при изменении определённого приложения вам будет очень просто найти нужное правило и отредактировать его.

Исключения из правил

В отличие от правила хеша, правила пути и издателя не позволяют уникально идентифицировать файл и обладают достаточно большой областью действия. Поэтому возможны ситуации, когда вы хотите запретить запуск некоторых файлов, которые подпадают под разрешающее правило. Для этого в секции «Exceptions» мастера создания правила вы можете указать исключения.
Рис. 8
Рис. 8 — окно «Exceptions» мастера создания правил
Как вы видите на рисунке, исключения можно создавать используя все возможности AppLocker. В порядке исключения вы можете добавлять исключаемые пути, хеши файлов и даже цифровые подписи. Например, вы разрешили все файлы по маске «%PROGRAMFILES%\Microsoft Office\*», используя правило пути. Однако вы хотите запретить запуск программы PowerPoint. Для этого вы можете создать исключение по правилу пути вида «%PROGRAMFILES%\Microsoft Office\Office12\POWERPNT.EXE» или по правилу хеша, указав конкретный файл «PowerPnt.exe».
Другой сценарий может подразумевать, что у вас есть приложение, исполняемые модули которого подписаны различными сертификатами. В таком случае правило издателя будет не очень эффективным решением, и вы приняли решение создать правило пути или правило хеша для всего каталога. Но вы хотите запретить запуск файлов, которые подписаны определённым сертификатом. В данном случае в секции «Exceptions» вы указываете тип исключения «Publisher» и в диалоговом окне поиска выбираете файл с необходимой цифровой подписью. Таким образом вы сможете запускать все файлы из каталога — кроме тех, которые подписаны указанным сертификатом.

Исключения или запреты?

Внимательные читатели могут задать вопрос: а зачем делать исключения, если их можно вынести в отдельные правила запрета? Действительно, на первый взгляд может показаться, что это более простое решение. Однако запреты всегда являются краеугольным камнем в настройке прав.
Применительно к AppLocker здесь есть несколько нюансов, которые следует учитывать при создании запретов. Самый главный из них — порядок применения правил. Для определения возможности запуска файла AppLocker при сортировке правил использует принцип первого попадания (First Match). Это означает, что правила к файлу применяются в строго определённом порядке, и действующим окажется то, которое сработало (т.е. под которое подпал файл) первым. Поэтому знание принципа сортировки правил в AppLocker может сэкономить вам время.
Все правила сортируются отдельно по запретам и разрешениям и проверяются в следующем порядке.
  1. Сначала проверяются все явные запреты (в произвольном порядке).
    a) Если файл подпал под явный запрет, то для этого запрета отрабатываются все исключения. Если файл всё ещё подпадает под явный запрет, то файл блокируется для запуска.
    b) Если после обработки исключений больше не подпадает под явный запрет, то берётся следующее запрещающее правило и так продолжается, пока не будут проверены все явные запреты.
  2. Если ни одного явного запрета не обнаружено, то проверяются все явные разрешения.
    a) Если файл подпал под явное разрешение, то для этого разрешения отрабатываются все исключения. Если файл всё ещё подпадает под разрешение, то файл будет разрешён для запуска.
    b) Если после обработки исключений файл больше не подпадает под явное разрешение, то берётся следующее разрешающее правило, и процесс повторяется до тех пор, пока файл после фильтрации исключений не подпадёт под разрешение.
  3. Если ни одна из итераций не дала однозначный ответ вида разрешено/не разрешено, то файл блокируется для запуска.
Чтобы понять, как это работает, рассмотрим один пример.
На компьютере в каталог по умолчанию установлен пакет Microsoft Office, которым можно пользоваться всем. Но группе «Accountants» необходимо разрешить запускать только программы Word и Excel. Запуск остальных файлов из «Program Files» разрешён без ограничений.
Для решения этой задачи мы должны разрешить весь каталог «Program Files» по правилу пути для группы «Everyone». Поскольку доступ к программам Microsoft Office будет ограничен только для группы «Accountants», мы создаём новое запрещающее правило (с действием «Deny»), которое применяется только к группе «Accountants». Теперь программы из пакета Microsoft Office будут разрешены для запуска всем, кроме группы «Accountants». Чтобы обеспечить запуск только необходимых приложений из этой папки, мы редактируем запрещающее правило и добавляем два исключения (по правилу пути, хеша или издателя) для файлов «Excel.exe» и «Word.exe».
Исходя из порядка сортировки правил, в первую очередь файлы будут проверены на соответствие запрещающему правилу (запрет на каталог Microsoft Office) с учётом исключений. После этого под запретом остаётся весь каталог Mictosoft Office, но без «Word.exe» и «Excel.exe». Если у нас запретов больше нет, то применяется разрешение на каталог «Program Files» для группы «Everyone». Поскольку указанные файлы подходят под это разрешающее правило, они и будут разрешены для запуска. (Разумеется, при условии, что в этом разрешающем правиле нет исключений, действующих на эти файлы).
А вот если члены группы «Accountants» попытаются запустить PowerPoint, то ситуация окажется совершенно другой. Мы снова начинаем с первого шага. Из запрещающего правила отрабатываются исключения, т.е. Word и Excel, а затем файл снова проверяется на соответствие правилу. И даже после удаления исключений PowerPoint всё ещё подпадает под запрет. В таком случае остальные правила не проверяются, а запуск блокируется.

Импорт и экспорт правил AppLocker

В процессе эксплуатации AppLocker вы можете захотеть зафиксировать конфигурацию политик на отдельной рабочей станции перед изменением существующих правил. Одной из причин такого шага может служить необходимость отката к заведомо работоспособной конфигурации на случай, если изменения приведут к непредвиденным последствиям, а так же для использования шаблонов правил. При использовании SRP это зачастую было неразрешимым вопросом, поскольку стандартные шаблоны безопасности (Security Templates) не позволяют заранее настроить правила для SRP и сохранить их в каком-то состоянии. В AppLocker этот недостаток также решён.
Рис. 9
Рис. 9 —контекстное меню импорта и экспорта политики AppLocker
В контекстном меню AppLocker вы можете выбрать команду «Export Policy» для экспорта и «Import Policy» для импорта политик. AppLocker сохраняет все правила и настройки в файле XML, который вы можете редактировать даже без доступа к редактору групповой политики. Если в доменной среде вы можете делать резервные копии политик с помощью GPMC, то в условиях рабочей группы (например, домашнего использования) эта возможность будет очень удобным и простым средством сохранения ваших правил AppLocker.

Заключение

В данной статье мы рассмотрели ключевые возможности нового инструмента защиты ПК от выполнения нежелательного (и потенциально злонамеренного) ПО — AppLocker. Также мы рассмотрели методику создания правил на нескольких практических примерах. Изложенный материал является достаточным для начала эффективной работы с AppLocker с целью обеспечения безопасности ваших систем. Если вы заинтересовались данной технологией и хотели бы испытать её в действии, то вы можете загрузить ознакомительную версию Windows 7 Enterprise с сайта Microsoft. Также, более глубокое изучение особенностей работы политики AppLocker вы можете прочитать в блоге автора статьи — http://www.sysadmins.lv

Ссылки

AppLocker Technical Documentation for Windows 7 and Windows Server 2008 R2 — http://www.microsoft.com/downloads/details.aspx?FamilyID=025cf2e8-b0ab-4419-b5bb-86ab2d5eca83
AppLocker Step-by-Step Guide — http://technet.microsoft.com/library/dd723686.aspx
Windows 7 Enterprise 90-day Trial — http://technet.microsoft.com/evalcenter/cc442495.aspx

Nov 29, 2009

So, you installed System Center Operations Manager…what next?


So, you decided to install System Center Operations Manager in your environment in order to start monitoring your environment. Or someone else installed Operations Manager for you, and it’s your job to start working with it. What should you do next?

You probably made a design or a design was made and based on that design Operations Manager is installed in your environment. For these steps a lot of documentation is available from Microsoft, a lot of this documentation can be found on the Microsoft website.

- Infrastructure Planning and Design guides: http://go.microsoft.com/fwlink/?LinkId=160871
- Technet – Operations Manager: http://technet.microsoft.com/en-us/opsmgr/default.aspx
- Technet – Operations Manager R2 Design Guide: http://technet.microsoft.com/en-us/library/dd789005.aspx
- Technet – Library: http://technet.microsoft.com/en-us/library/bb310604.aspxhttp://technet.microsoft.com/en-us/library/bb310604.aspx

Keep in mind two things:

1. Beside using Operations Manager as a tool to detect problems in your environment, Operations Manager as a product must be maintained as well.
o Tune your Operations Manager environment
o Update Management Packs
o Add Agents

2. You must seriously invest time in Operations Manager, so that engineers who use the application to detect problems in the environment will soon lose their interest in the product when Operations Manager doesn’t reflect the real situation. When “bogus” messages appear, or problems aren’t detected in System Center Operations Manager, the product will not be taken serious.

Here are some tips which can help you to start tuning your Operations Manager Environment.

Rename your Default Management Pack

By design, when you define an override you will end up saving this override in the Default Management Pack. If you save all of your overrides in one management pack though, you will eventually end up with a serious problem. That’s because you can’t delete a management pack which has another management pack which depends on it. For Example: you need to upgrade your Cluster MP, but first have to remove it because of the changes to the MP, you need to delete your Default MP; this deletes all overrides and all tuning is gone, result: lots of alerts again,etc. If you already have overrides in your default management packs you can use Override Explorer written by Boris Yanushpolsky to track them down, and move them to another management pack.

Keep in mind though, that moving an override to another management pack doesn’t remove the reference in the Manifest section of the (Default) Management Pack. In order to accomplish this you have to do some editing in the XML file as outlined in this blog post: http://blogs.technet.com/momteam/archive/2007/05/03/removing-dependencies-on-the-default-management-pack.aspx

Define Override Management Packs

For the Management Packs which are already available I suggest that you create override Management Packs per MP. Define a naming convention for these kind of Management Packs so that you can easily identify them. Use the name of the Management Pack and the word Override in the name, for example: “Windows Cluster MP – Overrides”.
I would even suggest to make a distinct in override managements packs, one which contains overrides for object you really don’t want to monitor, and another one which contains ‘fixes’ which might be resolved by later Management Packs.

Create a Closed Alerts View

By design, there is no view which contains the Closed Alerts, you may want to create this view though so that you can browse to the closed alerts. Which can help you to determine what was wrong at a certain point of time. Use the filter “resolution state equals 255” to achieve this.

Schedule a backup of your Management Packs

Define a Scheduled task which runs a Powershell script which will make an export of your management packs every night. Having your Management Packs available can help you a lot when you have problems with one of your operational Management Packs, and saves you from restoring the whole Ops DB.

Reference: Using PowerShell to import/export management packs: http://ops-mgr.spaces.live.com/Blog/cns!3D3B8489FCAA9B51!159.entry

Antivirus Exclusions on your Agents

Keep in mind that the Operations Manager Agent executes certain scripts for all kinds of tasks. If a virus scanner is blocking these scripts, the scripts can’t do their job, resulting in lots of errors. These scripts are run from the Health Service State folder, so exclude this folder containing the Operations Manager Agent installation on every Agent and disable things like the McAfee scriptscan functionality.

Firewall Ports

When your clients have the firewall enabled, keep in mind to open the necessary port based on the functionality you need. You can find more information about that in the following articles

Reference: Using a Firewall with Operations Manager 2007: http://technet.microsoft.com/en-us/library/cc540431.aspx

And if you want to install the Operations Manager Agent from the console you will need the following firewall rules enabled.

Reference: How does Computer Discovery Work in OpsMgr 2007?: http://blogs.technet.com/momteam/archive/2007/12/10/how-does-computer-discovery-work-in-opsmgr-2007.aspx

Add Agents and additional Management Packs

Out of the box, System Center Operations Manager is installed with a couple of Management Packs already installed. These Management Packs provide some basic monitoring though, so you may want to install additional Management Packs.
You can find many Management Packs in the System Center Operations Manager Management Pack Catalog, and you can find some community written Management Packs here: http://www.systemcentercentral.com/WIKI/WIKIDetails/tabid/146/indexid/20495/Default.aspx
Keep in mind though that it is a good practice to read the corresponding Management Pack Guide carefully before you import your management pack. They contain information like which discoveries are disabled by default or which overrides to set to get a “working” MP. These Management Pack Guides can be found at the following location:
System Center Operations Manager 2007 Management Pack Guides: http://technet.microsoft.com/en-us/library/dd347500.aspx

From my perspective there are two approaches to fully deploy monitoring to your infrastructure:
- Install Agents on all of your “to-be monitored machines”, and introduce one Management Pack at a time and tune it before continuing to the next MP.
- Add all the Management Packs at once and granularly deploy your Agents, tuning them agent-by-agent.

Don’t do both, because you will end up with a lot of noise by so called “false positives” being generated, and for that noise you will have to figure out if it contains valid errors or that you can discard the error. You do this by either solving a bug, or by defining an override, but having to do this all at once will “drown” you in alerts
Tuning your Operations Manager environment consists of a lot of steps to adjust the MPs. There is no cookbook on how to tune your environment, because how and what to tune depends on your environment. That’s what makes Operations Manager a product that is different for every environment ;)

You may want to start looking at the Critical alerts, check the proposed resolution steps in the alert and try to solve the problem. If you don’t understand the alert try to find more information about the alert on the Internet. There are many good blog posts out there which can help you to determine what the problem is you are experiencing, and how to solve it.

Get involved in the community

One of the big advantages of working with System Center Operations Manager is that it’s supported by a very enthusiastic community and a very involved MS product team. Many problems you will encounter are already described and solved in blog posts, and if not you can post your problem on one of the forums which is monitored by a lot of SCOM guru’s which will try to help you the best they can. Here are some suggestions:

o System Center Central – http://www.systemcentercentral.com
o Operations Manager Online Forums - http://social.technet.microsoft.com/Forums/en-US/category/systemcenteroperationsmanager

Blogs:
o Kevin Holman – http://blogs.technet.com/kevinholman/
o Boris Yanushpolsky - http://blogs.msdn.com/boris_yanushpolsky/
o Marius Satura - http://blogs.msdn.com/mariussutara/
o Stefan Stranger - http://blogs.technet.com/stefan_stranger/default.aspx
o Walter Chomak - http://blogs.technet.com/wchomak/
o Operations Manager http://ops-mgr.spaces.live.com/default.aspx
o Operations Manager Team Blog http://blogs.technet.com/momteam/default.aspx
o Operations Manager Support Team Blog - http://blogs.technet.com/operationsmgr/

Begin building your Distributed Applications

After you performed your initial tuning of the environment, and you feel comfortable with the messages you’re receiving in the SCOM Console, you can take the next step. Start building your Distributed Applications and move from Server monitoring towards Service/Application Monitoring. Here you will discover the true strength of System Center Operations Manager.
When building Distributed Applications, keep in mind that in order to successfully monitor an distributed application you need to monitor all the objects that compose the distributed application. Sometimes this means you might want to consider buying 3rd party management packs which provide this functionality, or create your own management pack.

Download this article in PDF format for easy reading

Nov 26, 2009

SQL Server: Recovering from Disasters Using Backups


Paul S. Randal

There isn't much point taking SQL Server backups unless you know how to restore them. If you have anything more complicated than just a full database backup, you're going to need to know some RESTORE options to be able to successfully restore your database to the desired point in time.
This is even more the case if you have a complicated database layout or a complex backup strategy and you want to be able to restore, for example, a single file or filegroup, or take advantage of partial database availability.

As long as you have an effective backup strategy and your backups are valid, you should be able to recover from a disaster within your Recovery Time Objective (RTO) and to your Recovery Point Objective (RPO). In the first article in this three-part series, I discussed the various types of backups and how to formulate a backup strategy (see "Understanding SQL Server Backups" in the July 2009 issue).
In this article, I'll explain how restore works and how to perform some of the more common restore operations. It will be helpful if you've read the backup article, and the background material I mentioned in that article's introduction. I'm also going to explain a few more tricky operations, such as doing a point-in-time restore and an online piecemeal restore with partial database availability.
Just as in the previous article on BACKUP, I'm not going to explain how the RESTORE syntax works or go through the specific steps of all restore operations. SQL Server Books Online does an excellent job of that. See "RESTORE (Transact-SQL)" for more info, especially the examples spread throughout the topic. There are actually so many options to RESTORE that it's a whole other topic to explain them! "Backing Up and Restoring How-to Topics (SQL Server Management Studio)" explains how to use the tools to perform restores.

The Four Phases of Restore

Let's start with how restore actually works. A restore operation has up to four phases:
  1. File creation and initialization
  2. Data and/or transaction log copy
  3. REDO phase of recovery
  4. UNDO phase of recovery
One of the primary goals of disaster recovery is to bring the database online as quickly as possible. If your disaster-recovery plan involves restoring backups (instead of, say, failing over to a database mirror), you're going to want the restore process to be as fast as possible. With each of the four restore steps in mind, is there anything you can do to speed them up?
The first step can be essentially skipped if the data and log files already exist. This means that if you're going to overwrite an existing database, don't drop the database before doing the restore. Instead, use the WITH REPLACE option on the first restore operation to tell SQL Server to use the existing files. If the files don't exist, they will be created and then initialized. Creating the files is very fast, but the process of zero-initializing them can be very slow.
For security reasons, and by default, all database files are zero-initialized. You can enable instant file initialization for the SQL Server instance, which skips the zeroing process for data file create and grow operations, including those required during a restore -- possibly saving hours of downtime, even if the data files are only gigabytes in size. Transaction log files are always zero-initialized because of the circular nature of the transaction log itself.
You can read more about all of this, with references to Books Online, in my "Instant Initialization" blog post category.
You may be wondering about the second phase -- why does the item say "and/or transaction log"? If you read the previous article, you'll remember that all full and differential backups also include some transaction log records, to enable the database to be restored to a transactionally consistent point in time. Phase two is a pure copy operation -- no processing of the data is performed -- so the main way to speed this up is to have a better-performing I/O subsystem. This is one of the few times when it's acceptable to "throw hardware at the problem."
The other way to speed up the copy phase is to use some kind of backup compression technology, either native to SQL Server 2008 or through one of the various third-party solutions. The two parts of the copy phase are reading from the backup media and writing out to the data and/or log files. If you can do fewer reads (using compressed backup media), you can speed up the overall process, at the expense of a small amount of CPU resources.
Phases three and four are about running recovery on the transaction log to bring the database to a transactionally consistent point in time. I explained the details of recovery in the February 2009 article "Understanding Logging and Recovery in SQL Server". Note that phase four is optional, as I'll explain later.
Suffice it to say that the more transaction log that needs to be recovered during a restore, the longer the restore will take. This means that if, for instance, you have a full database backup from a week ago and hourly transaction log backups since then, the restore process will essentially replay all the transactions from the last week before completing. I discussed a solution for this in the previous article -- adding differential backups into a full-plus-log backup strategy.
A differential database backup contains all the datafile pages that have changed since the last full database backup, and can be used in a restore operation to avoid having to replay all the transactions that occurred in the period between the full database backup and the differential database backup. This can vastly reduce the time it takes to restore the database, but at the expense of a slightly more complicated backup strategy.
You can find more information in the Books Online topic "Optimizing Backup and Restore Performance in SQL Server".

What Do You Need to Restore?

When disaster strikes, the first thing you need to do is work out what has been damaged, as this is going to dictate the actions you must take to recover from the disaster. For storage media failure, the possibilities include:
  • Damage to the entire database (for instance, whatever was storing the database was destroyed, or the database was a single data file and it was damaged).
  • Damage to a single filegroup of a multi-filegroup database.
  • Damage to a single file of a multi-file filegroup.
  • Damage to a single page in the database.
  • Damage spread through the database.
You can ascertain the damage by looking through the SQL Server error log for notifications that file(s) are inaccessible, that page-read errors occurred (for instance, page checksum failures or a torn-page detection error), or that general corruption was encountered. If damage occurred, it is usual practice to run the DBCC CHECKDB consistency-checking operation to get an idea of how pervasive the damage is.
An explanation of consistency checking is beyond the scope of this article, but you can watch a video of a presentation I made at the Tech-Ed IT Forum in November 2008 titled "Corruption Survival Techniques", and listen to a TechNet Radio interview from earlier this year where I discuss database corruption (direct download links are here).
Disasters are not limited to I/O subsystem or server failures -- there's also human error to consider. Database tables (or data from them) are often accidentally deleted by poorly programmed applications or careless Transact-SQL statements (the "I didn't realize I was on the production server" scenario). In such cases, it can be very difficult to figure out what needs to be restored and from what point in time, especially if no one owns up to making the mistake. You might get lucky using standard reports from the default trace where the DDL operation is still available or the DELETE statement was caught by your own logging -- but often there's no record of who did what to the database. I'll discuss recovering from this situation in more detail later. Regardless of who performed the accidental data deletion or when it happened, the longer you wait to recover -- or the more time that passes before you are made aware of the problem -- the more complex it can be to recover.
So, as a first step if the database is running in the FULL recovery model and the transaction log is undamaged, perform a tail-of-the-log backup to ensure that all transactions up to the point of the disaster are backed up. This "final" transaction log backup will have everything up until the time of the disaster and can be used to bring the database being restored as far as possible, possibly up-to-the-minute.
In a nutshell, you need to work out what you have to restore. Then it becomes a question of what you are able to restore.

What Are You Able to Restore?

The aim of any restore operation is to restore the fewest possible backups, so the restore operation is as fast as possible and completes within your RTO, while also allowing you to meet your RPO.
The main question to ask here is "What backups do I have?" If the only backup you have is a full database backup from a week ago and the whole database has been lost, there's only one restore option -- to a point in time a week ago, losing all work since then. Simply put, your backup strategy should always ensure that you are able to restore what you need to in the event of a disaster, as I discussed in the previous article.
So how can you determine what backups you have available? First, you can query that various backup history tables in the msdb database. These tables contain a record of all backups that have been taken in the SQL Server instance since the last time the backup history tables were cleared out.
As far as the backups themselves are concerned, it is a best practice to name backup files to include the database, type of backup, date and time so that the backup can be identified at a glance. If you haven't done this, you can find out what a backup file contains using the RESTORE HEADERONLY command. This will display the contents of the backup file's header, essentially the metadata that describes the backup itself. You can read more in the Books Online topic "Viewing Information About Backups".
Using either method, you are trying to work out the restore sequence to use to restore the damaged or deleted data. A restore sequence is a set of backups that must be restored and the appropriate order in which to restore them. The restore sequence may be as simple as just one full backup (of a database, filegroup or file), or a complicated set of full, differential and transaction log backups.
For instance, imagine a scenario where the backup strategy involves full database, differential database and transaction log backups. If a system crash occurs and the data files are damaged, what is the restore sequence? Figure 1 illustrates this example.
In this case, the shortest and fastest restore sequence is the most recent full database backup (F), the most recent differential database backup (D2), and then all subsequent transaction log backups, up to and including the tail-of-the-log backup (L7 and L8).
One of the tricky problems when planning a restore sequence is finding the earliest required transaction log backup to restore (sometimes called finding the "minimum-LSN," or "minimum-Log Sequence Number"). In the example in Figure 1, only transaction log backups L7 and L8 are required, because the differential database backup D2 brings the database to a more recent point in time than all the previous transaction log backups.

Figure 1: Example Restore Sequence
SQL Server will allow previous, unneeded transaction log backups to be restored, but they will not be used and essentially just waste disaster-recovery time.Continuing my example, what would happen if the differential database backup D2 was damaged or missing? Figure 2 shows this case.

Figure 2: Restore Sequence with a Damage Differential Database BackUp
In this scenario, the shortest and fastest restore sequence is the most recent full database backup (F), the next most recent differential database backup (D1), and then all subsequent transaction log backups (L4, L5, L6, L7 and L8). This is possible only as long as backups D1, L4, L5 and L6 are still available. It is important that you do not delete backups too soon; otherwise you could run into problems during a disaster.
For instance, if the full database backup F is damaged, unless the previous full database backup is still available, the database will not be recoverable. If the differential database backup D1 is deleted as soon as D2 completes, then the scenario in Figure 2 will not be possible, and the restore sequence will involve all transaction log backups since the full database backup -- a potentially very long restore sequence.
This raises the question of "When should you delete your previous backups?" The answer is definitely "It depends!" If you don't have a legal obligation to keep your backups around for a certain length of time, then it's up to you, and depends on the backup strategy you have and how much disk space is required. Regardless, don't immediately delete previous backups as soon as a new one is taken; it's best to keep at least one or two complete cycles of backups before getting rid of older backups. Ideally, you should test your backups before removing older ones.
For transaction log backups, in general you must have all of them since the last full database backup was taken, as that is the final fall-back restore sequence. If a single transaction log backup from the transaction log backup "chain" is missing or damaged, the restore operation can't proceed past the gap. As I mentioned in the previous article, verifying the integrity of your backups is a key part of being able to restore successfully.
You can find more details on figuring out what you're able to restore in the comprehensive Books Online topic "Working with Restore Sequences for SQL Server Databases".

Example Restore Scenarios

The most common restore scenario involves a full database backup and then one or more transaction log backups to bring the database forward in time. You can do this through SQL Server Management Studio (SSMS) or through Transact-SQL, although there is something you need to be aware of if you're going to use RESTORE commands directly.
When a backup is restored, there are three options for how the restore operation completes and they all relate to the UNDO phase of recovery. As each successive backup in the restore sequence is restored, the REDO phase of recovery is always performed, but the UNDO phase cannot be performed until the very last backup in the transaction log backup chain has been restored. This is because as soon as recovery is completed, no further transaction log backups can be applied, so all restores in the restore sequence must specify not to run the UNDO phase of recovery.
The default, unfortunately, is to run the UNDO phase of recovery -- the equivalent of using the WITH RECOVERY option on the RESTORE statement. When restoring multiple backups, you must be careful that each one specifies WITH NORECOVERY. In fact, the safest way is to use the WITH NORECOVERY option on all restores in the restore sequence, and then manually complete recovery afterward. Here is some example Transact-SQL code to restore a full database backup and two transaction log backups, and then manually complete recovery to bring the database online:
RESTORE DATABASE DBMaint2008 FROM
DISK = 'C:\SQLskills\DBMaint2008_Full_051709_0000.bak'
WITH REPLACE, CHECKSUM, NORECOVERY;
GO
RESTORE LOG DBMaint2008 FROM
DISK = 'C:\SQLskills\DBMaint2008_Log_051709_0100.bak'
WITH NORECOVERY;
GO
RESTORE LOG DBMaint2008 FROM
DISK = 'C:\SQLskills\DBMaint2008_Log_051709_0200.bak'
WITH NORECOVERY;
GO
RESTORE DATABASE DBMaint2008 WITH RECOVERY;
GO
Notice that I also used the CHECKSUM option on the restore of the full database backup to ensure that any page checksums present in the database being restored are verified as they are restored.
If WITH NORECOVERY was not specified on the first RESTORE statement, the following error is returned:
Msg 3117, Level 16, State 1, Line 1
The log or differential backup cannot be restored because no files are ready to rollforward.
Msg 3013, Level 16, State 1, Line 1
RESTORE LOG is terminating abnormally.
You must be very careful to use the right option, otherwise you risk having to start a long restore sequence again -- there's no way to undo recovery once it's completed.
There is, however, an interesting option which kind of does that -- the WITH STANDBY option. This is the last of three options I mentioned earlier. It works by running the UNDO phase of recovery, but it keeps a note of what it did (in an "undo" file whose name and path you specify) and then allows read-only access to the database. The database is transactionally consistent, but you have the ability to continue with the restore sequence. If you decide to continue, the UNDO is reversed (using the contents of the undo file) and then the next transaction log file is restored. This is useful in two scenarios: for allowing read-only access to a log-shipping secondary database and for looking at the contents of the database during the restore sequence.
If the disaster you're recovering from involves accidental deletion of a table, for instance, you may want to do a point-in-time restore. There are several ways to do this, but the most common is where you want to restore the database but ensure that recovery does not proceed past a certain time. In that case you can use the WITH STOPAT option to prevent transaction log restore from going past the time you know the table was deleted. For instance, using the Transact-SQL example above, if I wanted to prevent the database from being restored past 1:45 a.m., I could use the following syntax on the second RESTORE LOG statement:
RESTORE LOG DBMaint2008 FROM
DISK = 'C:\SQLskills\DBMaint2008_Log_051709_0200.bak'
WITH NORECOVERY, STOPAT = '2009-05-17 01:45:00.000';
GO
I could even combine STOPAT and STANDBY to see whether that was the correct point in time and then, if not, restore the same transaction log backup with a time a few seconds later and so on. This kind of operation becomes very tedious, but it may be the only solution if you don't know what time an operation took place.
A comprehensive discussion of these and other options for the RESTORE statement can be found in the Books Online topic "RESTORE Arguments (Transact-SQL)".
One of the coolest new features introduced in SQL Server 2005 Enterprise Edition was partial database availability. This feature allows a multi-filegroup database to be online and available as long as at least the primary filegroup is online. Obviously, data in any offline filegroups can't be accessed, but this feature allows a very large database to be split into separate filegroups for easier and faster recoverability. Another Enterprise-only feature that was added is the ability to perform piecemeal restores (for instance, a single filegroup from a multi-filegroup database) online, while the rest of the database is being used for processing.
These two features combined enable some quite sophisticated and efficient restore scenarios, as long as the database has been architected that way and the correct backups exist.
You'll find an excellent, in-depth SQL Server Technical Article titled "Microsoft SQL Server 2005 Partial Database Availability" with some extensive examples available at tinyurl.com/mbpa65. There's also a 75-minute recording of Kimberly L. Tripp delivering a Tech-Ed EMEA session titled "SQL Server 2005 VLDB Availability and Recovery Strategies" that is well worth watching.

Considerations When Restoring to a Different Location

The simplest restore scenario is when the database is being restored on the same SQL Server instance to which it is usually attached, and with the same name. As you move further away from that scenario, the aftermath of the restore operation becomes more complicated.
If the database is being restored on the same instance, but with a different name, you may need to make changes to elements like DTS/SSIS packages, database maintenance plans, application strings and anything that relies on a database name.
If the database is being restored on a different instance on the same server, things get a lot more complicated:
  • The SQL Server logins will be different or may not exist.
  • SQL Agent jobs and DTS/SSIS packages will be different or may not exist.
  • The master database is different, so any user-defined stored procedures may be missing.
  • The SQL Server instance name will be different, so there may be client connectivity issues.
  • If the database is being restored on an instance on a different server, everything listed applies, but there may be added security issues as Windows accounts may be different, and they may be in a different Windows domain.
  • One other consideration is the edition of SQL Server the database is being restored on. There are some features that, if used in the database, make the database "Enterprise-only" -- it cannot be restored on a Standard Edition (or lower) SQL Server instance.
  • In SQL Server 2000 and earlier, this is not an issue. In SQL Server 2005, if table or index partitioning is used, the database is "Enterprise-only." In SQL Server 2008, the feature list is:
  • Change data capture
  • Transparent data encryption
  • Data compression
  • Partitioning
All of these require sysadmin privileges to enable except data compression, which can be enabled by a table owner, thus potentially breaking a disaster-recovery plan involving restoring to a Standard Edition instance. You can tell whether any of these features are being used in the database using the DMV sys.dm_db_persisted_sku_features and adjust your disaster-recovery plan accordingly.

Dig Deeper

Just as with the first article in the series on backups, there are lots of facets of restore operations that I didn't have space to cover. Now that you know the basics, however, you can dive into some of the Books Online and blog links for deeper information. The best place to start in Books Online is the topic "Restore and Recovery Overview (SQL Server)". You can also find a lot of information on my blog, starting with the Backup/Restore category.
The main takeaway I'd like you to gain from this article is that to successfully recover a database using backups, you need to practice to make sure you know what to do. You don't want to be learning the syntax for the RESTORE command during a high-pressure disaster-recovery situation. You may also find that your backup strategy does not allow you to recover within your business requirements. Maybe the backups take too long to restore, maybe your log backups are accidentally overwriting each other, or maybe you forgot to back up the server certificate used to enable transparent database encryption in SQL Server 2008.
By far the best way to prepare for disaster is to have a restore plan that lists the steps to go through, and to have a set of scripts that will help identify what backups exist and the order in which to restore them. I always like to say that this should be written by the most senior DBA on the team and tested by the most junior DBA -- to ensure that everyone can follow the steps safely. However, if you're an involuntary DBA, you're going to need to put a plan together yourself and make sure you can follow it.
In the next article, I'll explain how to recover from database corruption if you don't have any backups, and why you might choose to run a repair operation even if you do have backups.
In the mean time, and as always, if you have any feedback or questions, drop me a line -- Paul@SQLskills.com.

Thanks to Kimberly L. Tripp for providing a technical review of this article.
Paul S. Randal is the managing director of SQLskills.com, a SQL Server MVP and Microsoft regional director. He worked on the SQL Server Storage Engine team at Microsoft from 1999 to 2007. Randal wrote DBCC CHECKDB/repair for SQL Server 2005 and was responsible for the Core Storage Engine during SQL Server 2008 development. Randal is an expert on disaster recovery, high availability and database maintenance and is a regular presenter at conferences around the world. He blogs at SQLskills.com/blogs/paul and is on Twitter as @PaulRandal.