0% found this document useful (0 votes)
6 views38 pages

SQLDEV320A Week 9-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views38 pages

SQLDEV320A Week 9-1

Uploaded by

adams.radiy
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 38

Instructor:

SQL Server boB Taylor


Developme boB@sqlboBT.co
nt m
SQLDEV
320 A
Spring
2021 MCA, MCM, MCSM,
Week 9 MCSE, MCSD, MCT,
Data Scientist
REVIEW
• RECAP WEEK8
TODAY • ASSIGNMENT 8 REVIEW

CURSORS

DATA ACCESS
SECURITY

SQL INJECTION

ENCRYPTION
Writing
• What are Cursors
• Examples

Cursors •

Discussions
Pros and Cons
What is a cursor?
A cursor is a database object used by
applications to manipulate data in a set on a
row-by-row basis, instead of the typical SQL
commands that operate on all the rows in
the--set at one time.
Cursor Syntax
DECLARE cursor_name
CURSOR [LOCAL | GLOBAL] [FORWARD_ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR select_statement
[FOR UPDATE [OF column_name [,...n]]]
Steps to use a Cursor:
--Declare the cursor and associate it with a query
DECLARE <cursorname> CURSOR FOR <query>

--Open the cursor


OPEN <cursorname>;

--Fetch the first data row


FETCH NEXT FROM <cursorname> INTO <@variable>;

--Loop until the end of the cursor is reached WHILE @@FETCH_STATUS = 0 BEGIN
<SQL statements>

--Get the next row


FETCH NEXT FROM CustList INTO @customerid; END -- End the while loop

--Close the cursor


CLOSE <cursorname>;

--Release resources
DEALLOCATE <cursorname>;
• @@FETCH_STATUS
• 0 Successful
• -1 Failed
• -2 Row missing

System • @@CURSOR_ROWS
• -m The number of rows in the
Cursor keyset
• -1 Dynamic cursor

Functions:
• 0 No cursor has been
opened
• n Total number of rows
in the cursor

•3) CURSOR_STATUS
• 'local' | 'global' | 'variable'
Common Cursor Arguments
Argument Purpose
UPDATE [OF column_name] for update columns within the cursor

READ ONLY Prevents updates made through this cursor

FORWARD_ONLY Cursor can only be scrolled from first to the last row

STATIC Cursor makes a temporary copy of the data in


tempdb Data changes to base tables are not visible
KEYSET Cursor makes a keyset table in tempdb Data
changes to base tables are visible
DYNAMIC Cursor reflect all data changes as you scroll

OPTIMISTIC Update through the cursor will not succeed if the


row has been updated since it was read into the
cursor. Timestamp is used.

FAST_FORWARD FORWARD_ONLY, READ_ONLY with performance


optimizations enabled
Sample Cursor
DECLARE @customerid int; DECLARE CustList CURSOR FOR
SELECT CustomerID from Sales.Customer WHERE CustomerID IN (1,2,3,4,5,6,7,8,9,10);

OPEN CustList;

FETCH NEXT FROM CustList INTO @customerid;

WHILE @@FETCH_STATUS = 0
BEGIN
IF (SELECT COUNT(CustomerID) FROM Sales.Customer) > 0
SELECT AccountNumber FROM Sales.Customer
WHERE CustomerID = @customerid;
PRINT @customerid;

-- Loop to next record


FETCH NEXT FROM CustList INTO @customerid;
END

CLOSE CustList;
DEALLOCATE CustList; -- Required to DEALLOCATE
GO
What does this code do?
DECLARE @SPID int

DECLARE c_idleSessions CURSOR FAST_FORWARD


FOR SELECT s.spid FROM master..sysprocesses s
WHERE spid > 50
AND DATEDIFF(ss,s.last_batch,GETDATE()) > (60*30)

OPEN c_idleSessions
FETCH NEXT FROM c_idleSessions INTO @SPID;

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'killing process: ' + CAST(@spid as NVARCHAR(5)) EXEC('kill ' + @spid)
FETCH NEXT FROM c_idleSessions INTO @spid
END

CLOSE c_idleSessions;
DEALLOCATE c_idleSessions;
GO
Cursor Discussion:

Can you think of any scenarios


or applications that a cursor
should be used?

What kind of cursors should


be used?
It depends on:
Size of the result set.
Percentage of the data likely tobe needed.
Performance of the cursor open.
Need for cursor operations, such as scrolling or
positioned updates.
Level of visibility to data modifications made by other

Choosing a users.

Simple rules:
Cursor Type Use default settings when possible.
Dynamic cursors open faster than static or keyset-driven
cursors.
In joins, keyset-driven and static cursors can be faster
than dynamic cursors.
Keyset-driven or static cursors must be used if you want
to do absolute fetches.
Keyset-driven or static cursors increase the usage of
tempdb.
Cursor Pros and Cons
Pros
They are necessary for some dynamic operations that can't be accomplished with set-based
operations.
They are simple to understand, which makes them ideal for quick-and-dirty programming
A tool of choice for beginner SQL developers or developers who are used to procedural
programming
They outperform while loops when you need row-by-row processing.
They are ideal for scrolling a portion of a large resultsset.
By default, they provide a window into your tables or results set, which maximizes concurrency
Confor
s all applications.
They are procedural iterative functions that are not like database set operations
They are resource intensive and generally slower than other application approaches
They may not scale to support processing and better options are available
They may lock table inserts or updates causing excessiveblocking
There are better alternatives for FOREACH operations
SQL Injection
In a web application, it is common to have users enter input on the
web page. The web application will formulate that into a SQL
string and send it to the database server to execute the SQL
string

Web page:

Server Code:
SQL
Injection
User id:
SQL Injection – Encoded data attack

1
5
DON’T: Parameterized Queries
--1 Standard SQL
SELECT ProductID, Name, ListPrice FROM Production.Product WHERE Name like 'Road
%'

--2 Unsafe parameter query


DECLARE @ProdName NVARCHAR(25) = N'Road'
DECLARE @SQLSelect NVARCHAR(max) = N'SELECT ProductID, Name,ListPrice '
DECLARE @SQLFrom NVARCHAR(max) = N'FROM Production. Product '
DECLARE @SQLWhere NVARCHAR(max) = N'WHERE Name Like ''' + '%' + @ProdName + '%'
+ '''';
DECLARE @SQL NVARCHAR(max) = @SQLSelect + @SQLFrom + @SQLWhere

--3 Are you sure?


EXEC sp_executesql @SQL
DON’T: Parameterized Queries
DO: Parameterized Queries

CREATE PROCEDURE [Production].[Get_ProductInfoByName] @Name


NVARCHAR(64)
AS
SELECT ProductID, [Name], ListPrice FROM Production.Product
WHERE [Name] like @Name

GO

10
Data Access Security
• Hijacking queries with SQL Injection
• Writing parameterized queries
• Object access permissions
Securing the environment
Infrastructure Security Threats

Secure Infrastructure
Managing user
permissions
Monitoring activity
levels
Configuration
monitoring
Application input
validation

20
Restricting Access Permissions

Grant only explicit permissions as needed


Grant SELECT for specific tables
Only allow DML via stored procedures
Use different proxy users per application
Capture and store authenticated user
information
Security Configuration Best
Practices
Minimize shared
resources for secure
Use current OS with Change SQL Server
data – consider Hide SQLinstance
latest patches default (1433) port
dedicated SQL Server
for high security

Document and audit Turn off unused SQL


Disable unused Implement cell-level
secure access – set Server features
network protocols encryption
access end dates! (SSAS, SSRS, etc.)

Plan for security


Use Windows Configure SQL Server incident response,
Authentication mode Secuirty Logs for communications,
only Auditing auditing, and data
recovery
Protect Sensitive Data

Is data revealing Are you storing Are you subject to Are you under
personally confidential or laws and contractual or
identifiable sensitive business regulations that professional
information (PII)? information? require sensitive obligation to
data encryption? protect your data?
Service Master Key (SMK)
• A symmetric key generated the first time the SQL
Server instance is started
• Encrypt a linked server password, credentials, and

SQL Server the DB master key


• Encrypted by Windows Data Protection API (DPAPI)

and • Key is derived from the Windows credentials of the


SQL Server service account and the machine key

Database from DPAPI

Database Master Key (DMK)


Keys • A symmetric key that is unique to each database
• Protect the private keys of certificates and
asymmetric keys that are present in the DB
• Stored in both the DB and in the master system
database
• Created by the CREATE MASTER KEY command

24
Symmetric Keys Asymmetric Keys

Same key used for both encryption An asymmetric key is made up of a


and decryption private key and the corresponding
Better performance public key
Algorithms: One key decrypts the encryption of the
DES, TRIPLE_DES, TRIPLE_DES_3KEY, other
RC2, RC4, RC4_128, DESX, Asymmetric encryption and decryption
AES_128, AES_192, AES_256 are relatively resource-intensive
Algorithms:
RSA_4096, RSA_3072, RSA_2048,
RSA_1024, RSA_512

SQL Server and DB Keys


Similar to a asymmetric key

Private and public keys that are


digitally associated with an
individual or device

Certificates
Can be created externally from SQL
Server and can have expiration
dates

To create it in SQL Server, use the


CREATE CERTIFICATE command

26
Data Encryption
Master Key Management

Server Master Key (SMK)


Created when SQL Server
installed

Database Master Key (DMK)


Created per database using SMK
Master Key Management

-- First thing! Backup up your keys***


--1 Server Master Key
BACKUP SERVICE MASTER KEY TO FILE = 'c:\temp\exportedservicemasterkey' ENCRYPTION
BY PASSWORD = 'password@1234!' ;
GO

--2 Database Master Key


USE AdventureWorks2019;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'password@4321!’
GO

OPEN MASTER KEY DECRYPTION BY PASSWORD = 'password@4321!';


BACKUP MASTER KEY TO FILE = 'c:\temp\exportedAdventureWorks2012masterkey'
ENCRYPTION BY PASSWORD ='password@4321!';
GO
Encryption Functions – Cell Level Encryption

EncryptByPassphrase()
DecryptByPassphrase()

EncryptByCert()
DecryptByCert()

EncryptByKey() Benefits of cell-


DecryptByKey() levelencryption:
Granular – encryption can be provided at a much
finer-grained level than the entire database. It offers
EncryptByAsymKey() the means to encrypt a single cell within the table
DecryptByAsymKey() uniquely from another cell.
Secure – the element of data that is encrypted remains
inthat
state, even when recalled into memory, until it is actively
decrypted.
User Specific – users can be granted access to keys
that encrypt
and decrypt data that is exclusive to their use.
Encrypt data by Passphrase
(weakest)
-- 1 Define plaintext
DECLARE @plaintext nvarchar(100) = N'The Coca Cola secret formula
is...';

-- 2 Encrypt data with a passphrase


DECLARE @encryptedtext varbinary(300);
SET @encryptedtext = EncryptByPassPhrase(N'Quick brown fox',
@plaintext);

-- 3 View encrypted text


SELECT @encryptedtext as EncryptedData

-- 4 Decrypt the data with the same passphrase


SELECT CAST(DecryptByPassPhrase(N'Quick brown fox', @encryptedtext)
AS nvarchar(100) )AS DecryptedData;
Encrypt data using a Certificate
--1 Create Certificate
CREATE CERTIFICATE CertTest01
ENCRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y'
WITH SUBJECT = 'Secret Records',
EXPIRY_DATE = '20211231';
GO
--2 Create table and variable
DECLARE @CertData TABLE (DataDesc varchar(255), CypherText varbinary(MAX));
DECLARE @cleartext nvarchar(255) = N'The Coca Cola Secret Formula is...';

INSERT INTO @CertData


VALUES( N'data encrypted by certificate', EncryptByCert(Cert_ID('CertTest01'), @cleartext) );

--3 Read encrypted data


SELECT DataDesc,CONVERT(nvarchar(max)
, DecryptByCert(Cert_ID('CertTest01'),CypherText,N'pGFD4bb925DGvbd2439587y')) FROM @CertData

--4 all done


DROP CERTIFICATE CertTest01
Encrypt data using a Symmetric
Key

Supported encryption algorithms: (DES, TRIPLE_DES, RC2, PC4, PC4_128, DESX, AES_128, AES_192,
AES 256)
Encrypt data using a Symmetric
key
DROP MASTER KEY
GO
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'password@1234!'
GO
CREATE CERTIFICATE HR037 WITH SUBJECT = 'EmployeeSSN';
GO
CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = AES_256 ENCRYPTION BY
CERTIFICATE HR037;
GO
ALTER TABLE HumanResources.Employee ADD EncryptedNationalIDNumber
varbinary(128);
GO
OPEN SYMMETRIC KEY SSN_Key_01 DECRYPTION BY CERTIFICATE HR037;
GO
UPDATE HumanResources.Employee SET EncryptedNationalIDNumber =
EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
-- remove column
--ALTER TABLE HumanResources.Employee DROP COLUMN
EncryptedNationalIDNumber;
--select top 10 * from HumanResources.Employee
Encrypt data using an Asymmetric
Key
Encrypt data using an Asymmetric
Key
--2 Create Asymmetric Key
CREATE ASYMMETRIC KEY SecureAsymmetricKey WITH ALGORITHM = RSA_2048 ENCRYPTION BY PASSWORD =
N'AReallyStrongPassword!&*';
--3 Create table to store encrypted data
CREATE TABLE AsymmetricTempTable (Id INT IDENTITY(1,1) PRIMARY KEY, PlainText NVARCHAR(100), CipherText
VARBINARY(MAX));
--4 Declare and set variable @str to store plaintext
DECLARE @str NVARCHAR(100) = N'The recipe for the secret Coke formula is...';

--5 Insert data into AsymmetricTempTable


INSERT INTO AsymmetricTempTable (PlainText, CipherText)
VALUES ( @str, EncryptByAsymKey(AsymKey_ID('SecureAsymmetricKey'), @str));

--6 Display encrypted data


SELECT * FROM AsymmetricTempTable;
--7 Display decrypted text
SELECT
CONVERT(NVARCHAR(100),
DecryptByAsymKey(AsymKey_ID('SecureAsymmetricKey'), CipherText, N'AReallyStrongPassword!&*')) AS
PlainText
FROM AsymmetricTempTable;
--8 Cleanup
DROP ASYMMETRIC KEY SecureAsymmetricKey;
DROP TABLE AsymmetricTempTable;
Transparent Data Encryption
a. Ease of implementation:
TDE is essentially a “flip-the-switch” solution
that allows you to encrypt your entire
database at once, without any database
rework.
b. Use any datatype:
TDE allows you to store data using any
native data type,including large-object data
types. Cell-level encryption operates on the
varbinary data type, and limits the amount of
data that can be encrypted at once to 8,000
bytes or less.

c. Speed:
Because it decrypts data in the buffer pool,
TDE allows SQL Server to take advantage of
indexes to improve query performance. Cell-
level encryption requires a performance
tradeoff, which can be very hard to overcome.
Top 10 Security
Tips
Security is a feature – it needs to be planned, tested, and maintained.

Development shortcuts can always lead to costly security incidents.

Develop a security checklist for regular auditing and configuration review.

Application updates are risky – ensure extra testing and support time.

Monitor server utilization and watch for spikes outside of normal


operation.

Most security incidents occur inside an organization -- protect all access.

Implement logging and auditing to monitor access to sensitive


information.

Separate sensitive information from other application data.

Keep current with Windows OS and SQL Server updates.

Don’t neglect physical security – including offsite backup materials.


Week 9 Assignment

QUIZ 9 CODING
ASSIGNMENT

You might also like