Lab 8: Securing MSSQL Server Lab
I. Open access to SQL Server
Objective: Connect remotely to SQL server when using dynamic ports
1. On the desktop, press the key combination Win + R then enter WF.msc and
select OK.
In the Windows Firewall with Advanced Security section, select the Inbound
Rules tab on the left, then click New Rule.
2. In the Rule Type section, select Program, then click Next.
3. In the Program box, select This program path. Click Browse and navigate to the
path containing the SQL Server you want not to be blocked by the firewall, then
click Open. By default, the SQL Server path is
C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe.
Click Next
4. In the Action section, select Allow the connection and click Next.
5. In the Profile section, select the connection environment type of the device when you use
the database and click next.
6. In the Name section, enter a name to distinguish the rule and description (optional)
and click Finish.
7. After completing the above steps, data from the SQL server to the outside and
from the outside will not be blocked.
II. Decentralize permissions on SQL server
*Lưu ý: When an error occurs during the process, turn off SQL Server Management
Studio and turn it back on.
Create Lab5 database, create table tblEmployee
Nhập dữ liệu cho bảng tblEmployee
Create user1 to log in to SQL, right-click Security, select new -> login
Select SQL Server authentication, Enter Login name, Password and click OK
In Lab5 database, right-click Security, select new -> user
Enter the username and login name you just created
Authorized
To assign permissions to user1 on the tblEmployee table, select Tables, right-click
dbo.tblEmployee, select Properties
Select the Permissions tab, click Search, enter the user name and click Check Names
Click OK to continue
Tick the permissions we want to grant to user1 (select, insert) and press OK
- Turn off SQL Server Management Studio, restart and reconnect using the user1 account
- Execute query to check the access rights assigned to user1 Select permission, run the select
statement and observe the results
select employeeName, email, phone from tblEmployee
So user1 has the right to select, continue with the right to insert, run the sql statement and
observe the results
insert into tblEmployee(employeeName,email,phone)
values('khanh','[email protected]','0284916472')
So user1 also has the insert right. Let's try the delete right, a right that user1 is not
assigned. Run the delete command and observe the results.
delete from tblEmployee where employeeName='khanh'
So user1 does not have the right to delete on the tblEmployee table
Revocation of rights
Disconnect and connect the database using the admin account to revoke user1's rights.
Revoke user1's insert rights by following the same steps as assigning rights and
unchecking insert rights.
Turn off SQL Server Management Studio, restart and reconnect using user1 account,
execute the insert statement and observe the results:
insert into tblEmployee(employeeName,email,phone)
values('tri','
[email protected]','0284916472')
We see that user1 no longer has insert rights on the tblEmployee table
Check permissions
To check the rights of users on the tblEmployee table, we can repeat the steps in
the rights assignment section to observe the assigned rights of each user. Or run the
following query
declare @tblTemp as table
(
databasename nchar(50),
own nchar(10),
tblname nchar(50),
grantor nchar(10),
username nchar(10),
privilege nchar (50),
grantable nchar(10)
)
insert into @tblTemp
EXEC sp_table_privileges
@table_name = 'tblEmployee'
select username, privilege from @tblTemp
order by username
Result:
Limit access to rows
Create a new user in the Lab5 database named manager and assign select
permissions on the tblEmployee table
Run the insert statement to add a row of data:
insert into tblEmployee(employeeName,email,phone)
values('user1','
[email protected]','07351273242')
Run each of the following commands in turn to create a filter for the tblEmployee
table
Step 1:
CREATE SCHEMA Security;
GO
CREATE FUNCTION Security.fn_securitypredicate(@username AS
nvarchar(50))
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS fn_securitypredicate_result
WHERE @username = USER_NAME() OR USER_NAME() = 'manager';
Step 2:
CREATE SECURITY POLICY EmployeeFilter
ADD FILTER PREDICATE Security.fn_securitypredicate(employeeName)
ON dbo.tblEmployee
WITH (STATE = ON);
Step 3:
GRANT SELECT ON security.fn_securitypredicate TO user1;
GRANT SELECT ON security.fn_securitypredicate TO manager;
- Run the query with user1 and manager and observe the results
Hide information
Run the following command to create a masked table:
CREATE TABLE Membership
(MemberID int IDENTITY PRIMARY KEY,
FirstName varchar(100) MASKED WITH (FUNCTION =
'partial(1,"XXXXXXX",0)') NULL,
LastName varchar(100) NOT NULL,
Phone varchar(12) MASKED WITH (FUNCTION = 'default()') NULL,
Email varchar(100) MASKED WITH (FUNCTION = 'email()') NULL);
INSERT Membership (FirstName, LastName, Phone, Email) VALUES
('Roberto', 'Tamburello', '555.123.4567', '
[email protected]'),
('Janice', 'Galvin', '555.123.4568', '
[email protected]'),
('Zheng', 'Mu', '555.123.4569', '
[email protected]');
SELECT * FROM Membership;
- Create a user to perform test queries:
CREATE USER TestUser WITHOUT LOGIN;
GRANT SELECT ON Membership TO TestUser;
EXECUTE AS USER = 'TestUser';
SELECT * FROM Membership;
REVERT;
III. SQL injection
Create table:
create table users(
username char(20) primary key,
password char(20)
)
create table products(
product_name char(20) primary key,
product_description char(50),
category char(20)
)
- Add data to the table:
insert into users values('admin','adminpassword');
insert into users values('superuser','superuserpass');
insert into users values('alex', 'alexpass');
insert into users values('bentley', 'bentleypass')
insert into products values('car', 'xe hoi', 'transportation')
insert into products values('bus', 'xe buyt', 'transportation')
insert into products values('ship', 'tau thuy', 'transportation')
insert into products values('teddy', 'gau bong', 'gift')
insert into products values('sticker', 'nhan dan', 'gift')
insert into products values('stamp', 'con tem', 'gift')
insert into products values('flower', 'hoa', 'gift')
- SQLi in SELECT statement:
select * from users where username='admin' and password='adminpassword';
select * from users where username='admin'-- and password='
select * from users where username='1' or 1=1--;
- SQLi with UNION:
select product_name, product_description from products where category='gift' and
product_name like '%s%';
select product_name, product_description from products where category='gift'
union select username, password from users-- and product_name like '%t%';
select * from products where category='gift';
select * from products where category='gift'; update users set password='newpass'
where username='alex'—
select * from users;
select * from products where category='gift'; drop table users--
IV. Encrypt data, view log
- Create Master Database Key
- Create Certificate
- Backup Certificate
- Create Database Encryption Key
- Turn on encryption
Note: Use any database, in this section use a database named University
1. Create Database Master Key(DMK)
First of all, it has nothing to do with the main database. DMK is a symmetric key
that protects other keys. You must have DMK to be able to encrypt all encryptable
objects in the database such as:
Symmetric Keys (Khóa đối xứng)
Asymmetric Keys (Khóa bất đối xứng)
Certificates (Chứng chỉ)
Command to create DMK:
USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD
=‘VeryStrongPassword’;
GO
2. Create a certificate
Now that we have the DMK in the main database, we can generate keys and
certificates then encrypt them with the DMK. Command to create certificate:
USE master;
CREATE CERTIFICATE TDECert WITH SUBJECT= ‘TDE Certification‘;
GO
3. BackupCertificate
This is extremely important because if you lose your certificate, you lose all your
data, period. That's why, the safest way is to backup immediately after you create a
certificate. The command to backup:
BACKUP CERTIFICATE TDECert
TO FILE = ‘D:\BK\MyTDECert.cer’
WITH PRIVATE KEY
(
FILE = ‘D:\BK\CertPrivateKey.key’,
ENCRYPTION BY PASSWORD = ‘VeryStrongPassword’
);
GO
4. Create Database Encryption Key
It's time to create our master key, the Database Encryption Key. A certificate in the
main database will protect DEK, and DEK will encrypt data on every page.
Command to create DEK:
CREATE DATABASE ENCRYPTION KEY
WITH ALGORITHM = AES_256
ENCRYPTION BY SERVER CERTIFICATE TDECert;
Note :
If you encounter the above error, recheck step 1 to make sure you have used the
correct database, here it is “use master;” else “use your_database”
5. Turn on encryption
The final step is to enable encryption for the database. This will start a chain to
encrypt the entire database using the Database Encryption Key, Command:
SELECT db_name(database_id) as db_name, percent_complete, * FROM
sys.dm_database_encryption_keys
GO
ALTER DATABASE University SET ENCRYPTION ON;
ALTER DATABASE University SET ENCRYPTION SUSPEND;
ALTER DATABASE University SET ENCRYPTION RESUME;
6. View Log
Open the log file, view the logs on the computer and test for error cases.
Step 1: click view on the task bar, select object Explorer F8:
Step 2: After SQL Explorer appears, find the SQL Server Logs folder as shown in
the image, right-click on the folder, select view SQL server Log
Step 3: All logs appear, including time, source, and information for each log:
Step 4: Perform log testing in SQL server. Here, we will create a user with the
username 'teacher2' and password: 123.
Step 5: Login this user into sql server. We use the sqlcmd command in windows
cmd with the user teacher2 but the password will be entered incorrectly:
Step 6: Reopen sql server logs to see the changes:
We notice that on March 7, 2021 at 10:23 the server caught a failed login log for
user teacher2. The reason is that the password does not match.
Step 7: We can also view other logs about Windows NT and database mail.