2
Core ConceptsCore ConceptsExecution ContextsExecution ContextsModule SigningModule SigningCryptographyCryptographyAuditingAuditing
An endpoint exposes SQL Server services on networkExposed Services:
TSQLSOAP (Web Services)Service BrokerDatabase Mirroring
Works over TCP and HTTP transportService must be compatible with the transport (TSQL works with TCP only)
TSQL endpoints are created by defaultHTTP endpoints deprecated in SQL Server 2008
• CONNECT SQL permission on SERVER• For all types of services (TSQL, SOAP, …)• Implicitly granted when login is created
• CONNECT permission on ENDPOINT• CONNECT on TSQL ENDPOINT is granted to
PUBLIC by default• Login enabled or disabled
• Login attribute not a real permission• Allows disabling SA and sysadmin
Authenticates identity within SQL ServerEndpoint basedVerifies access rights to the serverEstablishes primary security context
SQL AuthenticationIn-built authentication protocolLogin/password basedIndependent of Windows OS authentication
Windows AuthenticationWorks with passwords, smartcards, thumb readers, etc.Recommended in most cases
Windows onlySQL logins cannot connect
MixedSQL logins and Windows logins allowed
Mode can be changed after installation
Requires SQL logins
Login handshake encrypted using SSLCertificate to be used determined at connection
Validates passwordEnforces account policy
Account is locked out, must change password
Supports password change on login
CREATE LOGIN Alice WITH PASSWORD = ‘…’
SQL authentication is not un-secureUsed when
No rights to create Windows usersAvoiding delegation double-hop issuesNon-Windows clientsApplication logins outside of Windows
NotesEncrypted when using SNACNo SID from operating systemPrincipal is not guaranteed unique
{OK}
TSQL TCPendpoint
SQL Server box{Alice, pwd} SSLAlice’s box
Alice
TCP/IP
SQL Server
SSL certificate
Designed to deter brute force attacksPassword must not contain all or part of the account name
Part of an account name is defined as three or more consecutive alphanumeric characters delimited on both ends by whitespace or some special chars
Min 8 chars, max 128 charsContains characters from three of the following four categories:
Latin uppercase letters (A through Z) Latin lowercase letters (a through z) Base 10 digits (0 through 9) Non-alphanumeric characters
Leave CHECK_POLICY onSet CHECK_EXPIRATION on to avoid old passwordsSet MUST_CHANGE for new logins
Uses Windows OS usersCREATE LOGIN [REDMOND\SQLTest1] FROM WINDOWS
Secure using Kerberos or NTLMWindows creates client security token on the serverThe Windows token contains
User identityGroup membershipsWindows privileges
{OK}
TCP/IP TSQL TCPendpoint
SQL Server box{Alice, NULL}
LSA
SQL Server
Domain Controller
Alice’s token
Alice
LSA
Uses standard Kerberos / NTLM protocolNo need to manage logins in SQL ServerWorks with SmartCards and other non-password based authentication devices
Only possible for Windows LoginsLogin is not provisioned in SQL Server
CREATE LOGIN has not be called
Login is a member of Windows Group, provisioned in SQL Server
CREATE LOGIN [Bob\SQLUsers] FROM WINDOWS
Have distinct owners for databasesNot all owned by “SA”Minimize owners for each database
Confer trust selectivelyLeave CDOC (cross-database ownership chaing) setting off
Migrate usage to selective trust instead
User token outside the databaseToken authenticator vouches for the tokenIf authenticator trusted, token is honoredIf authenticator not trusted, token not honored
Default behaviour
Two alternatives for setting authenticatorsUse TRUSTWORTHY setting to have DBO as an authenticatorUse certificates as authenticators
Recommended
Per database settingIndicates that a context set in this DB can have the DBO as an authenticatorOnly a sysadmin can change the TRUSTWORTHY state for a databaseALTER DATABASE database_nameSET TRUSTWORTHY {ON | OFF}
Don’t turn TRUSTWORTHY ON unless the DB and all its administrators are truly trustworthyMonitor TRUSTWORTHY bit changesAvoid turning TRUSTWORTHY ON a database owned by sysadmin members
For Cross-DB scenarios assign a low privileged dbo
For cross database & server access impersonation consider using signatures
TRUSTWORTHY ONdbo is a member of sysadmin roleResult: Privileged users in this DB can become sysadmin themselves.
Password basedCompletely contained in DB
No presence outside the DB
By default cannot revert SQL Server 2005 added sp_unset_approle
Application roles are DB scopedToken is not trusted in server scope
Do not access:Cross database resources as “guest”No access to server scoped metadata
PasswordDo not hardcode itSubject to password policy check (complexity)
Use flag 1416 for backwards compatibility only“guest” access cross database
Limited “guest” access
Permission basedScoped
User vs. LoginContext impersonation bound to module
Stack basedREVERT
NO REVERT & REVERT WITH COOKIE
EXECUTE AS LOGIN = ‘login_name’Server level impersonationRequires IMPERSONATE ON LOGIN::<login_name>
EXECUTE AS USER = ‘user_name’Database level impersonationRequires IMPERSONATE ON USER::<user_name>
Stackable – can return to previousEXECUTE AS
push new execution context frame
REVERTpop top execution context frame
Active context is determined exclusively by top context frame
Default behaviorUse the caller’s contextSame as SQL Server 2000No IMPERSONATE permission is required
Will execute under the specified principal contextRequires IMPERSONATE on the principal
Returns details of the non-impersonated contextVery useful for auditingAllows controlling behavior based on original login details when EXECUTE AS another principal
What it is designed forControlled escalation of privileges via modulesEasy to use when all resources are in the same DB
What it is not designed forSandboxing against an attackCan be used as a defence in depth.
CREATE USER Someuser WITHOUT LOGINNo access to outside databasesTo switch to user context useEXECUTE AS USER = ‘Someuser’
Requires IMPERSONATE permission on SomeuserBetter alternative to application roleOrphan users / mismatched SIDs are similar
Use sp_change_users_login to map them to loginsALTER USER … WITH LOGIN since 2005 SP2
Stores authentication information needed to access resources outside SQL ServerMost contain a Windows username and passwordPermits access to Windows resources for SQL Server loginsOne credential can be mapped to multiple loginsOne login can only be mapped to a single credentialMapped using CREATE/ALTER LOGINsys.credentials
Allow subsystems to make use of credentials for external accessSpecify proxy name, credential name and descriptionMust create the credential firstAssign created proxy to appropriate subsystems
Deprecated –> do not useOnly for backwards compatibility
Limited to sysadmin & DBO onlyDBO access is restrictedRequires high privileges
No stack on impersonated contextRevert via SETUSER call
NO REVERT
Consider IMPERSONATE a privileged permission
Impersonator >= Impersonated
AUTHENTICATE permission is highly privileged permission
Can escalate to DBO
Consider AUTHENTICATE SERVER as powerful as sysadmin!
Module encapsulation can be done usingOwnership chainingEXECUTE ASCode signing
Always place a security check inside the module
Don’t rely on EXECUTE permission on the module
Set context on modules (don’t let default)Use EXECUTE AS instead of SETUSERUse WITH NO REVERT/COOKIE instead of App Roles
Cryptography is the science of keeping secrets Encryption is the process of obscuring information to make it unreadable without special knowledge
Plain text -> Cipher Text -> Plain Text
2000 years ago…
Famous electro-mechanical encryption device used to encrypt and decrypt messages
Every encryption method has an encryption algorithm and decryption algorithm. When both algorithms depend on the same key, its known as symmetric key encryption.
SymmetricKey
Encryption
Decryption
0x0088840517080E4FA2…
4428-6823-7821-2358
Biggest challenge has been management of keysHow do I send you the key that I will use to encrypt data that I send you?Chicken/Egg problem
Keys are mathematically relatedContains public and private keyComputationally infeasible (today) to derive one from the other
AsymmetricKey
Encryption with Public Key
Decryption with Private Key
4428-6823-7821-2358
One-way function onlyFingerprint of dataCannot derive the data from the hashProves the integrity of the dataRecipient recalculates hash and compare values
Random number added to the encryption key or to a password to protect them from disclosureAlso known as “Initialization Vector”Without salt, a value encrypted twice will have same ciphertextCritical to also avoid known text in known location
Magic recipe for scrambling data is the algorithmMost algorithms are mind-numbingly complex mathematical equationsMany algorithms usedNot all as useful as othersSQL Server uses Microsoft CSP limited to algorithmsavailable in operating system
Digitally sign modulesTwo roles of the signing certificate:
Secondary IdentityExtend the execution context
AuthenticatorVouch for the EXECUTE AS context defined in the module definition
NOTE: Signature can act as secondary identity and authenticator simultaneously
To send you encrypted data, I encrypt the data with your public keyYou use your private key to decryptI know that only you can read itSSL works like this
Asymmetric keys with some metadataDigital signatures bind together a public key with an identity — i.e. the name of a person or an organization, their address, etc Signature can be from cert. authority Signature can be self-signed
Used to verify the identity of the person who has the public keyUse in real life: SSL connections to web servers Digital signatures in email
Designed to authenticate the server not the clientUses public key crypt for the initial exchangesSession key then generated and exchangedSession key used for symmetric encryptionTraffic overhead typically about 30%Must also consider CPU overheadPrevents “man in the middle” attacks and TCP hijacking
Execution ContextExecution Context
Attaches a cryptographic signature to the moduleIf the module does implicit impersonation
Certificate as an authenticator
If a principal is mapped to the certificateCertificate as secondary identity
The signature affects the execution context only if it is valid
Changing a signed module requires re-signing it
The signature only affects execution context for the scope of the signed moduleCan still audit/identify executing user
CONTROL permission on the certificate is requiredSyntax:
ADD SIGNATURE TO <module_name>BY CERTIFICATE <key_name>[{ WITH PASSWORD = ‘password’| WITH SIGNATURE=binary_signature}]
Trust on the group of people who have CONTROL on the signing private keyTrust on the code.
If you don’t trust the code or you are not comfortable with its quality do not sign it.
Signed code can move from one DB or server to another
Certificate, Asymmetric key principalsBoth logins and usersA way to grant permissions to signers
Can not be used for loginCan not be directly impersonated using EXECUTE AS
CREATE USER Cert_User FROM CERTIFICATE Cert1
Module SigningModule Signing
59
PasswordPassword KeyKeyCertificateCertificate
Public KeyPublic Key Private KeyPrivate Key
Master KeyMaster Key PasswordPassword
Service KeyService KeyDP APIDP API
WrapsWraps AssociatedAssociatedwithwith
Secured BySecured By
Secured BySecured By
SecuredSecured ByBy
KeyKey
Secured BySecured By
• Typically requires varbinary datatype• Maximum encrypted size is 8000 bytes• Encrypted data is salted
Prevents copy/paste attacks Can’t reference encrypted columns
• Can’t index/full-text search encrypted columns Might index a hash instead Might index part of the column instead
• Encryption EncryptByKey, DecryptByKey, DecryptByKeyAutoCert,
DecryptByKeyAutoAsymKey EncryptByCert, DecryptByCert EncryptByAsymKey, DecryptByAsymKey
• Encrypted data is prefixed with key GUID identifier (required for symmetric keys)
• Password protected keys vs Database Master key protected keys/certificates
• Decryption automatically determines key• Hashing
HashBytes: SHA1, MD5
Symmetric Keys No DDL support These keys can be (re)generated from a passphrase
(KEY_SOURCE + IDENTITY_VALUE + algorithm)
For Asymmetric keys Can import keys from .SNK strong named files and
strong named assemblies No option to export
Certificates Can import/export DER encoded (.cer files) X.509
certificates Private keys only in PVK format. (.pvk files)
Keys are stored with the databaseRestore the Service Masker Key
OPEN MASTER KEY DECRYPTION BY PASSWORD = <password>
ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY
For keys that protect other keys: ALTER SERVICE MASTER KEY REGENERATE ALTER MASTER KEY REGENERATE Add new key encryption, remove old key encryption
For keys that protect data, data needs to be decrypted and re-encrypted using the new key: Inconvenient, but unavoidable
For backups, need to keep track of passwords that protect old keys
SQL EKM Provider DLL
SQL EKM Key(HSM key proxy)
Data
SQL Server
HSM
• Key storage, management and encryption done by HSM module
• SQL EKM key is a proxy to HSM key
• SQL EKM Provider DLL implements SQLEKM interface, calls into HSM module
SecurityData and keys are physically separated (keys are stored in HSM modules)Centralized key management and storage for enterpriseAdditional authentication layerSeparation of duties between db_owner and data owner
PerformancePluggable hardware encryption boards
EKM providers are server objectsCREATE CRYPTOGRAPHIC PROVIDER DataSafeProvider FROM FILE = ‘DataSafeProvider .dll’
EKM keys are very similar to native keysManaged using the same TSQL
CREATE SYMMETRIC KEY SymmKeyEkm FROM Provider DataSafeProvider WITH ALGORITHM AES_256 …
Visible in the same catalogsData encryption with standard built-insUsed to encrypt SQL native keys
HSM
DatDataa
DatDataa
Native Symmetric key
TDE DEK key
EKM Symmetric key EKM Asymmetric key
SQL Server
Symmetric key Asymmetric key
Builtin\AdministratorsCan debug server process
Server administrator (sysadmin)Can look at server tracesLuring attacksExtended procs to dump memory
Best lock down encryptionDrop the service master key from the DB master key encryption
Goal : Encrypting/Decrypting Columns without changing Application ,is this possible ?
Possible through implementing a methodology : Views ,Functions, Triggers.
71
Sql Sql ServerServer
Encrypt/Decrypt Abstraction layer Encrypt/Decrypt Abstraction layer Encrypt/Decrypt Abstraction layer Encrypt/Decrypt Abstraction layer
ApplicationApplication
I Name CCno Address
1 George 0Xjhsl.. …
2 Mike 0Xkas… …
3 Dan 0Xoee.. …
TextTextDataData
Key Key ManagementManagement
Encrypted Encrypted DataData
Decrypted Decrypted DataData
Encrypted Encrypted DataData KeysKeys
DMLDML
INSTEAD OF INSTEAD OF Trigger/sTrigger/s
(Encryption)(Encryption)
INSTEAD OF INSTEAD OF Trigger/sTrigger/s
(Encryption)(Encryption)
Encrypted
Encrypted DataData
View/sView/s(Decryption)(Decryption)
View/sView/s(Decryption)(Decryption)
Encrypted
Encrypted
DataData
Encrypt/Decrypt Abstraction layer Encrypt/Decrypt Abstraction layer
KeysKeys KeysKeys
selectselect
74
Tracking and logging eventsSQL Trace/Profiler commonly used in earlier versionsAutomated system introduced in 2008Need to check government requirements or organizational standardsOutput of audit activity is often referred to as an “audit”Audit is at the instance levelMultiple audits per instance possibleImplemented via Extended Events infrastructure
Triggers have been widely used for auditingNo SELECT triggersIssues with nesting triggersIssues with trigger firing orderIssues with performance
General event handling for serversIntention is to provide end-to-end eventing with Event Tracing for WindowsEngine is event agnosticConsumers of events are called “targets”Actions are distinct from the events raisedPredicates can be used for filtering
Server Audit SpecificationOne server audit specification per auditCollects server-level actions
Database Audit SpecificationOne database audit specification per auditCollects database-level actions
Audit Action GroupsPredefined groups of actions
Results of an audit sent to a targetFileWindows Security Event LogWindows Application Event Log
Must be reviewed and archived periodicallyBe cautious with application log as any authenticated user can read itWriting to security event log
SQL Server Service must be added to “Generate Security Audits” policy
sys.server_auditssys.server_file_auditssys.server_audit_specificationssys.server_audit_specifications_detailssys.database_audit_specificationssys.database_audit_specifications_detailssys.dm_server_audit_statussys.dm_audit_actionssys.dm_audit_class_type_map
AuditingAuditing
82
Top Related