Portcullis Labs » BLH https://labs.portcullis.co.uk Research and Development en-US hourly 1 http://wordpress.org/?v=3.8.5 MS SQL Server audit: Surface area reduction (part 2) https://labs.portcullis.co.uk/blog/ms-sql-server-audit-surface-area-reduction-part-2/ https://labs.portcullis.co.uk/blog/ms-sql-server-audit-surface-area-reduction-part-2/#comments Thu, 15 Feb 2018 20:27:39 +0000 https://labs.portcullis.co.uk/?p=3384 Continuing on from part 1, we will look other benchmark settings that will help to reduce the surface area of attack. Other settings There are a number of other settings in the Center for Internet Security (CIS) Security Benchmark for SQL Server relating to surface area reduction that should be considered: Set is_trustworthy settings for […]

The post MS SQL Server audit: Surface area reduction (part 2) appeared first on Portcullis Labs.

]]>
Continuing on from part 1, we will look other benchmark settings that will help to reduce the surface area of attack.

Other settings

There are a number of other settings in the Center for Internet Security (CIS) Security Benchmark for SQL Server relating to surface area reduction that should be considered:

  • Set is_trustworthy settings for each database in sys.databases to off (2.10 in CIS SQL Server 2008R2; 2.9 in CIS SQL Server 2012)
  • Disable unnecessary SQL Server protocols (2.11 in CIS SQL Server 2008R2; 2.10 in CIS SQL Server 2012)
  • Configure SQL Server to use non-standard ports (2.12 in CIS SQL Server 2008R2; 2.11 in CIS SQL Server 2012)
  • Set the “Hide Instance” option to Yes for Production SQL Server instances (2.13 in CIS SQL Server 2008R2; 2.12 in CIS SQL Server 2012)
  • Disable the sa Login Account by setting is_disabled in sys.server_principals to yes where sid is 0×01 (2.14 in CIS SQL Server 2008R2; 2.13 in CIS SQL Server 2012)
  • Rename the sa Login Account (2.15 in CIS SQL Server 2008R2; 2.14 in CIS SQL Server 2012)

Set is_trustworthy setting is off for each database

Using the catalog view of databases (sys.databases), check whether the database is trusted or not using the “is_trustworthy_on”. Here we want to ensure that databases are considered not trusted and set to disabled (0).

Note: The msdb database is excluded as disabling the trustworthy setting may cause unexpected behaviour in SQL Server components that use information from the msdb database.

A query can be constructed as follows:

SELECT name FROM sys.databases WHERE is_trustworthy_on = 1 AND name != 'msdb' AND state = 0;

The Trustworthy setting can also be observed using SQL Server Management Studio.

  • Within the Object Explorer, navigate to the SQL Server Instance and expand the path to “Databases”
  • Right-click on each database under ‘Databases’ and ‘Databases\System databases’ and select properties
  • Click on “Options” page and scroll down in the right pane to “Miscellaneous” where “Trustworthy” is seen
Trustworthy option for database in SQL Server Management Studio
image-3385

Trustworthy option for database in SQL Server Management Studio

Disable unnecessary SQL Server protocols

Ideally the number of SQL Server protocols enabled should be reduced. It is noted that CIS Security Benchmark do not score this particular issue.

The list of SQL Server Protocols can be found in SQL Server Configuration Manager. To see the settings:

  • Go to the SQL Server Network Configuration in object explorer and navigate to “Protocols for”
  • Ensure that only required protocols are enabled

Note: Microsoft does not specify exactly which protocols should be disabled. However, the setting for a default installation of SQL Server 2008R2 for example appears to be.

  • NP (Named Pipes) – Disabled
  • SM (Shared Memory) – Enabled
  • TCP – Enabled
  • Via – Disabled

The following is query that performs a check on the protocols by checking the registry entry for each of the 4 possible protocols, NP (Named Pipes), SM (Shared Memory), TCP and Via. Note: It makes 4 separate queries for each protocol by finding whether registry entry is enabled or not with the results combined together using a union.

DECLARE @InstanceName nvarchar(50)
DECLARE @MajorVersion decimal
DECLARE @RegKey_Instance nvarchar(500)
DECLARE @RegValue_Instance VARCHAR(100)

DECLARE @RegKey nvarchar(500)
DECLARE @Value_Sm int
DECLARE @Display_Sm VARCHAR(20)
DECLARE @Value_Np int
DECLARE @Display_Np VARCHAR(20)
DECLARE @Value_TCP int
DECLARE @Display_TCP VARCHAR(20)
DECLARE @Value_Via int
DECLARE @Display_Via VARCHAR(20)

-- Get the Instance Name. Default is 'MSSQLSERVER'
SET @InstanceName=CONVERT(nVARCHAR,isnull(SERVERPROPERTY('INSTANCENAME'),'MSSQLSERVER'))

-- Get the Major version number. 8=SQL2000, 9=SQL2005, 10=SQL2008, 11=SQL2012
-- Convert first 2 characters ('8.', '9.', '10', '11'). Convert to Decimal
SET @MajorVersion=CONVERT(decimal,CONVERT(varchar(2),(SERVERPROPERTY('ProductVersion'))))

-- Get the RegKey for Instance Name (e.g. 'MSSQLSERVER')
SET @RegKey_Instance='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL'

-- Get the RegValue for Instance Name (e.g. 'MSSQL10_50.MSSQLSERVER')
EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey_Instance,
  @value_name = @InstanceName,
  @value = @RegValue_Instance OUTPUT

-- Get the RegKey for SM (Shared Memory) and whether protocol is enabled
SET @RegKey='SOFTWARE\Microsoft\Microsoft SQL Server\'+@RegValue_Instance+'\MSSQLServer\SuperSocketNetLib\Sm'
EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'Enabled',
  @value = @Value_Sm OUTPUT

EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'DisplayName',
  @value = @Display_Sm OUTPUT

-- Get the RegKey for Np (Named Pipes) and whether protocol is enabled
SET @RegKey='SOFTWARE\Microsoft\Microsoft SQL Server\'+@RegValue_Instance+'\MSSQLServer\SuperSocketNetLib\Np'
EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'Enabled',
  @value = @Value_Np OUTPUT

EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'DisplayName',
  @value = @Display_Np OUTPUT

-- Get the RegKey for TCP and whether protocol is enabled
SET @RegKey='SOFTWARE\Microsoft\Microsoft SQL Server\'+@RegValue_Instance+'\MSSQLServer\SuperSocketNetLib\TCP'
EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'Enabled',
  @value = @Value_TCP OUTPUT

EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'DisplayName',
  @value = @Display_TCP OUTPUT

-- Get the RegKey for Via and whether protocol is enabled
SET @RegKey='SOFTWARE\Microsoft\Microsoft SQL Server\'+@RegValue_Instance+'\MSSQLServer\SuperSocketNetLib\Via'
EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'Enabled',
  @value = @Value_Via OUTPUT

EXECUTE xp_regread
  @rootkey = 'HKEY_LOCAL_MACHINE',
  @key = @RegKey,
  @value_name = 'DisplayName',
  @value = @Display_Via OUTPUT

SELECT @Display_Np as DisplayName, @Value_Np as Enabled
UNION SELECT @Display_Sm, @Value_Sm
UNION SELECT @Display_TCP, @Value_TCP
UNION SELECT @Display_Via, @Value_Via

The following is a sample result from a SQL Server 2008R2 database instance:

DisplayName          Enabled
-------------------- -----------
Named Pipes                    0
Shared Memory                  1
TCP/IP                         1
VIA                            0

Check port is running for SQL Server

An ideal practice is to configure the SQL server instance to not use the default TCP port of 1433. Using a non-default port helps protect the database from attacks directed to the default port. It is noted that CIS Security Benchmark do no score this particular issue.

This can be checked using netstat and looking for port 1433 in command prompt:

C:\>netstat -ano

Or with PowerShell:

C:\>netstat -ano | select-string 1433.+listening

Alternatively, SQL Server Configuration Manager can be used to see what port is set:

  • Go to the SQL Server Network Configuration in object explorer and navigate to “Protocols for”
  • Right-click on “TCP”
  • Click on the “IP Protocols” tab
  • Observe the IP address and port that has been set

You should also ensure the interface for each IP address (particularly Internet interface) is not enabled.

A query that uses the registry settings for the TCP service used by SQL Server can be made and the port returned as follows:

DECLARE @InstanceName nvarchar(50)
DECLARE @RegKey VARCHAR(100)
DECLARE @PortNumber VARCHAR(20)

-- Get the Instance Name. Default is 'MSSQLSERVER'
SET @InstanceName=CONVERT(nVARCHAR,isnull(SERVERPROPERTY('INSTANCENAME'),'MSSQLSERVER'))

SET @RegKey = 'SOFTWARE\MICROSOFT\MSSQLServer\'+@InstanceName+'\Supersocketnetlib\TCP'
EXEC xp_regread
  @rootkey='HKEY_LOCAL_MACHINE', @key=@RegKey,
  @value_name='Tcpport', @value=@PortNumber OUTPUT

SELECT @InstanceName as Instance, @PortNumber as Port

Hidden option

Another good practice is to configure SQL Server instances within production environments as hidden to prevent advertisement by the SQL Server Browser service.

The “Hide Instance” state can be found in SQL Server Configuration Manager. To see the settings:

  • Go to the SQL Server Network Configuration in object explorer and navigate to “Protocols for”
  • Right-click “Protocols for”, and then select “Properties”
  • On the “Flags” tab, observe the “Hide Instance” box
  • In the “Hide Instance” box, select Yes to enable hiding the server instance

The following query can be used to determine if the server instance is hidden:

DECLARE @InstanceName nvarchar(50)
DECLARE @MajorVersion decimal
DECLARE @RegKey_Instance nvarchar(500)
DECLARE @RegValue_Instance VARCHAR(100)</pre>
DECLARE @RegKey nvarchar(500)
DECLARE @Value int

-- Get the Instance Name. Default is 'MSSQLSERVER'
SET @InstanceName=CONVERT(nVARCHAR,isnull(SERVERPROPERTY('INSTANCENAME'),'MSSQLSERVER'))

-- Get the Major version number. 8=SQL2000, 9=SQL2005, 10=SQL2008, 11=SQL2012
-- Convert first 2 characters ('8.', '9.', '10', '11'). Convert to Decimal
SET @MajorVersion=CONVERT(decimal,CONVERT(varchar(2),(SERVERPROPERTY('ProductVersion'))))

-- Get the RegKey for Instance Name (e.g. 'MSSQLSERVER')
SET @RegKey_Instance='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL'

-- Get the RegValue for Instance Name (e.g. 'MSSQL10_50.MSSQLSERVER')
EXECUTE xp_regread
@rootkey = 'HKEY_LOCAL_MACHINE',
@key = @RegKey_Instance,
@value_name = @InstanceName,
@value = @RegValue_Instance OUTPUT

-- Get the RegKey for SM (Shared Memory) and whether protocol is enabled
SET @RegKey='SOFTWARE\Microsoft\Microsoft SQL Server\'+@RegValue_Instance+'\MSSQLServer\SuperSocketNetLib'
EXECUTE xp_regread
@rootkey = 'HKEY_LOCAL_MACHINE',
@key = @RegKey,
@value_name = 'HideInstance',
@value = @Value OUTPUT

SELECT @InstanceName as 'InstanceName', @Value as 'HideInstance'

Check sa account has been disabled

A good practice is to have the widely known system admin account sa disabled. Enforcing this control reduces the probability of an attacker executing brute force attacks.

The following query shows the name of the system admin account, which sa by default and whether it is disabled:

SELECT name, is_disabled
FROM sys.server_principals
WHERE sid = 0x01;

Check sa account has been renamed

A good practice is to have the widely known system admin account sa disabled. It is more difficult to launch password-guessing and brute-force attacks against the sa account if the username is not known.

The following query lists the name of the system admin account:

SELECT name
FROM sys.server_principals
WHERE sid = 0x01;

Summary

In this article, you have seen a few more settings that can be used to configure to reduce the surface area of attack and improve the security of the SQL Server following good practices and the CIS Security Benchmark.

You can audit manually looking at SQL Server Management Studio and SQL Server Configuration Manager. You can also create a query that will read the catalog information for the databases and the registry to gather the information about the server instance.

The post MS SQL Server audit: Surface area reduction (part 2) appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/ms-sql-server-audit-surface-area-reduction-part-2/feed/ 0
NOPC version 0.4.7 released https://labs.portcullis.co.uk/blog/nopc-version-0-4-7-released/ https://labs.portcullis.co.uk/blog/nopc-version-0-4-7-released/#comments Wed, 28 Oct 2015 14:14:21 +0000 https://labs.portcullis.co.uk/?p=5355 NOPC, the Nessus-based offline patch checker for Linux distributions and UNIX-based systems has had some changes made and been made available in our tools section. This article discusses the new features in detail and provides some working examples. Updated features and bug fixes Improvements to the interactive mode (e.g. asking for what format for results […]

The post NOPC version 0.4.7 released appeared first on Portcullis Labs.

]]>
NOPC, the Nessus-based offline patch checker for Linux distributions and UNIX-based systems has had some changes made and been made available in our tools section. This article discusses the new features in detail and provides some working examples.

Updated features and bug fixes

  • Improvements to the interactive mode (e.g. asking for what format for results to be displayed)
  • Hidden systems/distributions now displayed and re-ordered (see Usage)
  • Script consolidated back to one file
  • Testing script with shellcheck
  • Default location set for nasl and plugin directory

Usage

$ nopc.sh -?
/opt/bin/nopc.sh [Options]
Version: nopc.sh  0.4.7d
OPTIONS:
  -?: This usage page
  -d: Location of Nessus Plugins directory
  -n: Location of nasl program directory
  -s: System Type (with optional arguments)
  -l: Output Type
  -v: Version of NOPC

Where system type is one of:
 1 - AIX
 2 - HP-UX
 3 - MacOS X *
 4 - Solaris (!11) *
 5 - Debian
 6 - FreeBSD
 7 - Gentoo
 8 - Mandrake
 9 - Redhat
 10 - Redhat (Centos)
 11 - Redhat (Fedora)
 12 - Slackware
 13 - SuSE *
 14 - Ubuntu
 15 - Cisco IOS/ASA *

 * EXPERIMENTAL!!

Where output type is one of:
 0 - Displays Outdated Packages only
 1 - Displays NASL name and Outdated Packages
 2 - CSV output of CVE, KB and description (comma)
 3 - CSV output of CVE, CVSSv2, Severity, KB, Description (comma)
 4 - CSV output of CVE, KB and description (tab)
 5 - CSV output of CVE, CVSSv2, Severity, KB, Description (tab)

** Entering no parameters will run this in wizard mode walking you through the data collection for your desired system

The post NOPC version 0.4.7 released appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/nopc-version-0-4-7-released/feed/ 0
NOPC version 0.4.5 released https://labs.portcullis.co.uk/blog/nopc-version-0-4-5-released/ https://labs.portcullis.co.uk/blog/nopc-version-0-4-5-released/#comments Fri, 12 Jun 2015 08:38:39 +0000 https://labs.portcullis.co.uk/?p=3683 NOPC, the Nessus-based offline UNIX patch checker has had some changes made and been made available in our tools section. This article discusses the new features in detail and provides some working examples. Introduction There have been some updates to the NOPC tool. The latest version is now 0.4.5. Updated features and bug fixes Added Output […]

The post NOPC version 0.4.5 released appeared first on Portcullis Labs.

]]>
NOPC, the Nessus-based offline UNIX patch checker has had some changes made and been made available in our tools section. This article discusses the new features in detail and provides some working examples.

Introduction

There have been some updates to the NOPC tool. The latest version is now 0.4.5.

Updated features and bug fixes

  • Added Output CSV Format to display information of affected CVEs and CVSS scores
  • Fixed bug in Ubuntu, Redhat and others where “host/cpu” type (value of either: x86_64, i686) is required
  • Fixed OSX mktemp problem by forcing temp storage in /tmp/kb.xxxx directory
  • Fixed bug in HP-UX section where “/Host/HP-UX/hardware” is required

Usage

The following are optional parameters:

  • -d ‘nessus plugin dir’
  • -l ‘output type’
  • -n ‘location of nasl command’
  • -s ‘system type’

The -d option is not required as the default settings is the location for a standard nessus installation (/opt/nessus/lib/nessus/plugins/).

The -l option decides how the output is displayed (see below for support output types). The -n option is not required if you include the nasl command in your path (e.g. export PATH=$PATH:/opt/nessus/bin/). The -s option selects which operating system that will analysed (discussed later).

Output types

Basically, there are raw and CSV output types. There are different output variations available particularly for CSV as follows:
* -l ’0′ = Displays outdated package information only. This is the Installed and Fixed version for each outdated package
* -l ’1′ = Displays NASL name and outdated packages
* -l ’2′ = Displays CVEs for each affected package in (CSV comma separated format)
* -l ’3′ = Displays CVEs and CVSSv2 score for each affected package (CSV comma separated format)
* -l ’4′ = Displays CVE for each affected package (tab separated format)
* -l ’5′ = Displays CVE and CVSSv2 score for each affected package (tab separated format)

Interactive mode

If nopc.sh is launched with no -s option, it will go to interactive mode.

Example

$ nopc.sh -l 3
[+] What type of system have you got the patch output for?
 1 - Redhat
 2 - OSX
 3 - Debian
 4 - Ubuntu
 5 - Slackware *
 6 - Solaris (Maybe !11) *
 7 - AIX
 8 - HP-UX *
 9 - FreeBSD *
 10 - Cisco ASA/IOS

 * UNTESTED!!

Enter 1-10? 4
[+] Ubuntu Selected
[+] Run 'dpkg -l|cat > patchlist.txt'
[+] Enter Location of file: patch-ubuntu-krb5-2.txt
[+] Enter the Value of DISTRIB_RELEASE=() from /etc/lsb-release e.g. 11.10
[+] Enter Text Requested: 10.04
[+] Enter value of 'uname -m' e.g. x86_64, i686
[+] Enter Text Requested: i586
[+] To run this in a script the command would be:

/opt/bin/nopc.sh -l '3' -s '4' 'patch-ubuntu-krb5-2.txt' '10.04' 'i586'

[+] Locating Nasls
[+] Checking for 2314 Missing Patches
NOPC, Ubuntu
Plugin ID, CVE, CVSSv2, Severity, KB, Title
61379, "CVE-2012-1012, CVE-2012-1013, CVE-2012-1014, CVE-2012-1015", 9.3, High, "USN-1520-1", "Ubuntu 10.04 LTS / 11.04 / 11.10 / 12.04 LTS : krb5 vulnerabilities (USN-1520-1)"
51116, "CVE-2010-1323, CVE-2010-1324, CVE-2010-4020, CVE-2010-4021", 4.3, Medium, "USN-1030-1", "Ubuntu 6.06 LTS / 8.04 LTS / 9.10 / 10.04 LTS / 10.10 : krb5 vulnerabilities (USN-1030-1)"
52682, "CVE-2011-0284", 7.6, High, "USN-1088-1", "Ubuntu 9.10 / 10.04 LTS / 10.10 : krb5 vulnerability (USN-1088-1)"
55074, "CVE-2011-0285", 10, High, "USN-1116-1", "Ubuntu 9.10 / 10.04 LTS / 10.10 : krb5 vulnerability (USN-1116-1)"
51985, "CVE-2010-4022, CVE-2011-0281, CVE-2011-0282", 5, Medium, "USN-1062-1", "Ubuntu 8.04 LTS / 9.10 / 10.04 LTS / 10.10 : krb5 vulnerabilities (USN-1062-1)"
49772, "CVE-2010-1322", 6.5, Medium, "USN-999-1", "Ubuntu 10.04 LTS / 10.10 : krb5 vulnerability (USN-999-1)"

Command line

You will notice that the interactive version displays corresponding command-line syntax you could have used. In the example above the following non-interactive invocation could have been used:

/opt/bin/nopc.sh -l '3' -s '4' 'patch-ubuntu-krb5-2.txt' '10.04' 'i586'

Other interesting variations include for Mac OSX, the location of files for Nessus is may not be same Linux (e.g. /library/Nessus) and hence you will need to add -d and -n options to run as follows:

$ nopc.sh -d "/Library/Nessus/run/lib/nessus/plugins/" -n "/Library/Nessus/run/bin/nasl" -l '3' -s '4' 'patch-ubuntu-10.04.txt' '10.04' 'i586'

You can also use specific plugins, which what I did in testing nopc.sh out. For example, copy a number of nasls into a directory myplugins and then:

$ nopc.sh -d "myplugins/" -l '3' -s '4' 'patch-ubuntu-10.04.txt' '10.04' 'i586'

Hidden options

You will see that there are 10 options in the interactive mode.

 1 - Redhat
 2 - OSX
 3 - Debian
 4 - Ubuntu
 5 - Slackware *
 6 - Solaris (Maybe !11) *
 7 - AIX
 8 - HP-UX *
 9 - FreeBSD *
 10 - Cisco ASA/IOS

However a few more are added in this release:

 11. SuSE
 12. CentOS
 13. Fedora
 14. Gentoo
 15. Mandrake

Example

$ nopc.sh -s 11
 [+] SuSE Selected
 [+] Run '/bin/rpm -qa --qf '%{NAME}-%{VERSION}-%{RELEASE}|%{EPOCH}\n' > patchlist.txt'
 [+] Enter Location of file: patch-suse10-multi1.txt
 [+] Run 'cat /etc/SuSE-release > release.txt
 [+] Enter Location of file: release-suse-10.txt
 [+] Enter value of 'uname -m' e.g. x86_64, i686
 [+] Enter Text Requested: i686
 [+] To run this in a script the command would be:

/opt/bin/nopc.sh -s '11' 'patch-suse10-multi1.txt' 'release-suse-10.txt' 'i686'

[+] SuSE Selected
 [+] Locating Nasls
 [+] Checking for 4905 Missing Patches
 /opt/nessus/lib/nessus/plugins/suse_SA_2007_004.nasl: Success
 /opt/nessus/lib/nessus/plugins/suse_SA_2007_025.nasl: Success
 /opt/nessus/lib/nessus/plugins/suse_SA_2007_038.nasl: Success

Note for these distributions, some simple tests were performed to ensure it is working (as they are not as commonly seen OS).

The next version of NOPC will update the interactive screen and also include an option to which output type format to use.

Summary

This article presents the improvements and fixes to NOPC for the version 0.4.5 release. We have gone through examples and how to use it.

If you find any bugs with this version, please let us know, particularly if you know you are reviewing a vulnerable system and NOPC generates no output or errors.

The post NOPC version 0.4.5 released appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/nopc-version-0-4-5-released/feed/ 0
MS SQL Server Audit: Extended Stored Procedures / Table Privileges https://labs.portcullis.co.uk/blog/ms-sql-server-audit-extended-stored-procedures-table-privileges/ https://labs.portcullis.co.uk/blog/ms-sql-server-audit-extended-stored-procedures-table-privileges/#comments Fri, 23 Jan 2015 16:24:17 +0000 https://labs.portcullis.co.uk/?p=3385 (If you excuse the pun), everyone has a different view on Extended Stored Procedures: Some might say they are stored procedures with extra functionality Some might say they can cause problems to a database if misused Some simply say they are stored procedures with a prefix of xp_ This post will hopefully give a better […]

The post MS SQL Server Audit: Extended Stored Procedures / Table Privileges appeared first on Portcullis Labs.

]]>
(If you excuse the pun), everyone has a different view on Extended Stored Procedures:

  • Some might say they are stored procedures with extra functionality
  • Some might say they can cause problems to a database if misused
  • Some simply say they are stored procedures with a prefix of xp_

This post will hopefully give a better understanding of what Extended Stored Procedures are, how to identify them and how to restrict public access to them. Also this post will look at identifying permissions upon tables, views and functions to ensure it is not possible for users to directly modify data.

Assessing XP stored procedures

Extended Stored Procedures are stored procedures that call functions from Dynamic-Link Library (DLL) files. However these features are deprecated in SQL Server 2012 and may not be supported in future versions of SQL Server. CLR integration should be installed instead if required. In the CIS benchmarks for SQL Server 2008R2 and SQL Server 2012, item 2.2 CLR Integration should be disabled with CLR enabled configuration setting set to 0.

In general, Extended Stored Procedures should not be enabled as good practice. In Centre for Internet Security (CIS) Benchmark for SQL Server 2008r2 and 2012, for the Extended Stored Procedures listed, the recommendation is for those stored procedures to be disabled.

Extended Stored Procedures can be observed using SQL Server Management Studio. Within the Object Explorer, navigate to the SQL Server Instance and expand the path following:

Databases\System Databases\master\Programmability\Extended Stored Procedures\System Extended Stored Procedures

Locate any of the Extended Stored Procedures and look at their properties. The CIS Benchmark for SQL Server 2008R2 and SQL Server 2012 identifies the following are audited:

  • 3.1 xp_availablemedia
  • 3.2 xp_cmdshell
  • 3.3 xp_dirtree
  • 3.4 xp_enumgroups
  • 3.5 xp_fixeddrives
  • 3.6 xp_servicecontrol
  • 3.7 xp_subdirs
  • 3.8 xp_regaddmultistring
  • 3.9 xp_regdeletekey
  • 3.10 xp_regdeletevalue
  • 3.11 xp_regenumvalue
  • 3.12 xp_regremovemultistring
  • 3.13 xp_regwrite
  • 3.14 xp_regread

For example, to look at xp_dirtree:

  1. Locate xp_dirtree (labelled sys.xp_dirtree) in the object explorer, right click and select Properties
  2. Select the Permissions tab
  3. Look in the Users or Roles listing, If the public entry does not exist, then it complies with the CIS Benchmark (and you can skip further steps)
  4. If public entry does exist, select the it within the Users or Roles listing
  5. If the Grant checkbox for the Execute permission is checked, the Public role has Execute permission on the procedure

You should remove the the public entry.

Permissions for xp_dirtree
image-3386

Permissions for xp_dirtree

A useful query can be constructed that gathers the permissions granted to public for all XP stored procedures. The query looks at the database permissions table and identifies the associated objects that are extended stored procedures (XP) with it assigned permissions which applies to PUBLIC.

select OBJECT_NAME(major_id) as 'extended_procedure', permission_name, 'PUBLIC' as 'to_principal'
from sys.database_permissions where OBJECT_NAME(major_id) like 'XP_%'
AND [type] = 'EX' AND grantee_principal_id = 0
order by 'extended_procedure';

Table & View Privileges

In CIS Benchmark for SQL Server 2008R2 and SQL Server 2012, there is a recommendation to sanitise the database and application user input. To help to perform this, a good idea is to gather all the permissions for tables, views, stored procedures and functions including the columns for each of these object types. Note for each user with the permissions to access these object types, the aim is to eliminate any permissions to INSERT, DELETE or UPDATE to non-administrative users (i.e. user that do not require these permissions).

The following query gathers all objects of the above type and their columns and identifies which users can access them with what permission for each database.

sp_msforeachdb 'USE ? SELECT ''?'', cast(o.name as char) AS ObjectName,
CASE o.type WHEN "U" THEN "Table" WHEN "V" THEN "View" WHEN "P" THEN "Stored Proc" WHEN "FN" THEN "Function" ELSE o.type END AS ObjectType,
cast(u.name as char) AS UserName, p.state_desc, p.permission_name, USER_NAME(o.schema_id) AS SchemaName,
CASE WHEN cl.column_id IS NULL THEN "--" ELSE cl.name END AS ColName,
CASE WHEN p.state = "W" THEN "X" ELSE "--" END AS IsGrantOption
FROM sys.objects AS o
INNER JOIN
sys.database_permissions AS p ON p.major_id = o.object_id
INNER JOIN
sys.database_principals AS u ON p.grantee_principal_id = u.principal_id
LEFT JOIN
sys.columns AS cl
ON cl.column_id = p.minor_id AND cl.object_id = p.major_id
WHERE o.type in ("U", "V", "P", "FN")
ORDER BY u.name, p.state_desc ASC, p.permission_name ASC'

Summary

In this article, we have looked Extended Stored Procedures and how to identify them. In general, Extended Stored Procedures are not required for the running of a SQL Server and should be disabled from use. Good practices from Microsoft and CIS support this.
We also looked at constructing a query that can evaluate what permissions are assigned to users for objects that can be applied to sensitive data, such as tables, views, stored procedures and functions.

The post MS SQL Server Audit: Extended Stored Procedures / Table Privileges appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/ms-sql-server-audit-extended-stored-procedures-table-privileges/feed/ 0
MS SQL Server audit: Surface area reduction (part 1) https://labs.portcullis.co.uk/blog/ms-sql-server-audit-surface-area-reduction-part-1/ https://labs.portcullis.co.uk/blog/ms-sql-server-audit-surface-area-reduction-part-1/#comments Wed, 26 Feb 2014 06:50:04 +0000 https://labs.portcullis.co.uk/?p=3380 SQL Server has a number of components that allow clients to connect and communicate with it. Microsoft introduced the term, “Surface Area Reduction” as a security measure that involves stopping or disabling unused components. Like the name suggests, it reduces the number of ways that an attacker could try to interrogate the SQL Server. This […]

The post MS SQL Server audit: Surface area reduction (part 1) appeared first on Portcullis Labs.

]]>
SQL Server has a number of components that allow clients to connect and communicate with it. Microsoft introduced the term, “Surface Area Reduction” as a security measure that involves stopping or disabling unused components. Like the name suggests, it reduces the number of ways that an attacker could try to interrogate the SQL Server.

This post discusses the following:

  • Surface area reduction using Microsoft SQL server-wide configuration (sys.configurations) using the Center for Internet Security (CIS) SQL Server guidelines as a benchmark
  • SQL Server Policy to reduce surface area configuration
  • Which Services should be disabled
  • Surface area reduction using other tables and views using Center for Internet Security (CIS) SQL Server guidelines as a benchmark

Note: The queries mentioned in this article are based on SQL Server 2008 R2. They all should be applicable to SQL Server 2012. Older versions of SQL Server may have different syntax.

Server-wide configuration

Microsoft SQL Server has amongst all of its features, catalog views that return information used by its database engine. One particular catalog information that provides details about all the server wide configuration values is “sys.configurations”. Such information covered include: audit modes, language settings, memory usage, tracing and type of stored procedures enabled.

The following SQL query displays all the server-wide configuration values:

SELECT name, cast(value_in_use as char) FROM sys.configurations;

In general, to reduce the surface area, you should disable as many unnecessary features and services as possible without affecting the performance and functionality of your SQL Server Database Engine. Furthermore, some audit features should be enabled to be log access yo your SQL Server Database Engine. Fortunately, the Center for Internet Security provide security benchmarks for SQL Server that can be followed to cover off disabling unnecessary features.

CIS have written security benchmark guides for SQL Server 2005, 2008 and 2012. It is noted that the SQL Server 2008R2 and 2012 are very similar in layout and recommendation.

Based on the CIS security benchmarks recommended for SQL Server 2008R2 and 2012, for surface area reduction, the following configuration settings relating to the server-wide configuration (sys.configurations) should be disabled for compliance.

  1. Ad Hoc Distributed Queries
  2. CLR Enabled
  3. Cross DB Ownership Chaining
  4. Database Mail XPs
  5. OLE Automation Procedures
  6. Remote Access
  7. Remote Admin Connections
  8. Scan For Startup Procs
  9. SQL Mail XPs

Note: the last configuration setting, “SQL Mail XPs” is not covered in the CIS Microsoft SQL Server 2012 Database as that setting was deprecated in that version with “Database Mail XPs” as its replacement.

Other configuration settings of interest:

  • Agent XPs – Extended Stored Procedures for SQL Server Agent should be disabled. Default value is ’0′ (disabled)
  • C2 Audit Mode – Logs both successful and successful attempts to access statements and objects (superceded by Common Criteria Compliance). C2 Audit Mode should be enabled
  • Common Criteria Compliance Enabled – Replacement for ‘C2 Audit Mode’ (only available for Enterprise/Developer versions). Common Criteria Compliance should be enabled
  • SMO and DMO XPs – Extended Stored Procedures for SQL Server Management Objects (SMO) and Database Management Objects (DMO) ideally should be disabled. However, Default value is ’1′ (enabled). If disabled, SQL Server Management Studio will not see the database instance and to load the database instance force this setting to be re-enabled
  • Default Trace Enabled – Tracing should be enabled. Default value is ’1′ (enabled)

The remediation covered by the CIS security benchmark is to show advanced options and then configure the configuration setting, with 0 (for disable) as appropriate.

For example to disable “Scan For Startup Procedures”:

EXECUTE sp_configure 'show advanced options', 1;
RECONFIGURE;
EXECUTE sp_configure 'Scan for startup procs', 0;
RECONFIGURE;
GO
EXECUTE sp_configure 'show advanced options', 0;
RECONFIGURE;

SQL Server policy

Microsoft recommend that policy-based management for SQL Server is used. In earlier versions of SQL Server, this was covered using Surface Area Configuration. This was removed from SQL Server 2008 and its functionality was moved into policy management facets in SQL Server Management Studio.

Using SQL Server Management Studio, within the Object Explorer, navigate to the SQL Server Instance and expand the path following:

Management\Policy Management\Facets

The following facets should be disabled (disabled by default) according to Microsoft:

  • Surface Area Configuration
  • Surface Area Configuration for Analysis Services
  • Surface Area Configuration for Reporting Services

As seen in the following screenshot example:


Surface Area Configuration Facet in SQL Server Management Studio
image-3381

Surface Area Configuration Facet in SQL Server Management Studio

Services

Microsoft also recommend turning off any unneeded services by setting the service to either manual startup or disabled using SQL Server Configuration Manager.

Microsoft do not specify exactly which services that should be disabled. Obviously, you want the core SQL Server service but you could in theory run without the other services. Double check if you need other services such SQL Server analysing and SQL Server reporting services.

To see what services are currently running or disabled, in SQL Server Configuration Manager:

  1. Click on SQL Server Services
  2. In Details Pane, right-click on a service and choose properties
  3. To change the start mode, select “service” tab and edit the start mode entry

As seen in the following screenshot example:


Disable SQL Services using SQL Server Configuration Manager
image-3382

Disable SQL Services using SQL Server Configuration Manager

Summary

In this post, we have had a look at reducing surface area by:

  • Modifying the server-wide configuration (sys.configurations view)
  • Applying SQL Server policies
  • Turning off unneeded SQL services

In the second part of the article, we will look at other features and SQL queries that can be used to reduce the surface area and comply with good security practices.

The post MS SQL Server audit: Surface area reduction (part 1) appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/ms-sql-server-audit-surface-area-reduction-part-1/feed/ 0
MS SQL Server Audit: Introduction https://labs.portcullis.co.uk/blog/ms-sql-server-audit-introduction/ https://labs.portcullis.co.uk/blog/ms-sql-server-audit-introduction/#comments Mon, 10 Feb 2014 06:20:21 +0000 https://labs.portcullis.co.uk/?p=3371 MS SQL Server is Microsoft’s relational database management system with a large number of features and services. With this coverage, there is a large surface area for attack and vulnerabilities. Fortunately, there are a number of security benchmarks and good practice documents available. This article gives an introduction to the security guidelines available and an […]

The post MS SQL Server Audit: Introduction appeared first on Portcullis Labs.

]]>
MS SQL Server is Microsoft’s relational database management system with a large number of features and services. With this coverage, there is a large surface area for attack and vulnerabilities. Fortunately, there are a number of security benchmarks and good practice documents available. This article gives an introduction to the security guidelines available and an overview on what key areas to audit and lock down.

Introduction

Microsoft has a SQL Server – Best Practices section on their technet web site. Specifically, a couple of good practice documents of interest are:

Microsoft also has available a Best Practices Analyser (BPA) for each version of SQL Server which is a diagnostics tool that trawls through a given SQL Server instance and reports the configurations and any differences against Microsoft’s recommended good practices.

The Center for Internet Security (CIS) is the non-profit organisation focused on enhancing the cyber security readiness and response of public and private sector entities. One of its divisions deals with setting Security Benchmarks for a number of systems and frameworks. There are specific security benchmark documents for each major version of SQL Server up to 2012.

Security Technical Implementation Guide (STIG) is a methodology for standardised secure installation and maintenance of computer software and hardware. It was originally defined by the Defense Information Systems Agency (DISA) which created configuration documents in support of the US Department of Defence (DoD). The resource for STIG documents can be found on DISA’s Information Assurance Support Environment.

Looking in particular at Microsoft SQL Server Best Practice and CIS security benchmark, there are a few sections that are covered:

  • Compliance
  • Encryption
  • Access Control
  • Authentication
  • Network Security
  • Auditing

Compliance

For compliance, a number of items have been identified to help improve the security for a SQL Server and used as a benchmark setting. The following are areas for compliance

  • Surface Area Reduction – Configure settings on SQL server to disable unnecessary features and services
  • Policy-Based Management – Configure a policy on SQL server
  • Service Account Selection and Management – Configure and disable unnecessary services
  • SQL Server Best Practices Analyzer and other analysis utilities – Run SQL tools to assist in auditing the SQL Server (such as SQL Server Best Practices Analyzer, Microsoft Baseline Security Analyser (MBSA), Microsoft Security Compliance Manager (SCM), Anti-Virus.
  • Patching and Automatic Windows Update – Ensure underlying system is patched up to date.

Encryption

For encryption, the following should be considered:

  • Encryption of Data and Database
  • SSL Encryption of client connections

Access Control

For access control, the following should be considered:

  • Administrator Privileges
  • Database Ownership and Trust
  • Lockdown of System Stored Procedures
  • Schemas
  • Authorization
  • Catalog Security
  • Execution Context
  • Remote Data Source Execution

Authentication

For authentication, the following should be considered:

  • Authentication Modes and Logins
  • Password Policy
  • Contained Databases and Authentication

Network Security

For network security, the following should be considered:

  • Limiting the network protocols used
  • Configuring and enabling a firewall
  • Avoiding expose a server that is running SQL Server to the public Internet

Auditing

For auditing, it is scenario-specific but in general to configure your server to audit as much detail as possible without making the server inoperable.
Generally, you should look at:

  • Auditing is scenario-specific. Balance the need for auditing with the overhead of generating addition data
  • Use the SQL Server 2008/2012 Audit feature for the most secure, performant, and granular
  • Audit successful logins in addition to unsuccessful logins if you store highly sensitive data
  • Audit DDL and specific server events by using trace events or event notifications
  • DML can be audited by using trace events or SQL Server Audit
  • Use WMI to be alerted of emergency events

Summary

As we have seen there are a number of security benchmark and guideline articles available. Examples include Microsoft, Center for Information Security (CIS) and Security Technical Implementation Guide (STIG). We looked at the general areas covered in these examples. In the next post, we shall look further at the first of these areas, reducing the surface area for vulnerabilities and attack.

The post MS SQL Server Audit: Introduction appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/ms-sql-server-audit-introduction/feed/ 0
Audit services using Windows Programs only https://labs.portcullis.co.uk/blog/audit-services-using-windows-programs-only/ https://labs.portcullis.co.uk/blog/audit-services-using-windows-programs-only/#comments Mon, 10 Feb 2014 06:00:04 +0000 https://labs.portcullis.co.uk/?p=3307 There are many third-party tools in the security industry that can perform a security audit of your Windows system. Some are standalone executable, some are frameworks, some are free and some you have to shell out money for. But what if you these tools are not available to you, you are stuck with a Windows […]

The post Audit services using Windows Programs only appeared first on Portcullis Labs.

]]>
There are many third-party tools in the security industry that can perform a security audit of your Windows system. Some are standalone executable, some are frameworks, some are free and some you have to shell out money for. But what if you these tools are not available to you, you are stuck with a Windows servers and essentially what Windows has given you. This article will look at executable programs under Windows that can be use audit services.

So you want to audit a Windows system with the credentials given. You may be able to download and install your own software but what if you are not permitted. What can you do?

Windows have native programs on-board that can be used to gather information about your system, for example:

  • WMIC
  • CACLS/ICACLS
  • netstat
  • systeminfo
  • tasklist

Using those commands and some clever batch processing, you can gather useful information. In this article, we will look specifically at auditing what Windows services are run and could be overrun with WMIC and CACLS.

WMIC

Windows Management Instrumentation Command-Line (WMIC) extends WMI for operation using a command-line interface to get and modify details about a Windows system. As a consequence, you must be a local administrator (a member of the local Administrators group).

Services

Details about the services running under Windows can be observed by loading the “services” console under Administrative Tools in Control Panel or running “services.msc”. To access services information running on a system using WMIC, you need to be logged with an administrative account and type:

C:\> wmic service get /all

You can get specific information from the service and even place it to a nice format as follows:

C:\> wmic service get DisplayName, Name
C:\> wmic service get Name, ProcessID, StartName
C:\> wmic service get Name, PathName /format: csv.xsl

The following is the help file for its usage:

Property get operations.
USAGE:

GET [<property list>] [<get switches>]
NOTE: <property list> ::= <property name> | <property name>,  <property list>

The following properties are available:
Property                                Type                    Operation
========                                ====                    =========
AcceptPause                             N/A                     N/A
AcceptStop                              N/A                     N/A
Caption                                 N/A                     N/A
CheckPoint                              N/A                     N/A
CreationClassName                       N/A                     N/A
Description                             N/A                     N/A
DesktopInteract                         N/A                     N/A
DisplayName                             N/A                     N/A
ErrorControl                            N/A                     N/A
ExitCode                                N/A                     N/A
InstallDate                             N/A                     N/A
Name                                    N/A                     N/A
PathName                                N/A                     N/A
ProcessId                               N/A                     N/A
ServiceSpecificExitCode                 N/A                     N/A
ServiceType                             N/A                     N/A
StartMode                               N/A                     N/A
StartName                               N/A                     N/A
Started                                 N/A                     N/A
State                                   N/A                     N/A
Status                                  N/A                     N/A
SystemCreationClassName                 N/A                     N/A
SystemName                              N/A                     N/A
TagId                                   N/A                     N/A
WaitHint                                N/A                     N/A

The following GET switches are available:

/VALUE                       - Return value.
/ALL(default)                - Return the data and metadata for the attribute.
/TRANSLATE:<table name>      - Translate output via values from <table name>.
/EVERY:<interval> [/REPEAT:<repeat count>] - Returns value every (X interval) seconds, If /REPEAT specified the command is executed <repeat count> times.
/FORMAT:<format specifier>   - Keyword/XSL filename to process the XML results.

NOTE: Order of /TRANSLATE and /FORMAT switches influences the appearance of output.
Case1: If /TRANSLATE precedes /FORMAT, then translation of results will be followed by formatting.
Case2: If /TRANSLATE succeeds /FORMAT, then translation of the formatted results will be done.

Now you can gather the executable program that are run in services using pathname property:

C:\>wmic service get pathname
PathName
C:\WINDOWS\system32\Macromed\Flash\FlashPlayerUpdateService.exe
C:\WINDOWS\system32\svchost.exe -k netsvcs
C:\WINDOWS\system32\svchost.exe -k LocalService
C:\WINDOWS\System32\alg.exe
C:\WINDOWS\system32\svchost.exe -k netsvcs
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_state.exe
...
"C:\Program Files\WinPcap\rpcapd.exe" -d -f "C:\Program Files\WinPcap\rpcapd.ini"
"C:\Program Files\Sophos\Sophos Anti-Virus\SAVAdminService.exe"
"C:\Program Files\Sophos\Sophos Anti-Virus\SavService.exe"
"C:\Program Files\Sophos\AutoUpdate\ALsvc.exe"
...

As you can see here, not only are the program names are included but its parameters. You pipe the information into a file and sort (i.e. wmic service get pathname | sort > services.txt). You could remove the parameters manually (or using a script).

Using this file you can enumerate each file location with CACLS/ICACLS

CACLS

CACLS and its replacement, ICACLS, are Microsoft Windows native command line utilities capable of displaying and modifying the security permissions on folders and files, controlling who can access it.

Putting everything together

You can use a for loop to execute cacls/icacls to identify what permissions are set for each service program:

for /f "tokens=*" %a in (services.txt) do cacls %a >> s_cacls.txt

From here, you can determine which services have a weak by searching for strings that do not contain Administrative users and assessing the permissions for remaining non-administrative users:

findstr /s /n /i /p  /v "Administrator Power Authority" s_cacls.txt

Batch Script Example

I have written a window batch script that grabs the pathname and does some pre-processing (sorting, removing duplicates, removing parameters) as follows:

REM	s_cacls.bat
REM
REM	The batch file extracts the services and finds the permissions for the underlying file
REM	* Uses 'wmic service' to get program executable for each service
REM	* Sort and process the list of programs
REM	* Perform cacls

:: SETUP for filenames and directories
SET dirscacls=scacls
SET fileservices=services.txt
SET fileservicessort=services-sorted.txt
SET fileservicesuniq=services-uniq.txt
SET filetemp=temp.txt
md %dirscacls%
cd %dirscacls%

:: Extract program executable for each service
for /F "skip=1 tokens=*" %%a in ('wmic service get pathname') do (
  setlocal enableDelayedExpansion
  set _str=%%a
  set ^"_str=!_str:  =^

!"
  for /f "eol= delims=" %%S in ("!_str!") do (
    if "!!"=="" endlocal
    @echo|set/p=%%S>>%fileservices%
    @echo.>>%fileservices%
  )
  endlocal
)

:: Strip out options. Assumption made that each service is using .exe file
for /f "tokens=*" %%a in (%fileservices%) do (
setlocal enableDelayedExpansion
  set _str=%%a
  set ^_str=!_str:.exe=^

!"
  for /f "eol= delims=" %%S in ("!_str!") do (
    if "!!"=="" endlocal
    @echo|set/p=%%S.exe>>%filetemp%
    @echo.>>%filetemp%
  )
  endlocal
)

:: Sort the file of programs into alphabetical order
::call:sort8ren "%filetemp%", "%fileservices%"
sort %filetemp% > "%fileservicessort%"
del %filetemp%

for /f "tokens=*" %%A IN (%fileservicessort%) DO (
SETLOCAL EnableDelayedExpansion
  if /i not [%%A]==[!LN!] (
    set "LN=%%A"
    echo %%A>>%fileservicesuniq%
  )
)
ENDLOCAL

call:sicaclsloop %fileservicesuniq%

cd ..
goto:EOF

:scaclsloop
for /f "tokens=*" %%a in (%~1) do (
  cacls "%%a" >> scacls_%%~na.txt
)
goto:EOF

:sicaclsloop
for /f "tokens=*" %%a in (%~1) do (
  icacls "%%a" >> sicacls_%%~na.txt
)
goto:EOF

:sort8ren
sort %~1 > %~2
del %~1
rename %~2 %~1
goto:EOF

Summary

It is possible to find out details of the Windows for auditing using the native Windows programs. In this article, we have managed to audit Windows services using WMIC, CACLS and some batch processing.

The post Audit services using Windows Programs only appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/audit-services-using-windows-programs-only/feed/ 0