0% found this document useful (0 votes)
66 views18 pages

20764C-ENU-Handbook-Module 01

This module describes SQL Server security models including authentication, authorization, and firewall configuration. It covers authenticating connections using Windows, SQL, or Azure Active Directory authentication. It also covers authorizing logins to databases, cross-server authorization, and partially contained databases.

Uploaded by

aruval
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views18 pages

20764C-ENU-Handbook-Module 01

This module describes SQL Server security models including authentication, authorization, and firewall configuration. It covers authenticating connections using Windows, SQL, or Azure Active Directory authentication. It also covers authorizing logins to databases, cross-server authorization, and partially contained databases.

Uploaded by

aruval
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |1 / 18

OF F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T

Contents Part 1 / 15
Module 1: SQL Server Security
Module Overview 1-1
Lesson 1: Authenticating Connections to SQL Server 1-2
Lesson 2: Authorizing Logins to Connect to Databases 1-7
Lesson 3: Authorization Across Servers 1-10
Lesson 4: Partially Contained Databases 1-15

ModuleOverview
Protection of data within your Microsoft® SQL Server® databases is essential and
requires a working knowledge of the issues and SQL Server security features.
This module describes SQL Server security models, logins, users, partially contained
databases, and cross- server authorization.

Objectives
After completing this module, you will understand, and have a working knowledge of:
 SQL Server basic concepts.
 SQL Server connection authentication.
 User login authorization to databases.
 Partially contained databases.
 Authorization across servers.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |2 / 18

Lesson 1 Authenticating Connections to SQLServer


Overview of SQL Server Security
Securables, Principals, and Permissions
Securable: the resource on which the action is to be
performed
Principal: the “someone or something” that needs to
perform the action
Permission: the configuration that allows the action
to be performed.
Example: a network administrator might need to
give users access to view the contents of a folder.
Securable: The folder;
Principal: the user, and the administrator.
Permission: action of the administrator granting
read access to the folder.

Security Hierarchies
inherited permissions can be explicitly overridden at different hierarchy levels, to fine-tune access.
This hierarchical arrangement simplifies permission management in a number of ways:
 Fewer individual permissions need to be granted, reducing the risk of misconfiguration. You can set
the general permissions that are required at the highest level in the hierarchy, and only apply explicit
overriding permissions further down the hierarchy, to handle exceptional cases.
 After the permissions have been set, they can be controlled through group membership. This makes it
easier to manage permissions in environments where new users arrive and existing users leave or
change roles.
Best Practice: When planning a security solution, consider the following best practices:
 Provide each principal with only the permissions they actually need.
 Use securable inheritance to minimize the number of implicit permissions that must be set to enable
the required level of access.
 Use principal containers, such as groups or roles, to create a layer of abstraction between principals
and permissions to access securables. You can then use membership of these groups to control access
to resources via the permissions you have defined. Changes in personnel should not require changes
to permissions.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |3 / 18

SQL Server Authentication


To connect to the SQL Server Database Engine, the
principal must supply authentication information
that matches their stored credential.

Who Performs the Authentication? When you


configure SQL Server, you must choose an
authentication mode for the database engine.
Authentication Modes: Windows®, SQL Server authentication is also known as mixed mode, and Azure
AD authentication.

Windows Authentication
SQL Server checks the provided user name and password against the Windows user details. SQL Server
does not require a password. This is the default authentication mode. Windows user security controls
access to SQL Server. Access is granted based on an access token issued when the user logged in to the
Windows session. Because groups of users can be created in Windows, domain access administration is
simplified. Best Practice: If possible, Windows authentication should be used.

SQL Server Authentication (Mixed Mode)


Mixed mode is the addition of SQL Server authentication to Windows authentication.
SQL Server authentication requires a login when the application is started. The user name and password
are stored within database tables, and so are separate from the Windows authentication. The following
optional policies can be applied:
 Change Password at Next Login. This feature is enabled in SSQ Server Management Studio.
 Password Expiration. You can set a maximum age policy for passwords.
 Windows Password Policy. You can enforce Windows policies for passwords. For example, minimum
and maximum password lengths, and other rules that define minimum standards for passwords. For
example, forcing the user to include capitals, numbers, and punctuation marks in their passwords.
Note:
o If you install SQL Server using mixed mode authentication, setup enables a SQL Server login
called sa. It is important to create a complex password for this login because it has
administrative rights at database server level.
o If you install using Windows authentication mode, then change to mixed authentication later, this
does not enable the sa login.

Azure Active Directory


You use Azure AD to manage user identities for connections to Azure databases in a single place. This can
help you provide integrated authentication policies at both Windows and database level. For further
details about using Azure Active Directory, see Use Azure Active Directory Authentication for authentication with SQL
Database or SQL Data Warehouse http://aka.ms/Wo9lg9

Protocols for Authentication


Windows authentication is typically performed by using the Kerberos protocol. The Kerberos protocol is
supported with SQL Server over the TCP/IP, named pipes, and shared memory network protocols.
The SQL Server Native Access Client (SNAC) provides encrypted authentication for SQL Server logins. If
SQL Server does not have a Secure Sockets Layer (SSL) certificate installed by an administrator, SQL Server
generates and self-signs a certificate for encrypting authentication traffic.
Note: Encrypted authentication only applies to clients running the SQL Server 2005 version
of SNAC or later. If an earlier client that does not understand encrypted authentication tries to
connect, by default SQL Server will allow the connection, but the username and password will be
transmitted in plain text. If this is a concern, you can use SQL Server Configuration Manager to
disallow unencrypted authentication from down-level clients by setting Force Encryption to Yes.
To find information about SQL Server Authentication modes, see
Choose an Authentication Mode http://aka.ms/Lem9ua
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |4 / 18

Azure SQL Database Firewall


The Azure SQL Database Firewall protects your
information by providing access to the IP addresses
you specify.
Firewall Rules
Two levels to configure Azure Firewall Rules:
 Server. You can configure rules that are stored
on the master database to allow principals
access to your server.
 Database. You can configure rules to allow
principals access to individual databases. These
rules are stored on the specific databases. For example, you might want certain principals to be
denied access to a financial database but allow access to a marketing database.
Best Practice: Microsoft recommends using database-level firewall rules. You should
consider using server rules if you have many databases with the same access requirements.
Note: Before proceeding, you need to ask your systems administrators for your outbound
IP address range.
Azure Database Firewall Rules
The initial state for your Azure Database Firewall is to block all access. To enable access, you should go to
the Azure Portal and create one or more server-level and database-level rules containing the IP address
range you are using. You should also specify whether Azure applications can connect to your Azure SQL
Database server.
The following summarizes Azure Database Firewall rule configuration:
 To allow server access, you create a server-level rule containing the IP address range.
 To allow access to a specific database, you create a database-level rule configured as follows:
o Make sure that the IP address the principal is using is outside of the one that is specified in the
server-level rule.
o Create a database-level rule using the IP address of the principal.
o Ensure the IP address of the principal falls within the range specified by the database-level rule.

For more information on how to configure Azure firewall settings, see the Manage firewall rules using the
Azure portal section Azure SQL Database server-level and database-level firewall rules
http://aka.ms/iddzy1

Making a Connection Through the Azure Database Firewall


When a connection is attempted over the Internet, the following process occurs:
1. Server Level. If the client IP address is within a range configured in a server-level rule, the connection
is allowed to your Azure SQL Database Server.
2. Database Level. If the client IP address is not within the server-level range, then the database-level
rules are checked. If the IP address falls within an IP range linked to one of the database-level rules,
then access is granted to all databases that the IP address has been assigned to.
3. Connection Denied. If the client IP address falls outside of both server-level and database-level rules,
the connection will be denied.
Note: Local Device. To access the Azure SQL Database, the firewall on your local device
TCP port 1433 must allow outgoing communications.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |5 / 18

Managing Your Azure Database Firewall


The following sections provide a summary of the methods used to manage your Azure Database Firewall.
Method Comments
Transact-SQL You can execute a query from SQL Server Management Studio or the Classic
Azure Portal. You need to connect to the master database, and then you can
select, create, update or delete firewall rules.
For example, to view firewall rules using Transact-SQL:
SELECT * FROM sys.firewall_rules ORDER BY name;

Viewing Your Microsoft Azure Firewall Rules


For more information about querying Azure firewall settings using Transact-SQL,
see the Manage firewall rules using Transact-SQL section of Azure SQL
Database server-level and database-level firewall rules in the Microsoft Azure
documentation: Azure SQL Database server-level and database-level
firewall rules http://aka.ms/F650g1
Azure To manage your firewall rules using Azure PowerShell, see the Manage firewall rules
PowerShell using Azure PowerShell section of Azure SQL Database server-level and database-
level firewall rules in the Microsoft Azure documentation: Azure SQL Database
server-level and database-level firewall rules http://aka.ms/Szncif
Rest API To manage your firewall rules using REST API, see the Manage firewall rules using
REST API section of Azure SQL Database server-level and database-level firewall
rules in the Microsoft Azure documentation: Azure SQL Database server-level
and database-level firewall rules http://aka.ms/K1fu0d

Troubleshooting Your Azure Database Firewall


Issues that might affect your ability to connect through the Azure Database Firewall include:
 Local Firewall Rules. TCP Port 1433 must be allowed. If you are inside the Azure cloud boundary,
you might have to create rules for additional ports.
 Network Address Translation (NAT). Your local device might use a different IP address to the one
you use to connect to Azure SQL Database. You can go to the portal and configure the Azure
Database Firewall to use the Current Client IP Address.
 Dynamic IP Addresses. In some cases, you might have to ask your Internet Service Provider (ISP) for
the range they use for your device. You can also obtain a static address.
For more detailed information about troubleshooting your Azure Database Firewall, see the
Troubleshooting the database firewall section of Azure SQL Database server-level and database-level
A firewall rules in the Microsoft Azure documentation:

Azure SQL Database server-level and database-level firewall rules http://aka.ms/Gyqdui

For more information about ports beyond 1433 for ADO.NET 4.5, see Ports beyond 1433 for ADO.NET 4.5
in the Microsoft Azure documentation:

Ports beyond 1433 for ADO.NET 4.5 http://aka.ms/Ppycp4


MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |6 / 18

Managing Logins and Policies


You can create logins and configure policy settings by using either Transact-SQL code or SSMS. its
much faster, to use a Transact-SQL script.
Creating Logins with SSMS
To create a login by using SSMS, expand the Security node for the relevant server instance, right-click
Logins, and then click New Login. Complete the details in the Login - New dialog box to configure the
login that you require.
Login Operations
Operation SQL Script Comments
Create CREATE LOGIN
[ADVENTUREWORKS\SalesReps] When you create a login, If you do not specify
Windows Login
FROM WINDOWS the default database option, the default
WITH DEFAULT_DATABASE = [salesdb]; database is set to master.
Create CREATE LOGIN Create and set security Policy for SQL Server
SQL Server DanDrayton
Logins
WITH PASSWORD = 'Pa55w.rd',
Login
CHECK_POLICY = ON,
DEFAULT_DATABASE = [salesdb];
Setting the ALTER LOGIN DanDrayton The full application of account policy is not
Password WITH CHECK_POLICY = OFF, always desirable. When, applications use fixed
Policy for a CHECK_EXPIRATION = OFF; credentials to connect to the server; and do not
Login support the regular changing of login
passwords. it is common to disable password
expiration for those logins
Changing the ALTER LOGIN DanDrayton
Password WITH OLD_PASSWORD = 'Pa55w.rd',
PASSWORD = 'NewPa55w.rd';
Disable Logins ALTER LOGIN DanDrayton DISABLE; If a user is currently logged in, you cannot drop
their login without first ending their session.
Delete Logins DROP LOGIN DanDrayton;
Note: Windows user and group names must be enclosed in square brackets because they contain
a backslash character.
You create SQL Server logins in the same way. There are, however, additional arguments that are only
relevant to SQL Server logins (for example, the PASSWORD argument).
SQL Server Login Security Policy
In a Windows-based environment, administrators can enable policies for Windows users that enforce
password complexity and expiration. SQL Server can enforce similar restrictions for SQL Server logins.
When you create a SQL Server login, you can specify the following options to control how the password
policy is enforced:
 MUST_CHANGE: SQL Server will prompt the user to change their password the next time they log
on. You must ensure that whatever client application the user will use to connect to SQL Server
supports this. The default value for this setting is ON when using the user interface to create a login,
but off when using a Transact-SQL CREATE LOGIN statement.
 CHECK_POLICY = {ON | OFF}: Setting this value to ON enforces the password complexity policy
for this user. The default value for this setting is ON.
 CHECK_EXPIRATION = {ON | OFF}: Setting this value to ON enables password expiration, forcing
the user to change their password at regular intervals. The default value for this setting is ON when
using the user interface to create a login, but off when using a Transact-SQL CREATE LOGIN
statement.
Disabling and Deleting Logins
If logins are not being used for some time, you should disable and re-enable them later. If there is any
chance that a login will be needed again in the future, it is better to disable it rather than drop it.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |7 / 18

Lesson 2 Authorizing Logins to Connect to Databases


After creating a login, you should give that login access to at least one database before they can connect
to the server. Generally, you only need to enable logins to access the databases that they need to work
with. You can do this by creating a database user for the login in each database that it must access.
Granting Access to Databases
 Logins cannot connect to a database to which they have not been granted access.
 Grant access to a login by creating a database user for it using SSMS or Transact- SQL statements.

Note: SSMS. To create a new database user in SSMS, expand the relevant database, expand the
Security node, right-click the Users node, and then click New User. Complete the details in the
Database User - New dialog box to configure the user you require.

You can also create database users by using the CREATE USER statement.

Creating Database Users


SQL Command Notes
USE salesdb; The user is assigned the default
CREATE USER SalesReps schema Sales
FOR LOGIN
[ADVENTUREWORKS\SalesReps] WITH
DEFAULT_SCHEMA = Sales;
CREATE USER DanDrayton FOR No default schema is specified, so the
LOGIN DanDrayton; user will default to the dbo schema
CREATE USER WebUser No default schema is specified, so the
FOR LOGIN schema will be dbo. Also note that the
[ADVENTUREWORKS\WebAppSvcAcct]; username is different to the login
with which it is associated.
Note: The names of Windows logins must be enclosed in square brackets “[…]” because
they contain a backslash “\” character.

Schemas are namespaces that are used to organize objects in the database. If no default schema is
specified when a user is created, then dbo is used.
You can remove users from a database by using the DROP USER statement or SSMS. However, you cannot
drop a database user who owns any securable object (for example, tables or views).

Managing Mismatched Security Identifiers


When you create a SQL Server login, it is allocated both a name and a security identifier (SID). When you
then create a database user for the login, details of both the name and the SID of the login are entered
into the sysusers system table in the database. If the database is then backed up and restored onto
another server, the database user is still present in the database—but there might be no login on the
server that matches it. If you then create a new login with the same name and map as a user in the
database, it will not work. This is because the new login has a different SID to the original login—so it
cannot be added to the database.

To resolve the different SID issue, you need to update the database user to link it to the new login on the
server by using the ALTER USER statement with the WITH LOGIN clause.

Resolving Mismatched SIDs

ALTER USER DanDrayton WITH LOGIN = DanDrayton;

This solves the issue but, if you later restore the database on the same or a different server, the problem
will reoccur. A better way of avoiding the problem is by using the WITH SID clause when you create the
login.
Note: Managing mismatched SIDs, orphaned users (those whose logins are disconnected
when a database is moved to another SQL Server instance), impersonation and delegation are
discussed in a later lesson, Authorization Across Servers.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |8 / 18

Managing dbo and guest Access


While it is generally true that a login cannot access a
database without having been explicitly granted access
through the creation of a database user, there are two
exceptions. Each SQL Server database includes two
special database users—dbo and guest.

dbo User
The dbo user is a special user who has permissions to
perform all activities in the database. Any member of the sysadmin fixed server role (including the sa user
when using mixed mode authentication) who uses a database is mapped to the special
database user called dbo. You cannot delete the dbo database user and it is always present in every
database.

Database Ownership
Like other securable objects in SQL Server, databases also have owners—these are mapped to the dbo
user.
Changing the Database Owner
ALTER AUTHORIZATION ON DATABASE::salesdb
TO [ADVENTUREWORKS\Database_Managers];

Any schema created by a login mapped to the dbo user will automatically have dbo as its owner. By
default, objects within a schema have their owner set to NULL and inherit the owner of the schema in
which they are defined. Owners of objects have full access to the objects and do not require explicit
permissions before they can perform operations on those objects.

guest User
The guest user account enables logins that are not mapped to a database user in a particular database to
gain access to that database. Login accounts assume the identity of the guest user when the following
conditions are met:
 The login has access to SQL Server, but not the database, through its own database user mapping.
 The guest account has been enabled.
You can enable the guest account in a database to give anyone with a valid SQL Server login access to it.
The guest username is automatically a member of the public role. (Roles will be discussed in a later
module.)

A guest user accesses a database in the following way:


 SQL Server checks to see whether the login that is trying to access the database is mapped to a
database user in that database. If it is, SQL Server grants the login access to the database as that
database user.
 If the login is not mapped to a database user, SQL Server then checks to see whether the guest
database user is enabled. If it is, the login is granted access to the database as guest. If the guest
account is not enabled, SQL Server denies access to the database for that login.
You cannot drop the guest user from a database, but you can prevent it from accessing the database by
using the REVOKE CONNECT statement. Conversely, you can enable the guest account by using the
GRANT CONNECT statement.

Enabling and disabling the guest Account


REVOKE CONNECT FROM guest;
GRANT CONNECT TO guest;
Note: By default, the guest user is enabled in the master, msdb, and tempdb databases.
You should not try to revoke the guest access to these databases.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |9 / 18

Authorizing Logins and User Tokens


Security tokens are used by SQL Server to work out which
permissions to apply.

Security Token Service


The Security Token Service (STS) is an identity provider
program that creates and issues security tokens using a
variety of methods, including Kerberos. Windows Identity
Foundation (WIF) allows you to build and use your own
security tokens. STS allows a single sign-on for multiple
services and applications—the security data is held in one place or in a chain of locations.
Briefly, instead of SQL Server directly authorizing a principal such as a client application or user, the
principal is passed to an STS—such as WIF.
For example, for a Windows user attempting to connect to a SQL Server database:
1. Windows login service is redirected to WIF.
2. WIF will build a security token based on the records it holds about the user.
3. The principal (or login service) then presents the token to SQL Server to verify that the principal is
authorized for access and, if correct, will create a session for the principal.
4. Once the connection is made, then SQL Server will create a list of all security tokens for each
Windows group the user belongs to. This is a recursive procedure so that nested Windows groups are
identified.
5. If the user context changes to another database, a further list of security tokens is made. In other
words, SQL Server and WIF will make sure the user has access to the new database. If the user has
permission to access the new database, then the security token is added to the token list. As in the
previous step, the collection and building of the token list is repeated recursively.
6. The two lists contain security tokens representing all of the principals for the user, and each contains
a record of deny or grant permissions. This is the Active Permission Set.
Strong encryption is used throughout this process to avoid compromising security.
For more information about WIF, see Windows Identity Foundation in the Microsoft .NET documentation:
Windows Identity Foundation https://aka.ms/U42695
Viewing Security Tokens
You can view security tokens using sys.login_token and sys.user_token system views. The following code
examples describe and show how each of these views is used:
Login tokens are created to authorize login credentials. The following code returns a row for each server
principal that is part of the login token:

Viewing Login Tokens


SELECT * FROM sys.login_token;

User tokens are created to authorize user credentials. The following code returns a row for each server
principal that is part of the user token:
Viewing User Tokens
SELECT * FROM sys.user_token;

For more information about: sys.login_token, see sys.login_token (Transact-SQL) in sys.login_token (Transact-SQL)
http://aka.ms/Qmwvd2
For more information about sys.user_token, see sys.user_token (Transact-SQL) in Microsoft Docs:
sys.user_token (Transact-SQL) http://aka.ms/Lx2e6w
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |10 / 18

Lesson 3 Authorization across Servers


Linked Servers Security
You can execute distributed queries on OLE DB data sources
that are external to the current SQL Server instance. For
example, you might wish to execute Transact-SQL against
tables in another SQL Server instance, Microsoft Excel®,or
other database products. You use the OLE technology to
manage connections between diverse data sources.
As the data sources might be out of your security domain,
you need to ensure that you understand how linked servers
operate and how to secure any connections between them.
The benefits of linked servers are as follows:
 External Data Access. Enables access to data that is external to the SQL Server instance.
 Diverse External Data Sources. You can work with many types of data sources within your
organization.
 Standardized Method. The way you interact with other data sources is standardized.

Linked Server Objects


The following objects are required to use linked servers with OLE DB:
 Provider. This is a dynamic-link library (DLL) file that manages connections to a specific data source.
 Data Source. The object that contains the data you wish to work with. They are usually databases but
they can also be other data sources, such as spreadsheets.
Note:
o The Native Client OLE DB provider is the SQL Server provider.
o SQL Server has been tested against the Native Client OLE DB provider and other providers.
The Open Database Connectivity (ODBC) provider can enable secure connections to many other
data sources.

Linked Server Configuration


So that distributed queries reach the correct data source and return the data, the deployment of linked
servers requires the building of three tiers:
1. Client Tier. The application that requires the data. This is where you will create the distributed
queries and present them to your SQL Server instance.
2. Server Tier. Your SQL Server instance directs the query to the relevant database via the OLE DB
provider DLLs—for example, a SQL Server database, Oracle and Microsoft Access. ODBC enables
connections to many other data sources, including Microsoft Excel.
3. Database Server Tier. These are the actual data sources. Note that you can use multiple SQL Server
databases for your distributed query.
Note: Third-party OLE DB providers must have a read and execute SQL Server service
account for all folders and subfolders in which the .dll is located.
Linked Server Definitions
During the configuration of a linked server, you need to register connection and source data information
with the SQL Server instance. Once set up, data sources can be referenced in distributed queries by a
single name.
You can use SQL Server Management Studio to add, change and remove linked server connection details:
 Create. To set up a linked server, you use Object Explorer. Open the SQL Server instance, right-click
Server Objects, select New, then select Linked Server. You can then enter details in the New Linked
Server dialog.
 View or Amend. Select the linked server, right-click and select Properties. The Linked Server
Properties dialog is displayed for you to change or view details.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |11 / 18

 Delete. To delete a linked server, you right-click the server and click Delete.
Stored procedures and catalog views can also be used to manage linked server connections:
 sp_addlinkedserver. Creates a linked server definition.
 sys.servers. You can query the system catalog views to return linked server details.
 sp_dropserver. Deletes a linked server definition and can be used to remove references to remote
servers. Note that you can also drop remote logins using this stored procedure, as shown in the
following example.
 sp_addlinkedsrvlogin and sp_droplinkedsrvlogin. These stored procedures allow you to map and
remove logins between your SQL Server instance and other server security accounts. See below for
further details.
The following code example shows how the sp_addlinkedserver and sp_dropserver can be used to
create and drop a linked server for RemoteServer:
Create and Drop a Linked Server Connection
-- Create linked server ---Drop linked server and
remove the default login
USE master
mapping
GO
USE master
EXEC sp_addlinkedserver
GO
@server='RemoteServer',
EXEC sp_dropserver
@srvproduct='', 'RemoteServer', ‘droplogins’;
@provider='SQLOLEDB', GO
@datasrc='r:\datasource\RemoteServer';
GO
Note: Fully Qualified Naming. The four-part name format is required in a distributed query
when referring to a linked server: linked_server_name.catalog.schema.object_name.
Linked Server Security
For linked server connections to operate, a login mapping must be created. You can use the system stored
procedure sp_addlinkedsrvlogin to map logins. You can drop a connection using
sp_droplinkedsrvlogin. Note that you can also use sp_dropserver to remove mapped logins as
described above.
When you run a stored procedure that queries a remote server or a distributed query linked server, there
must be a mapping between the requesting instance and the data sources.
Note: Windows Authentication Mode should be used if possible. However, some data
sources might not allow Windows Authentication Mode—for these, you can set up a Windows
authenticated login locally and map this to a specific login on the data source.
Create and Drop a Mapped Login to a Remote Server
-- Add a remote login mapping
USE master
GO
EXEC sp_addlinkedsrvlogin 'RemoteServer', 'false', 'LocalDomain\LocalUserName',
'RemoteUserName', 'Pa55w.rd';
GO

-- Connect all local logins to a linked server


USE master
GO
EXEC sp_addlinkedsrvlogin 'RemoteServer';
GO

-- Drop login mapping


USE master
GO
EXEC sp_droplinkedsrvlogin 'RemoteServer', NULL;
GO

You can test linked server connections in SQL Server Management Studio by right-clicking on the linked
server and clicking Test Connection in the Properties dialog box.
For more information about linked servers, see: Linked Servers (Database Engine) http://aka.ms/jmfec7
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |12 / 18

Typical "Double-Hop" Problem


A common feature in applications is that they
need to access data from back-end data
sources.
Authentication can fail because the second
and subsequent connections do not have the
correct authentication details. Typically, this
might occur when a distributed query is
executed from a linked database that
accesses other servers using mapped logins.

For example, consider a Windows user,


USER1, on an application that connects to a
SQL Server instance, SQL1. SQL1 has a
linked server SQL2 complete with mapped
logins. USER1 wants to
execute a distributed query against SQL2 but the query fails because USER1 Windows Authentication fails
on SQL2.
This is the “double-hop” problem. To solve this, we need to consider how to make sure that SQL2 is aware
that USER1 has Windows Authentication that allows the query to execute. Delegation is required so that
SQL1 forwards the credentials of USER1 to SQL2. Delegation allows SQL1 to impersonate the user so that
SQL2 will run the distributed query.

Delegation Requirements
Client. The following list summarizes the client (USER1) requirements:
o Access Permissions. USER1 must have Windows Authenticated logins for SQL1 and SQL2.
o Client Device. Must use TCP/IP or named pipes.
o Active Directory. The Active Directory Account is sensitive and cannot be delegated property
must not be checked for USER1.
Middle Tier. The following list summarizes the SQL1 requirements:
o Domain Admin. SQL1 requires a registered Service Principal Number (SPN).
o Delegation. The active SQL Server account must be trusted for delegation. See below for more
details.
o Server Device. Must use TCP/IP or named pipes.
o Linked Server. SQL2 must be configured as a linked server on SQL1.
Database Tier. The following list summarizes the SQL2 requirements:
o Server Device. Must use TCP/IP or named pipes.
o Domain Admin. SQL2 requires a registered SPN.

For more information about double-hop, see Configuring Linked Servers for Delegation in Microsoft
TechNet:

Configuring Linked Servers for Delegation https://aka.ms/Vfwuxk


MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |13 / 18

Impersonation vs. Delegation


Impersonation is a method used by services to control the
client access to resources within a domain—for
example, local files. Delegation is a method that allows a
client to execute and access resources on other
devices—for example, shared files.

Delegation
You have already seen how delegation works in the
previous topic Typical “Double-Hop” Problem. In this case, a SQL Server request used a forward identity to
execute on a remote server.

Impersonation
Impersonation is carried out on the remote server in a similar way to if it were executed on the local
server.
There are three methods used for impersonation:
 Windows Authentication. This uses a Windows identity token using Kerberos or the Security
Support Provider Interface. The supplied identity token can then be cached on the service for use in
impersonation.
 Service-For-User (S4U). Impersonation is carried out using a Windows identity token obtained from
Kerberos extensions. S4U is used when clients use non-Windows authentication.
Note: The process account must have the Act as part of the operating system access right.
 LogonUser API. An identity token can be requested and obtained from the LogonUser API. You can
use this Windows API to access remote services but delegation trust is not used.

Impersonation in a Database Engine Instance


To test security configurations, you could impersonate a server login or a database user with the EXECUTE
AS Transact-SQL command. Using EXECUTE AS switches the security context of the connection to that of
the login or user specified in the statement. To return to the connection’s original security context, you
use the REVERT Transact-SQL command.
The following examples demonstrate how to use EXECUTE AS to impersonate a login, and then a user:

EXECUTE AS Example
SELECT SUSER_SNAME(), USER_NAME();

EXECUTE AS LOGIN = 'MyLogin'


SELECT SUSER_SNAME(), USER_NAME();
REVERT

EXECUTE AS USER = 'DemoUser'


SELECT SUSER_SNAME(), USER_NAME();
REVERT

SELECT SUSER_SNAME(), USER_NAME();

For more information about using EXECUTE AS, see EXECUTE AS (Transact-SQL) in Microsoft Docs:

EXECUTE AS (Transact-SQL) http://aka.ms/Kho6sq


MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |14 / 18

Working with Mismatched Security Identifiers


Mismatched security identifiers (SIDs) can occur when you
move a database from one SQL Server instance to another.
SIDs on the source SQL Server instances will not match the
SIDs on the destination database; the users are orphaned if
their logins are affected. Users with mismatched SIDs might
not have usable logins.
This is because logins are associated with SIDs and the SIDs
on the destination SQL Server instance might not be the
same as those recognized by the moved database. If the
destination is in a different domain than the source database, then mismatched SIDs and orphaned users
might occur.
Note: It is recommended to use Windows authentication whenever possible.
Resolving Orphaned Users
The following steps describe how you can resolve mismatched IDs and orphaned users:
1. Search for Orphaned Users. On the destination server, run the following code to return a list of
orphaned users:
This Transact-SQL returns any orphaned users for MyMovedDatabase:

Orphaned Users
USE <MyMovedDatabase>;
GO;
SELECT dp.type_desc, dp.SID, dp.name AS user_name
FROM sys.database_principals AS dp
LEFT JOIN sys.server_principals AS sp
ON dp.SID = sp.SID
WHERE sp.SID IS NULL
AND authentication_type_desc = 'INSTANCE';

2. Resolve Orphaned Users. If any orphaned users are returned, you need to create logins for them
with Transact-SQL as in the following code example:
To resolve orphaned users, you use the CREATE LOGIN statement with the SID for the orphaned user:

Resolve Orphaned Users


-- This code will relink the orphaned user
USE master
GO
CREATE LOGIN [<domainName\loginName>]
WITH SID = <SID>;
GO

3. Database Owner (dbo). You can use Transact-SQL to relink an orphaned dbo:
To change dbo to MyUser in the destination database, you use the ALTER AUTHORIZATION statement.

Change dbo
ALTER AUTHORIZATION ON DATABASES::MyDatabase TO MyUser;
GO

Guests and Windows Group Members


The guest account is not mapped to a SQL Server login.
A SQL Server login that was sourced from a Windows account can access a database if the account is part
of a Windows group and is also a database user.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |15 / 18

Lesson 4 Partially Contained Databases


The containment feature in SQL Server reduces the reliance a database has on the SQL Server instance
that hosts it. This is very useful for optimizing the moving of a database to another SQL Server instance.
This lesson discusses the containment feature, how it is deployed, and the considerations for using
partially contained databases.

Introduction to Partially Contained Databases


Typically, databases in a SQL Server instance have
dependencies on server-level resources—most
typically logins, but often on other resources too. This
relationship between databases and the server
instance on which they are hosted enables a
hierarchical approach to security and management.
However, there are some scenarios where it would be
useful to completely isolate a database and its
management from the server on which it resides.
For example:
 When it is necessary to move databases between different SQL Server instances; entities
that are external to the database, such as logins, are not moved along with the database.
 When a database is in development and the developer does not know which instance will ultimately
host the database.
 When a database that participates in an Always On availability group is mirrored on multiple server
instances, and it is useful to be able to failover to a secondary instance without having to synchronize
the server-level logins required to access the database.

A contained database is one that is hosted on an instance of SQL Server, but which has no dependencies
on the server instance. Because there are no dependencies, you can move the database between servers,
or use it in availability group scenarios, without having to consider external factors, such as logins.

Containment Levels
Noncontained databases rely on their SQL Server instance for many features such as metadata,
authentication, collations, and resources. Most SQL Server databases are noncontained. Partially contained
databases have fewer dependencies on the hosting SQL Server instance. Partially contained databases are
mostly managed separately from the database engine instance. Partially contained databases allow the
use of some uncontained resources that are managed by the SQL Server instance and are outside of the
particular database boundary.

Note: There is one further level of database containment: full containment. Fully contained
databases hold all the metadata, data objects, data, database object logins, user accounts, and
other resources they need to operate—this is usually held in the SQL Server Instance. These
databases are fully stand-alone. Full containment is not supported in SQL Server 2017.
The following table provides a summary of terms and their definitions:

Term Description
Database Boundary The boundary between a partially contained database and other databases, and the
SQL Server instance.
Contained Attribute Refers to an element that is held within the database boundary.
Uncontained An element that is not held within the database boundary.
Contained User This type of user is authenticated by the partially contained database.
Windows Principals The partially contained database will use Windows to authenticate these users—
they are trusted and do not require logins to be set up in the master database.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |16 / 18

Characteristics of Contained Databases


Contained databases include the following characteristics that isolate them from a server instance:
 Contained databases store the metadata that defines the database. This information is usually stored
only in the master database but, in a contained database, it is also stored in the contained database
itself.
 All metadata uses the same collation settings.
 The database contains users and can authenticate those users without reference to SQL Server logins.
Authentication can be performed by the database itself, or by trusting users that have been
authenticated by Windows.

Enabling Database Containment


To use contained databases, you must enable contained database authentication at the level of the server
instance. You can do this either by using the sp_configure stored procedure to enable the contained
databases authentication option, or by setting the Enable Contained Databases option to True on the
Advanced page of the Server Properties window in SSMS.

Creating and Converting Partially Contained Databases


After the SQL Server instance has been enabled for containment, you can use either Transact-SQL or SSMS
to enable or disable containment on new or existing databases.
In SSMS, you toggle containment using the Containment Type drop-down in the Options page of the
Database Properties dialog box.
The following code shows how you can create a new partially contained database using CREATE Transact-
SQL:
Creating Partially Contained Database

CREATE DATABASE MyDatabase CONTAINMENT = PARTIAL;

You can also change the containment level of an existing database; you can use the CONTAINMENT
parameter of the ALTER DATABASE Transact-SQL statement to enable or disable containment.
The following code shows how to enable or disable containment in an existing table:

Alter Containment
-- Convert a database to partial containment
ALTER DATABASE MyDatabase SET CONTAINMENT = PARTIAL;

-- Disable off containment


ALTER DATABASE MyDatabase SET CONTAINMENT = NONE;

Contained Users
After creating a contained database, you can create contained users for that database. These users can be
one of two types:
 Users with associated password. These users are authenticated by the database; the user’s password is
stored in the database metadata.
 Users that are mapped to Windows user accounts. These users exist only in the database, with no
associated server-level login, and do not require the user to maintain a separate password. Instead of
performing its own authentication, the database trusts Windows authentication.
You create contained users by using the CREATE USER statement in the context of a contained database.
For more information about contained databases, see Contained Databases in Microsoft Docs:

Contained Databases http://aka.ms/F30zfd


MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |17 / 18

Considerations for Using Partially Contained Databases


This topic explores considerations for using partially contained databases.

Benefits of Using Partially Contained


Databases
Moving a Database to Another Host
The primary use of partially contained databases is
to simplify moving the database to another SQL
Server instance—for example, quick and simple
failover for business critical databases. During the
movement of a noncontained database to a new
host, it is possible to break the mapping between
users and their logins, creating orphaned users. As logins and users are held on the contained database,
this is less likely to happen.
Note: To facilitate moving contained databases, you need to document the external
elements that are required for the database to function outside of the current SQL Server
instance. For example, a related database might need to be noted, in addition to the relationship
details. Similarly, external settings need to be identified and documented.

Administration
To manage database settings for a non contained database, an administrator will need sysadmin
privilege to change instance level settings. In a partially contained database, the administrator will have
more control over their own database. Administrators might still require access to non contained
elements.

Partially Contained Databases and Always On


You can use Always On Availability Groups to optimize failover. Partially contained databases are more
independent than uncontained databases on the SQL Server instance. As contained users can connect
directly to the contained database, and then to the failover database, availability is improved. The
uncontained elements can be documented and scripted, making recovery faster and more efficient.
Contained elements are moved with the database. You can find out more about Always On Availability
Groups in Overview of Always On Availability Groups (SQL Server) and Prerequisites, Restrictions, and
Recommendations for Always On Availability Groups in Microsoft Docs:

Overview of Always On Availability Groups (SQL Server) http://aka.ms/Hgybtz


Prerequisites, Restrictions, and Recommendations for Always On Availability Groups
http://aka.ms/O18k7a

Database Development
Development of new databases will take place away from the live environment. By using partially
contained databases, the developer can evaluate the effect that instance level elements might have on the
database.
MOC 20764C | Administering a SQL Database Infrastructure | Module 1 – SQL Server Security |18 / 18

Considerations When Using Partially Contained Databases


Some of the features and issues mentioned in the following list might not be drawbacks in partially
contained databases and could be deployed or fixed by release. However, when designing or using
partially contained databases, they should be considered and possibly documented for migration, failover
or other database movements.

The following considerations need to be made when designing, developing, or using partially contained
databases:
1. Cross Database Queries. Users with the same name and password on different partially contained
databases are not the same user.
2. ALTER DATABASE. Use the current option, ALTER DATABASE CURRENT.
3. Change Data Capture (CDC). CDC is not supported in partially contained databases.
4. Change Tracking (CT). CT is not supported in partially contained databases.
5. Password Policy. CREATE USER does not support bypassing the password policy. If the partially
contained database does not have a password policy, this can cause problems after migration.
6. Synonyms. Some external dependencies might be omitted and cause issues when a partially
contained database is moved.
7. Connection Strings. You must specify the database name in application connection strings.
8. Numbered Procedures. Not supported in partially contained databases.
9. Temporary Procedures. Not supported in partially contained databases.
10. Replication. Not operational in partially contained databases.
11. Collation. Partially contained databases do not rely on tempdb to hold collation details in the SQL
Server instance. Therefore, code that uses explicit collation might need to be altered to use
CATALOG_DEFAULT and not DATABASE_DEFAULT. Schema-bound objects are dependent on
collation changed built-in functions.
12. IntelliSense. An SSMS connection to a partially contained database with a contained user login does
not wholly support this feature.
13. SQL Server Data Tools (SSDT). SSDT is not aware of containment and will not inform you if
containment is not adhered to.
For further information about contained databases, see Contained Database Users – Making Your
Database Portable, Contained Database Collations, and Migrate to a Partially Contained Database in
Microsoft Docs:
Contained Database Users - Making Your Database Portable http://aka.ms/aaew1r
Contained Database Collations http://aka.ms/Cw48th
Migrate to a Partially Contained Database http://aka.ms/Udr653

You might also like