SQL Server 2005 OverviewRafal LukawieckiStrategic Consultant
Project Botticelli Ltd
This session is based on the results of my close co-operation with my great friend Kimberly Tripp, as well as an article of Michelle Dumler on SQL Server new features. See summary for references.
22
Objectives
Introduce a selection of new features in Microsoft SQL Server 2005
Concentrate on how SQL Server 2005 Security
33
Overview of New Features
44
Introducing New Features
Over 5 years of work means many new and interesting features. Let’s group them:
Manageability
Availability
Scalability
Developer Productivity
Security
55
Manageability
Management Studio
One place for all SQL Server tasks
Performance Monitoring and Tuning
Less “black magic” needed, good self-tuning, but >70 new internal measures exposed for your use
SQL Management Objects (SMOs)
Programmatic administration of SQL through a new set of .NET objects
66
Availability
Failover clustering and mirroring
Complementary solutions; mirroring likely to ship a little after SQL 2005 does
Database snapshots
Instant, read-only views that self-update
Fast recovery
While roll-backs are still completing
Dedicated admin connection
Even if regular access no longer possible
77
Scalability
Snapshot Isolation
Transactionally consistent view up to last committed record for analysis (e.g. OLTP) purposes
Replication Monitor
Toolkit for automating complex replication
Table and Index Partitioning
Horizontal partitioning, especially for terabyte databases
64-bit Optimisation
88
Developer Productivity: .NET
CLR/.NET Framework support
New languages available, with C# and VB the main likely development environments
Can do things that were either extremely complex in T-SQL (e.g. RegEx), or quite unsafe (e.g. requiring extended stored procedures)
Strong-typing with user-defined data structures
Common development and debug environment
Performance!Yes, .NET precompilation is pretty good
99
Other Developer Goodies
T-SQL Updates:
Recursive queries, error handling, new feature support
Business Intelligence Development Studio
Based on Visual Studio, encompasses tasks for managing the database engine, reporting and analysis services
1010
Data Access and Web Services
ADO.NET 2.0 – Revamped, with support for notifications, multiple active result-sets (MARS)…
Query Notifications
Notifications are sent from SQL if data that underlies results from a query changes
Supported in ADO.NET, OLEDB, ODBC, ADO and SOAP
Useful for remote cache updates for web apps
Service Broker
SQL’s nod to Service Oriented Architectures (SOA), through asynchronous message routing as an application framework
1111
Security of SQL Server 2005
1212
Whose Fault was SQL Injection?
OK. I have your attention. It was not you anyway, of course.
Security for a database developer was a very rude wake-up call.
I feel your pain.
I can help you – in this session.
1313
Defense in DepthUsing a layered approach:
Increases an attacker’s risk of detection
Reduces an attacker’s probability of success
Policies, Procedures, & Awareness
Policies, Procedures, & Awareness
OS hardening, SQL Server patchingOS hardening, SQL Server patching
Firewalls, packet filtersFirewalls, packet filters
Guards, locks, tracking devices, Guards, locks, tracking devices, HSM, tamper-evident labelsHSM, tamper-evident labels
SSL, IPSec, No problemsSSL, IPSec, No problems
Application hardening, authorizationApplication hardening, authorization
Permissions, encryptionPermissions, encryption
DBA education against social DBA education against social engineeringengineering
Physical SecurityPhysical Security
PerimeterPerimeter
Internal NetworkInternal Network
HostHost
ApplicationApplication
DataData
1414
Authorization Model
How things used to work?
User-schema separation
Granular permissions
EXECUTE AS
SQL Injection (Classic)
SQL Injection (Future)
1515
Security through Encapsulation
Granting access to a process or a method without direct access to base objects
How?
Grant access to the stored procedures, views and/or functions without granting access to the base object
Requires
The objects in the dependency chain cannot be broken (object ownership chaining)
The user has to have direct base object access (which is what you’re trying to avoid)
1616
Do NOT Give Base Object AccessThe SQL Server 2000 Way
Only works when the object dependency chain is NOT broken
Only works when the commands inside of the stored procedure are not built/executed dynamically
dbo.Salesdbo.Salesdbo.Salesdbo.Sales
UserUserUserUser
dbo.DeleteASalesdbo.DeleteASalesdbo.DeleteASalesdbo.DeleteASales
Granted execute accessto procedure
has NO direct permissionsmay even be DENIED permissions to Sales
1717
User-Schema Separation
Database can contain multiple schemas
Each schema has an owning principal – user or role
Each user has a default schema for name resolution
Database objects live in schemas
Object creation inside schema requires CREATE permission and ALTER or CONTROL permission on the schema
Ownership chaining still based on owners not schemas
Role1Role1
OwnsOwns
Has Has default default schemaschema
OwnsOwns
OwnsOwns
Schema1Schema1 Schema2Schema2
Schema3Schema3
SP1SP1Fn1Fn1
Tab1Tab1
DatabaseDatabase
User1User1 Approle1Approle1
1818
Do NOT Give Base Object AccessThe SQL Server 2005 Way
Create a schema – for example one which contains procedures (and possibly even base tables) and then GRANT EXECUTE at the schema level
Add objects to appropriate schema
Grant access to the schema or the individual objects – if chaining is required, it is still based on the owner… the owner of the schema
1919
What if Dynamic String Execution
By default – and for better security – if the stored procedure has a statement which is built dynamically (using EXEC('string') or EXEC(@variable)) then the context under which the dynamically constructed string executes is ALWAYS the caller
Which is what helps to prevent some forms of SQL Injection
This is really a good thing BUT…
Can be limiting
Enter: EXECUTE AS
2020
Module Execution ContextExecute AS CALLER
Default behavior, same as SQL Server 2000
Use when caller’s permission needs to be checked – or when ownership chaining will suffice
Execute AS 'UserName'
Statements execute as the username specified
Impersonate permission required on user specified
Execute AS OWNER
Statements execute as the current owner of the module
Impersonate privileges on owner required, at setting time
On ownership change, context is new owner
Execute AS SELF
Statements execute as the person specifying the execute as clause for the module – even if the ownership changes
May be useful in application scenarios where calling context may change
2121
EXECUTE AS…
Solves problems
Allows permissions to be granted where never possible (e.g. granting truncate table)
Wrap ANYTHING inside a stored procedure and set the context to run as someone who has permissions – even dynamic string execution – then give execute permission
Creates potential for further SQL Injection
What if you’re code is not well tested and uses dynamically executed strings
2222
SQL Injection
SQL statement(s) or clause(s) injected into an existing SQL command
Injected string appended to application input
Text boxes
Query strings
Manipulated values in HTML
Why SQL injection works?
Application accepts arbitrary user input
Connection made in context of higher privileged account
2323
SQL Injection Mitigation
Do not trust the user’s input!
Look for valid input and reject everything else
Regular expressions (regex) are your friend!
Do not use string concatenation
Use parameterized queries to build queries
Restrict information in error messages
Use a low-privileged account
DO NOT use sa or sysadmin role member
2424
Code Signing
A module can be signed with a certificate
Separately, e.g. in another database, you can map signatures made by a specific certificate to a user
Authorizing that mapped user allows you to provide cross-database permissions without the use of EXECUTE AS
Trust is established between databases by exporting and importing the certificate
This application is likely to be of more use in the future, as today it is not possible to export signed code outside of a database
Esoteric applications exist, though: sophisticated trust control within a deep structure of ownership of database objects
2525
Data Protection
Use of cryptography to protect the data layer from theft or manipulation
Particularly important if offline data is in transit
Important for regulatory reasons
Prevent admin from access
SarbOx
Manipulation (integrity) protection uses digital signatures
Not implemented for data in SQL Server 2005
Can overcome this with judicious use of encryption alone
Implemented for code signing
2626
Check Your OS
Verify what algorithms and key lengths are supported by your OS, as this depends on your CSP (Cryptographic Services Provider)
Generate keys for all algorithms then look in the sys.symmetric_keys
At present, there is no way to change the CSP…
XP SP2 WS2003
DES 56 (64) 56 (64)
3DES 128 128
AES128 - 128
AES192 - 192
AES256 - 256
RC2 128 128
RC4 40 40
RSA 2048 2048
2727
Before You Begin
Your DBA must ensure that the server has a Service Master Key (SMK) that agrees with your disaster recovery strategy and a Database Master Key (DMK) has been created for each database that will use encryption
See later for more detail
ALTER SERVICE MASTER KEY can be used to change recovery options
CREATE MASTER KEY ENCRYPTION BY PASSWORD =
Use a strong password, write it down and keep it safe
2828
Key Generation
The key should be impossible to guess. Preferably random.
CREATE xSYMMETRIC… will generate a fairly random key for you – good!
You can base the key on data supplied by you, use KEY_SOURCE clause – good for generating identical keys from a high-quality password
2929
Passwords
Make sure passwords used to protect or create keys are very strong
In our opinion, it is better to create a very long and complex password that you will have to write down and store in a well-protected safe in your company
You can divide it into two halves and store in separate envelopes in different safes
E.g.: *87(HyfdlkRM?_764#{(**%GRtj*(NS£”_+^$(No dictionary words, more than 20 characters, many non-printing characters
Challenge: usability!
Consider also:Not keeping passwords as text in your code, but store and retrieve them through DPAPI and a .NET component
Using good quality password generators
3030
Key Protection
SQL Server 2005 insists that the key you create is further encrypted for its protection
Yes, that’s double-encryption, but that is not double-security. Actually, it reduces security a little in some cases
CREATE SYMMETRIC…ENCRYPT BYPASSWORD
Your (v. good) password generates a key to 3DES encrypt the key you are protecting
Note, 3DES is less secure than AES, so this
CERTIFICATEYour key is encrypted using the public key of a certificate
This, in essence, is hybrid encryption
If private key is kept secure (and offline), this is a very good way to protect a symmetric key
Or another SYMMETRIC or ASYMMETRIC key – less useful but interesting
3131
Encryption
1. Create or retrieve the key
2. Open the key – this means decrypt it with its (secondary) password or certificate or other key
3. Use function ENCRYPTBYKEY inside DML
3232
Decryption
1. Create or retrieve the key
2. Open the key
3. Use function DECRYPTBYKEY inside SELECT and all other DML
3333
Key Protection Hierarchy in SQL
Key
Another keyUser Password Certificate
Public KeyPrivate Key
Password Master Key
Secured By
Secured By
Secured By
Associated with…
Secured By DPAPI
Wraps the …
Service Key
3434
Managing Service Master Key (SMK)
SMK used to separate the relationship between DPAPI and machine dependency
DPAPI supports password changes but not Service Account changes
With SMK abstraction, account can be changed and encrypted data does not need to change
However, what happens when a database needs to be used on alternate server?
3535
Managing Service Master KeySingle Server v. Multiple Servers
SMK is machine dependant
Can “dump” certificate to use on secondary/mirror servers to keep SMK in sync
If not in sync, encrypted data will be unavailable until database master key is re-encrypted with SMK of destination server
Special considerations for mirror and automation of re-encryption through certificate store
3636
SQL Server 2005 – Secure by Default
SSL certificate created if doesn’t exist
Login Policies
Server Side
Check_Policy---Default ON
Check_Expiration---Default OFF
Client Side Support
Password Change at login
3737
Protecting SQL Credentials
Requires a secure channel
IPSEC, SSL
In previous releases required admin to setup SSL/IPSEC certificate
Not secure by default
In SQL SERVER 2005
SSL certificate automatically generated
Prevents passive man-in-the-middle attacks
3838
Encryption Over the Wire
Login Credentials EncryptionUses SSL certificate from certificate store (if available)
Can be explicitly chosen using Certificate Picker in SQL Server Configuration Manager
Otherwise, will use SQL generated Certificate (master.sys.certificates)
Data packets can be encryptedServer Side Option: ‘Force Protocol Encryption’
Client Side: Encryption with or without certificate validation
3939
Catalog Security
System tables implemented as views: catalog views
Metadata is secured by defaultMinimal permissions to public
Catalog views are row level secured
Need to be owner or have some permission on object to see it in catalog view
SA can see everything in server
DBO can see everything in database
New permission to allow viewing of metadataVIEW DEFINITON
Applicable at object level, schema level, database, and server level
4040
New Permission Examples
CONTROL
Ownership-like permissions
ALTER
Ability to alter properties – and/or hierarchy
On higher scopes, confers ability to add, drop and alter sub scopes
ALTER ANY ‘X’
Example: ALTER ANY ASSEMBLY
TAKE OWNERSHIP
Ability to take ownership of object
4141
Auditing
Successful and failed logins
sp_configure ‘c2 auditing’ (superseded by FIPS-140-2 Common Criteria but still supported)
Profiler Security Event Class
Events: Add Database User, Addlogin, DBCC events, Change Password, GDR events (Grant/Deny/Revoke events), Server Principal Impersonation event
Data Column: SessionLoginName
4242
Top 10 Best Practices
1. Risk assessment and threat analysis
2. Trap “developer quality” error messages – avoid indecent disclosure
3. Avoid using dynamic string execution
4. Think encryption for sensitive data
5. Do not create objects in DBO schema
6. Hide underlying application schema
7. Use Roles for managing permissions
8. Account for catalog security
9. Avoid encryption as it precludes indexing and performance
10. Know your CSP. Check allowed key lengths if needed. Chose carefully!
4343
Summary
Microsoft SQL Server 2005 makes proactive application-level security finally possible
It has been designed for scalability, availability and manageability needs of modern enterprises
Developers will become more productive through close integration with mature .NET Framework and CLR
Read http://www.microsoft.com/sql/2005/productinfo/overview.mspx for a good overview of all the new features in SQL Server 2005
4444
© 2005 Project Botticelli Ltd & Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. PROJECT BOTTICELLI AND MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN
THIS SUMMARY. You must verify all the information presented before relying on it. E&OE.