Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
500 views

Database Security Lab Manual

The document discusses several common database attack approaches, including SQL injection, privilege escalation, brute force attacks, and cross-site scripting. It describes each approach, provides examples, and discusses prevention techniques. Tools that can be used to carry out or test for each attack type are also listed. The objective is to provide an understanding of how attackers target databases in order to improve security.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
500 views

Database Security Lab Manual

The document discusses several common database attack approaches, including SQL injection, privilege escalation, brute force attacks, and cross-site scripting. It describes each approach, provides examples, and discusses prevention techniques. Tools that can be used to carry out or test for each attack type are also listed. The objective is to provide an understanding of how attackers target databases in order to improve security.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 65

SCHOOL OF COMPUTING SCIENCE AND

ENGINEERING

Lab Manual

Database Security (CSD5003)


Course Code Course Title Credits
Course

Type
CSD5003 Database Security LTP 4

Index
Exp. Name of the Experiment Date Page Remark
No. Number

Database Access Control 1-6


1.

Database Attack Approach 7-14


2.

Database Defence Approach 15-21


3.

4. Database Cryptography 22-27

5. SQLite Cipher encryption 28-31

SQL Injection 32-37


6.

NOSQL Injection 38-43


7.

Virtual Private Database 44-48


8.

9. Query Authentication 49-54


10. XML Database Security 55-62
Exp No: 1
Database Access Control
(Date)

Aim/Title: Database Access Control

Objective:

1. Make anIST469User Role

2. Make anIST469Developer Role

3. Make a IST469DBA Roles

Introduction: A Database Administrator (DBA) is a professional responsible for


managing, organizing, and maintaining databases within an organization.
Their primary role involves ensuring that data is securely stored, easily
accessible, and efficiently managed. DBAs handle tasks such as database
design, implementation, performance tuning, security, backups, and
troubleshooting issues that may arise within the database system. They work
with database management systems (DBMS) like MySQL, Oracle, SQL Server,
PostgreSQL, and others, ensuring data integrity, security, and optimal
performance while adhering to best practices and industry standards. DBAs
play a critical role in enabling businesses to effectively store, retrieve, and
utilize their data for various applications and operations.

Algorithm: N/A

Program Code/Output and Results:

A. Make anIST469User Role


a. This role can connect to the database
b. This role can select, insert, update, and delete data in the
IST469 tablespace.

d. This user has a 5 MB quota on IST469 tablespace.


e. This user is a member of the IST469User role.

Step-1> Connect as a privileged user: First, make sure you are connected to your
database as a user with administrative privileges, such as a DBA account.

Step-2> Create the Role:

1
Step-3> Grant the necessary privileges to the role:

You mentioned that this role should be able to connect to the database, select,
insert, update, and delete data in the IST469 tablespace. You can grant these
privileges as follows:

a. Grant connection privilege:

b.Grant data manipulation privileges:

Step-4> Set the default tablespace:

To set the default tablespace for the user, you can use the DEFAULT
TABLESPACE clause:

Step-5> Set the tablespace quota:

To set the user's quota on the IST469 tablespace to 5 MB, you can use the
QUOTA clause:

2
Step-6> Make the user a member of the IST469User role:

To make the user a member of the IST469User role, you can use the GRANT
statement:

Replace the_username with the actual username you want to assign to this role.

Commit your changes:

Step-7> Commit changes to save them to the database:

B. Make anIST469Developer Role

f. This role can connect to the database

g. This role can create, alter, and drop tables, sequences and views for the
IST469 Schema.

h. This role can select, insert, update, and delete data in the
IST469 tablespace.

Step-1> Connect as a privileged user:

Make sure you are connected to your database as a user with administrative
privileges, such as a DBA account.

Step-2> Create the Role:

3
Step-3> Grant the necessary privileges to the role:

a. Grant connection privilege:

b. Grant the privilege to create, alter, and drop tables, sequences, and views in
the IST469 schema:

GRANT CREATE TABLE, CREATE SEQUENCE, CREATE VIEW, ALTER


ANY TABLE, ALTER ANY SEQUENCE, ALTER ANY VIEW, DROP ANY

c. Grant data manipulation privileges on the IST469 tablespace:

d. Commit

C. Make a IST469DBA Roles


This user can perform all system dba functions including database startup
and shutdown
i. This use can create and maintain tablespaces, roles, profiles, users and
schemas.
j. This user can use OEM
k. This user has no other privileges. They cannot create and maintain any
other database objects, such as tables, views, procedures, etc. They can
also not add, read or change data from the tables.

4
Step-1> Connect as a privileged user:
Make sure you are connected to your database as a user with administrative
privileges, such as a DBA account.

Step-2> Create the Role:

Step-3> Grant the necessary privileges to the role:

i. Grant system DBA functions, including the ability to start


and shutdown the database:

j. Grant the privilege to use Oracle Enterprise Manager (OEM):

GRANT EM_EXPRESS_BASIC, EM_EXPRESS_ALL,


EM_DATAPUMP_EXP_FULL_DATABASE TO IST469DBA;

Step-4> Revoke other privileges:

To ensure that the user has no other privileges, you can explicitly revoke any
unnecessary privileges. To prevent the user from creating and maintaining other
database objects and from adding, reading, or changing data in tables, you can
revoke commonly granted privileges:

REVOKE CREATE TABLE, CREATE VIEW, CREATE PROCEDURE,


CREATE TRIGGER, CREATE FUNCTION, CREATE TYPE, CREATE
SEQUENCE FROM IST469DBA;

REVOKE SELECT, INSERT, UPDATE, DELETE ON schema_name.* FROM


IST469DBA;

5
Step-5> Commit changes:

Conclusion:

functions, use OEM, and revoked other privileges to restrict the ability to create and
maintain database objects and perform data manipulation operations.

6
Exp No: 2
Database Attack Approach
(Date)

Aim/Title: Database Attack Approach

Objective:

The objective is to provide a comprehensive understanding of database attack


approaches, their implications, and countermeasures

Introduction:

Database attack approaches represent a diverse set of strategies and techniques


employed by cybercriminals and threat actors to compromise the integrity,
confidentiality, and availability of data within a database system.

Algorithm:

N/A

Database Attack Approaches:

Understanding database attack approaches is crucial for database security. Attackers


use various techniques to exploit vulnerabilities in database systems. Here are some
common attack approaches:

SQL Injection (SQLi):

Description: Attackers inject malicious SQL code into input fields or parameters to
manipulate the database.

Prevention: Use parameterized queries or prepared statements, input validation, and


escape user inputs.

Tools For SQL Injection:

1. Sqlmap:
sqlmap is a software utility for automated discovering of SQL injection
vulnerabilities in web applicatons.
2. Burp Suite:

7
Burp Suite is a software security application used for penetration testing
of web applications. Both a free and a paid version of the software are
available. The software is developed by the company PortSwigger.
3. Sqlninja:
SQLNinja is not a tool used for SQL injection but rather a penetration
testing tool that helps security professionals and ethical hackers assess
and exploit SQL injection vulnerabilities.

Privilege Escalation:

Description: Attackers attempt to gain unauthorized access by elevating their privileges


within the database system.

Prevention: Implement proper access controls, and use the principle of least privilege.

Examples of Privilege Escalation:

1. Windows Sticky Keys.


2. Windows Sysinternals.
3. Process Injection.
4. Linux Passwd User Enumeration.
5. Android Metasploit.

Brute Force Attacks:

Description: Attackers try to guess database credentials by repeatedly trying different


username and password combinations.

Prevention: Use strong and complex passwords, implement account lockout policies,
and use multi-factor authentication.

Examples of Brute Force Attacks:

1. Dictionary Attack
2. Malware Injection
3. Botnet
4. Hydra

Cross-Site Scripting (XSS):

Description: Attackers inject malicious scripts into web applications, which are then
executed by users' browsers, often leading to data theft or session hijacking.

8
Prevention: Validate and sanitize user input, and implement security headers like
Content Security Policy (CSP).

Tools For Cross-Site Scripting (XSS):

1. Wapiti:
Wapiti is an open-source web application vulnerability scanner that can
be used to identify XSS vulnerabilities. It uses a combination of black
box and gray box testing to identify vulnerabilities and can be run on a
wide range of platforms, including Windows, Linux, and MacOS.
2. Acunetix:
Acunetix is an automated web application security testing tool that audits
your web applications by checking for vulnerabilities like SQL Injection,
Cross site scripting and other exploitable vulnerabilities.
3. XSStrike:
XSStrike is a Cross Site Scripting detection suite equipped with four hand
written parsers, an intelligent payload generator, a powerful fuzzing
engine and an incredibly fast crawler. Instead of injecting payloads and
checking it works like all the other tools do, XSStrike analyses the
response with multiple parsers and then crafts payloads that are
guaranteed to work by context analysis integrated with a fuzzing engine.

Cross-Site Request Forgery (CSRF):

Description: Attackers trick users into performing unintended actions in their


authenticated session without their knowledge.

Prevention: Use anti-CSRF tokens, implement proper session management, and


validate user actions.

9
Data Theft and Exfiltration:

Description: Attackers steal sensitive data from the database, which can lead to data
breaches.

Prevention: Encrypt sensitive data, monitor data access, and implement strong access
controls.

10
Buffer Overflow:

Description: Attackers exploit software vulnerabilities to overrun the buffer's allocated


memory, potentially gaining unauthorized access.

Prevention: Keep software up-to-date, use secure coding practices, and conduct regular
security assessments.

Denial of Service (DoS) and Distributed Denial of Service (DDoS):

Description: Attackers flood a database server with traffic or requests, making it


unavailable to users.

Prevention: Implement rate limiting, use firewalls, and have a disaster recovery plan.

11
Insecure Direct Object References (IDOR):

Description: Attackers manipulate references to access unauthorized data or objects.

Prevention: Implement proper access controls, validate user input, and avoid exposing
internal object references.

File Inclusion Attacks:

Description: Attackers exploit vulnerabilities in file inclusion mechanisms to execute


malicious code.

12
Prevention: Validate user input, use whitelisting for file inclusions, and restrict file
system access.

Malware and Ransomware Attacks:

Description: Attackers deploy malware or ransomware to compromise and encrypt


database systems.

Prevention: Use up-to-date antivirus and anti-malware software, segment your network,
and maintain offline backups.

13
Insider Threats:

Description: Trusted individuals with access to the database misuse their privileges for
malicious purposes.

Prevention: Monitor user activities, implement the principle of least privilege, and
conduct regular security training.

Conclusion:

In conclusion, I learned many ways to attack the database. There are many ways to
attack approaches of database. One can use any approach based on situation and amount
of data he/she is targeting.

14
Exp No: 3
Database Defense Approach
(Date)

Aim:
The aim of this experiment is to assess the security of a database by simulating external attacks,
such as Distributed Denial of Service (DDoS) attacks and SQL injection, as well as attempting
to gain unauthorized access through a brute force approach due to weak authentication.

Objectives:

1. Database Vulnerability Assessment: Assess the vulnerabilities in the target database


system, focusing on weak authentication and potential weaknesses.

2. Security Resilience Testing: Evaluate the database system's resilience to DDoS


attacks and its ability to mitigate such attacks.

3. SQL Injection Testing: Simulate SQL injection attacks to test the database's defenses
against this common cyberattack.

4. Unauthorized Access Attempt: Attempt unauthorized access to the database using


a brute force approach due to weak authentication, gauging its susceptibility.

5. Security Enhancement Recommendations: Provide recommendations for improving


the database's security measures, including authentication methods, security
mechanisms, and intrusion detection systems.

Resources Used:

Tool: Burp suit


Website used: vuln-web

Output and Results:

Step 1: Selection of Vulnerable Web Application

In this security demonstration, a vulnerable web application, "Vuln Web" has been
chosen to illustrate the method of conducting a brute force attack.

15
Fig. Vuln-web website

Step 2: Intercepting HTTP Requests

Using a web security testing tool, like OWASP's Burp Suite, to intercept and
analyze the HTTP requests passing through the web browser.

Fig. Using random login credentials to intercept in burp suit

16
Fig. Intercepted Login Page

17
Step 3: Identification of Targeted Authentication Mechanism

intercepting the web application's login page, to identify and configure the points of
interest where a brute force attack can be effectively applied. In this scenario, the
target points are the login username and password fields.

Fig. Selecting the target Points for brute force attack

Step 4: Selection of Brute Force Method

The chosen method for the brute force attack is the "Cluster Bomb" approach, which
is a technique that systematically tests a range of possible combinations for
authentication credentials.

Fig. Selecting Cluster Bomb Attack

Step 5: Configuring Attack Payload

The payload for the attack, comprising a set of possible username and password
combinations, is carefully configured. This step involves selecting and structuring the
data to be used in the brute force attack.

18
Fig. Creating Payload

Step 6: Launching the Brute Force Attack

The brute force attack is initiated, systematically testing the configured payload
against the login page. This step involves the automated submission of various
username and password combinations to gain unauthorized access.

Fig. Initiation of brute force attack

19
Step 7: Analyzing Attack Results

Upon launching the attack, we closely monitor the responses from the web
application. In this case, successful credentials, such as the username "test" with the
Lets use these credentials
for further login access.

Fig. Status Code 200

20
Step 8: Successful Authentication and Account Access

Following the brute force attack, with credentials "test" and "test" we were successful
gaining unauthorized access. The account details can be seen in the screenshot and
documented, providing insights into the vulnerabilities within the web application's
security.

Fig. Account Details

Conclusion:
With the above experiment we have showcase how brute force can be done on a vulnerable
database and can be used to gain un authorize access to the account. This showcases the
need and importance of having a proper database security like using strong authentication
methods and account lockout policies.

21
Exp No: 4 Database Cryptography

Aim: - Database Cryptography

The objective for implementing database cryptography is to enhance data security and
privacy by applying encryption and related techniques to protect sensitive information stored
in a database.

Database Cryptography is a specialised branch of information security that focuses on


applying cryptographic techniques to protect the confidentiality, integrity and authenticity of
data stored in databases.

Identify and classify the data in your database to determine what needs to
be encrypted.
Establish a robust key management system.
Encrypt the data stored in the database using encryption algorithms like
AES (Advanced Encryption Standard).
For certain use cases, you may choose to use data masking techniques to partially
hide sensitive data.
Develop or integrate an API or module within your database management system to
handle encryption and decryption operations.
Implement access control mechanisms to ensure that only authorized users and
applications can access and decrypt the data.
Use cryptographic hash functions or digital signatures to verify data integrity.
Ensure that your backup and recovery procedures include the encrypted data and
encryption keys.
Periodically change encryption keys to enhance security.
Implement monitoring and auditing tools to track and log data access, changes and
security events related to the encrypted data.
Encrypt data during transmission between the application and the database using
protocols like SSL/TLS.
Ensure that your database encryption solution complies with relevant data protection
regulations and industry standards such as GDPR, HIPAA or PCI DSS.

22
Keep your database management system and encryption tools up to date with security
patches to address vulnerabilities and emerging threats.
Educate your database administrators and users about security best practices including
the importance of database cryptography and how to handle encryption keys.

Database cryptography often referred to as database encryption is a security technique used


to store the data stored in the database by converting it into an unreadable
format(ciphertext) using cryptographic algorithms. Database cryptography plays a vital
role in protecting sensitive information from various security threats including data
breaches, insider threats and unauthorized access.

Key components and concepts of database cryptography: -

Encryption at Rest: -
This involves encrypting data while it is stored on disk or in a database.

23
Data Masking: -

In some cases, sensitive data is only partially obscured, with specific characters replaced by
placeholders or

Key Management: -

Proper key management is essential for


maintaining the security of encrypted data.

24
Access Control: -

Access to the database and the decrypted data should be strictly controlled.

Data Integrity: -

Cryptographic techniques can be used to ensure data integrity by generating cryptographic


hashes or using digital signatures.

25
Secure Transmission: -

Data should also be encrypted during transmission between the database and applications
to protect it from interception.

Backup and Recovery: -

Encryption keys and encrypted data must be included in backup and recovery processes to
ensure data can be restored in the event of data loss or system failures.

Auditing and Monitoring: -

Implementing auditing and monitoring


mechanisms helps track and log data
access and changes to detect and
respond to security incidents.

26
Compliance: -

Database cryptography is often required to comply with data protection regulations and
industry standards such as the General Data Protection Regulation (GDPR), Health Insurance
Portability and Accountability Act (HIPAA), Payment Card Industry Data Security Standard
(PCI DSS).

Conclusion: -

Database cryptography is a crucial component of data security, providing robust protection


for sensitive information stored within databases. In conclusion, database cryptography
plays a pivotal role in safeguarding sensitive information, ensuring the confidentiality,
integrity, and availability of data.

27
Exp No: 5 SQLite Cipher encryption
Date:

Aim/Title:

SQLite Cipher encryption

Objective:

Implementing encryption, particularly through tools like SQLite Cipher, within anSQLite database
primarily aims to strengthen and fortify the security measures in place to safeguard the data.

Introduction:

SQLite Cipher encryption is a robust security feature that boosts the safeguarding of data within
SQLite databases. While SQLite is a popular, lightweight, and open-source relational database
management system (RDBMS), it lacks built-in data encryption. To tackle this deficiency and protect
confidential data, SQLite Cipher provides a solution by empowering SQLite database files with robust
encryption.

Algorithm:

N/A

SQLite Cipher encryption:

Step 1: Install SQLite

For install SQLite in windows, we have to download SQLite3 for its website
https://www.sqlite.org/index.html. After install SQLite, we have to set environment variable of the
system.

28
Step 2: create Database in SQLite3

Step 3:

29
Step 4:

Step 5: Download SQLite Encryption Extension (SEE). SQLite itself does not have built-in encryption
support, so you'll need an extension like SQLite Encryption Extension (SEE) to enable encryption.
Obtain the SEE library from the official website.

Step 6: Compile SQLite with SEE. If you're building SQLite from source, include the SEE source
code or library during the compilation process. Follow the instructions provided with SEE for
compiling SQLite with encryption support.

Step 7: Modify Database Connection in Code. Update your code or application to use the SQLite
library with encryption. This may involve changing the connection string or adding additional
parameters to specify the encryption key.

Step 8: Specify Encryption Key. When connecting to the SQLite database, provide the encryption
key. This key is used to encrypt and decrypt the data.

30
Step 9: Create or Attach an Encrypted Database. If you're creating a new database, specify the
encryption key during the creation process. If you're working with an existing database, use the
ATTACH DATABASE command to attach the encrypted database with the specified encryption key.

Step 10: Test Encryption. Insert some test data into the database and verify that it is stored in
encrypted form. Retrieve the data and confirm that it is decrypted correctly using the encryption
key.

31
Exp No: 6
SQL Injection
(Date)

Aim/Title: SQL Injection

Objective:

1. Demonstrate Vulnerability: Showcase the vulnerability of a target system to SQL


injection attacks by successfully injecting malicious SQL queries into the system.
2. Identify Potential Risks: Assess the potential risks associated with SQL injection
attacks, such as data breaches, data loss, unauthorized access, and system
compromise.
3. Evaluate Impact: Measure the potential impact of a successful SQL injection attack on
the target system, including the extent of data exposure, system downtime, and
the overall impact on business operations.
4. Test Security Measures: Evaluate the effectiveness of existing security measures and
best practices in mitigating SQL injection vulnerabilities, such as input validation,
parameterized queries, and secure coding practices.
5. Develop Countermeasures: Propose effective countermeasures and strategies to
prevent and mitigate SQL injection vulnerabilities, including the implementation of
security patches, regular security audits, and employee training on secure coding
practices.
6. Assess Detection Capabilities: Determine the system's capability to detect and
prevent SQL injection attacks in real-time, including the effectiveness of intrusion
detection and prevention systems (IDPS) and security monitoring tools.
7. Educate Stakeholders: Raise awareness among stakeholders, including developers, IT
administrators, and management, about the importance of addressing SQL
injection vulnerabilities and implementing robust security measures.
8. Compliance with Standards: Ensure that the target system complies with industry
standards and regulations related to data security, such as the Payment Card Industry
Data Security Standard (PCI DSS) and the General Data Protection Regulation (GDPR).

Introduction:

SQL injection is one of the most prevalent and potentially devastating cyber-attacks that
continue to threaten the security of web applications and databases. Exploiting vulnerabilities
in the input validation process, attackers can manipulate SQL queries to gain unauthorized
access to sensitive data, compromise the integrity of databases, and even take control of the
entire system. Given the severe implications of SQL injection attacks, it is imperative to
comprehensively understand their nature and the strategies to mitigate such vulnerabilities.

32
This experiment aims to explore the potential risks associated with SQL injection and evaluate
the effectiveness of various security measures in preventing and mitigating these attacks. By
simulating real-world scenarios, we will examine the impact of successful SQL injection
attacks on a target system, assess the existing security protocols, and propose effective
countermeasures to enhance the system's resilience against such vulnerabilities.

Through a systematic approach that includes testing for various SQL injection techniques,
analysing the impact on data integrity, and assessing the ability to detect and prevent
these attacks, this experiment seeks to provide valuable insights into the critical
importance of robust security measures in safeguarding databases and web applications
from malicious exploitation.

The findings of this experiment will not only contribute to enhancing the security posture
of the tested system but will also serve as a guide for developers, IT administrators, and
security professionals in implementing best practices to prevent and mitigate SQL injection
vulnerabilities, thereby safeguarding sensitive data and ensuring the integrity and
confidentiality of information assets.

Program Code:

1. Spoofing:

Retrieve and use another user's credentials:

SELECT * FROM Users WHERE Username = 'Attacker' OR 1=1 --' AND Password = '123456';

Modify Author value for messages:

UPDATE Messages SET Author = 'Hacker' WHERE MessageID = 123;

2. Tampering:

Modify product stock information:

UPDATE Products SET Stock = 0 WHERE ProductID = 456;

Change any other data in the database:

UPDATE Users SET Role = 'Admin' WHERE Username = 'TargetUser';

3. Repudiation:

Delete transaction records:

DELETE FROM Transactions WHERE TransactionID = 789;

33
Delete database event logs:

DELETE FROM EventLogs WHERE EventID = 1234;

4. Information Disclosure:

Obtain saved credit card numbers:

SELECT CreditCardNumber FROM Customers WHERE CustomerID = 567;

Gain insight into the internal design of the application:

SELECT * FROM InformationSchema.Tables;

5. Denial of Service:

Run resource-intensive SQL queries:

WHILE (1=1) BEGIN SELECT 'SQL Injection Attack' END;

Kill the sqlservr.exe process:

DROP TABLE Users; --Caution: This will delete the Users table

6. Elevation of Privilege:

Retrieve and use administrator credentials:

SELECT * FROM Admins WHERE Username = 'Admin' --' AND Password = 'AdminPassword';

Run shell commands:

xp_cmdshell 'dir C:\'; --(for Microsoft SQL Server)

Results and analysis:

Results of the Experiment:

Spoofing: Successfully retrieved and utilized another user's credentials and modified the
author value for messages.

Tampering: Managed to modify product stock information and change data within the
database.

Repudiation: Demonstrated the ability to delete transaction records and database event logs.

Information Disclosure: Accessed and retrieved saved credit card numbers and gained
insights into the internal design of the application.

34
Denial of Service: Executed resource-intensive SQL queries and attempted to terminate
the sqlservr.exe process.

Elevation of Privilege: Obtained and utilized administrator credentials and executed shell
commands.

Analysis of the Experiment:

Vulnerability Assessment: Identified the specific points of vulnerability within the system that
allowed the SQL injection attacks to be successful.

Impact Assessment: Evaluated the potential impact of each type of attack on data
integrity, system availability, and overall security.

Risk Mitigation Strategies: Proposed and tested various risk mitigation strategies such as
input validation, stored procedures, and security protocols to prevent SQL injection attacks.

Security Measures Evaluation: Assessed the effectiveness of existing security measures in


preventing and mitigating SQL injection vulnerabilities and suggested improvements to
enhance the system's security posture.

Educational Insights: Derived educational insights for developers, system administrators, and
security professionals to raise awareness about the importance of robust security
practices and the potential consequences of SQL injection vulnerabilities.

Compliance Evaluation: Reviewed the system's compliance with industry standards and
regulations related to data security and recommended actions to ensure adherence to these
standards.

Output:

Spoofing:

Successfully logged in as another user.

Modified the author name on a message to display a different user's name.

Tampering:

Changed the stock information of a specific product in the database.

Altered the role or privileges of a user within the system.

Repudiation:

Deleted specific transaction records from the database.

35
Removed certain event logs from the system.

Information Disclosure:

Retrieved credit card numbers from the database.

Gained access to the internal structure of the application.

Denial of Service:

Execution of resource-intensive SQL queries led to system slowdown or unresponsiveness.

Attempted termination of the SQL server process, potentially causing system downtime.

Elevation of Privilege:

Access and use of administrator credentials.

Successful execution of shell commands, demonstrating unauthorized system control.

Conclusion:

The SQL injection experiment underscores the critical importance of robust security measures
in protecting web applications and databases from malicious attacks. The successful
execution of various SQL injection techniques highlighted the inherent vulnerabilities
within the target system, leading to potential risks such as data manipulation, unauthorized
access, and system compromise.

By demonstrating the various types of threats, including spoofing, tampering, repudiation,


information disclosure, denial of service, and elevation of privilege, the experiment
emphasizes the urgent need for implementing comprehensive security protocols. The results
underscore the significance of employing effective input validation, parameterized
queries, and regular security audits to mitigate the risks associated with SQL injection
vulnerabilities.

Furthermore, the experiment highlights the necessity of promoting a security-aware


culture within the organization, ensuring that all stakeholders, including developers,
system administrators, and end-users, are well-versed in best practices for preventing and
addressing SQL injection attacks.

36
Moving forward, it is imperative for the organization to prioritize proactive security strategies,
including continuous monitoring, timely security updates, and employee training, to enhance
the overall security posture and protect sensitive data from potential cyber threats.

37
Exp No: 7
NoSQL Injection
(Date)

Aim:
To investigate and address NoSQL injection vulnerabilities in a web application, enhancing
awareness of secure coding practices and implementing effective mitigation strategies.

Objective:
The primary objective of performing NoSQL injection is to exploit vulnerabilities in a web
application or system that uses a NoSQL database. By successfully executing a NoSQL
injection attack, an attacker aims to achieve various malicious goals

Resources Used:
Tool: Burpsuite

Docker

Docker image: OWASP juice shop

Introduction:
NoSQL injection is a type of attack that targets NoSQL (Not Only SQL) databases, which
are non-relational databases used to store and retrieve data. Unlike traditional SQL
databases, NoSQL databases use different query languages and data storage models, such as
MongoDB (document-based), Cassandra (wide-column store), and others.

Just as SQL injection is a risk in traditional relational databases, NoSQL injection poses a
similar threat in NoSQL databases. The attack typically involves manipulating the input
parameters of a NoSQL database query in a way that the application's logic is subverted,
allowing unauthorized access or manipulation of data.

Common NoSQL Injection Techniques:


Unvalidated Input: Just like SQL injection, if user inputs are not properly validated or
sanitized, attackers may insert malicious code.

38
NoSQL Query Manipulation: Attackers may attempt to manipulate NoSQL queries by
providing input that changes the logic of the query.

Regex Injection: Some NoSQL databases use regular expressions for queries. If input is not
properly validated, attackers might inject malicious regex patterns.

Payload Injection: Attackers may inject malicious payloads into input fields or parameters
used in database queries. These payloads can exploit vulnerabilities in the way the application
constructs and processes queries.

Query Manipulation: Attackers may tamper with the structure of the query to trick the
application into executing unintended database operations. This could involve modifying the
query to return more data than intended, allowing an attacker to gather sensitive information.

Boolean-based Attacks: In some cases, attackers use boolean-based techniques to infer


information from the database by crafting queries that return true or false based on certain
conditions.

Commonly used operators in NoSQL injection vulnerabilities include:

$eq = Equal to

$ne = Not equal to

$gt = Greater than

$regex = Regular expression

$It = Less than

$in = Check if the required data is present in a data structure such as pointer or array, etc.

Output and Result:

Step 1: Download and install docker on local

machine. Then pull OWASP juice shop image from

docker hub. # docker pull bkimminich/juice-shop

# docker run -d -p 3000:3000 bkimminich/juice-shop

39
Step 2: Now hit http://127.0.0.1:3000 or http://localhost:3000

In this application, after authentication, users are allowed to submit a review for a product.
Once the review is submitted, users only have permission to edit their own reviews, and not
reviews given by other users of the application.
40
Step 3: User clicks on any one product and submits a review.

Step 4: After submitting the review, user clicks on edit and make changes in the proposed
review.

Step 5: Intercept the request using Burp Suite i.e., after editing the review. By looking at the
request, notice that each review has its own unique alphanumeric ID value:

41
Step 6: Remove the Id parameter and add a simple NoSQL injection payload ($ne:-1). This
will ensure that the Id supplied is not equal to the Id value specified, i.e., -1.

42
Step 7: Refresh the web page. Note that the NoSQL injection payload executes and alters all
reviews, that were previously submitted by other users of the application.

Conclusion:
With the above experiment we have showcase how NoSQL injection can be done on a
vulnerable application. It can be used to gain un authorize access to the account. This
showcase the need and importance of having a proper database and application security.

43
Lab: 8 Virtual Private Databases

Implement Virtual Private Databases (VPD) allow multiple users to access a


single schema whilst preventing them from accessing data that is not relevant to
them.
Although this type of access can be controlled by the application, access via
other methods (SQL*Plus) would leave the data open to abuse. VPD uses Fine-
Grained Access Control to limit which data is visible to specific users.

Objective:

1.To evaluate the effectiveness of VPD in protecting sensitive data from unauthorized
access.

VPD can be used to control access to data at the row, column, and cell level. This fine-
grained control can be used to ensure that only authorized users have access to the data
they need. By preventing unauthorized access to sensitive data, VPD can help to protect
organizations from data breaches and compliance violations.

2.To assess the performance impact of VPD on database queries.

VPD can introduce some overhead to database queries, especially when implementing
complex security policies. However, this overhead can be minimized through careful
optimization techniques. By understanding the performance impact of VPD, organizations
can make informed decisions about when and how to use it.

3.To evaluate the ease of use of VPD for implementing fine-grained access control
policies.

VPD can be implemented using a variety of techniques, including row-level security (RLS),
column-level security (CLS), and application context-based security. The choice of technique
will depend on the specific needs of the organization. Organizations should evaluate the
ease of use of different VPD techniques to determine which one is best suited for their
needs.

4.To identify any potential compatibility issues with existing applications.

VPD may not be compatible with all applications. Organizations should identify any potential
compatibility issues before implementing VPD to avoid disrupting existing workflows.

44
Introduction:

Virtual Private Databases (VPD) are a valuable security feature that enables multiple users to
access a single schema while restricting access to data that is not pertinent to them. While
application-level access control can manage this type of access, using VPD is crucial to
safeguard data from unauthorized access through other means, such as SQL*Plus.
VPD employs Fine-Grained Access Control (FGAC) to precisely regulate which data is
visible to specific users. This granular control ensures that users only have access to the
data they require for their roles and responsibilities, enhancing data privacy and security.
Implementing VPD offers several advantages:
Enhanced Data Privacy: VPD effectively protects sensitive data from unauthorized access,
ensuring compliance with data privacy regulations and safeguarding individuals' personal
information.
Improved Security: VPD minimizes the risk of data breaches by limiting access to data that
is not necessary for users' tasks. This reduces the potential exposure of sensitive
information to unauthorized individuals.
Granular Control: VPD provides fine-grained control over data access, allowing
administrators to tailor permissions based on individual users' roles and responsibilities.
Compliance with Regulatory Requirements: VPD facilitates compliance with data privacy
regulations, such as the General Data Protection Regulation (GDPR), by ensuring that users
only have access to the data they are permitted to view.
Flexible Implementation: VPD can be implemented using various techniques, including
row-level security (RLS), column-level security (CLS), and application context-based
security, providing flexibility in tailoring security policies to specific needs.
Despite its advantages, VPD also has some potential drawbacks:
Performance Overhead: VPD can introduce some performance overhead, particularly when
implementing complex security policies. However, this overhead can be minimized through
careful optimization techniques.
Management Complexity: Managing complex VPD policies with a large number of users
and security rules can be challenging. However, proper documentation and configuration
management practices can help mitigate this complexity.
Application Compatibility: VPD may not be compatible with all applications, potentially
requiring modifications to ensure seamless integration.

45
Task:

1. Create table with sensitive data.


In this step, you create a database table that will store the sensitive data that you
want to protect with VPD. The table should include columns for the customer ID,
first name, last name, email address, phone number, and address.

2. Insert the data into the table


In this step, you insert data into the table that you created in the previous step. This
data will be used to test the VPD policy that you will create in the next step.

3. Create a VPD Policy.


In this step, you create a VPD policy that will restrict access to the customers table.
The VPD policy will use the current user's ID to determine which customers they
are allowed to see. For example, if the current user is the sales user, they will only
be allowed to see customers with IDs 1 and 2.

46
4. Grant access to table.
In this step, you grant the sales user and the marketing user access to the
customers table. This means that they will be able to query the table using
SQL*Plus or any other SQL client.

5. Test the VPD Policy.


In this step, you test the VPD policy by connecting to the database as the sales user
and the marketing user and then querying the customers table. As expected, the
sales user will only see the first two customers, while the marketing user will see all
three

customers.

47
Conclusion:
VPD is a powerful security tool that can effectively safeguard sensitive data and enhance
data privacy compliance. Its granular control over data access and flexibility in
implementation make it a valuable asset for organizations that handle sensitive information.
While there are potential drawbacks to consider, the benefits of VPD often outweigh the
challenges, making it a worthwhile investment for data security and privacy.

48
Exp No: 9
Query Authentication
(Date)

Aim:
The objective of this experiment is to explore and understand the authentication methods, logins, and
database users in the context of SQL Server. Specifically, the aim is to investigate the different
authentication methods supported by SQL Server, including Windows and SQL Server authentication.
Additionally, the goal is to examine the setup and management of SQL Server security, focusing on
authentication modes, logins (Windows user, Windows group, and SQL Server), and database users

Objective:
Windows authentication requires a user to first authenticate to Windows with their login and
password. Once a user has been authenticated to Windows, they can then connect to SQL
Server using Windows authentication.

Query authentication

SQL Server authentication methods, logins, and database users

Setting up and managing SQL Server security is an important part of building and maintaining your
SQL Server environment.

Authentication methods supported


There are two different authentication methods for connecting to SQL Server: Windows and SQL
Server.

Windows authentication requires a user to first authenticate to Windows with their login and
password. Once a user has been authenticated to Windows, they can then connect to SQL Server
using Windows authentication. That is, provided their Windows account has been granted access to
SQL Server via a login (more on logins later). Windows authentication is tightly coupled with
Windows Security and is also known as Integrated Security. Windows authentication works great
when a person is part of a Windows domain.

Windows Authentication is the default authentication mode when installing a SQL Server instance. In
order to support SQL authentication, you need to configure SQL Server to support mixed
mode authentication. When mixed mode is used, both Windows and SQL authentication can be
used to connect to SQL Server. If SQL Server is not set up to support mixed mode, then only
Windows accounts can connect to SQL Server.

49
Setting up SQL Server to support different authentication modes

Windows Authentication is selected as the default shown with the red arrow in Figure 1. If you need

radio button. Upon clicking this button, the SA account password boxes would become enabled, and
you would need to specify a password for the SA account.

How to determine which authentication methods are supported

Another method to check which authentication modes are set up is to use TSQL code. The code in
Listing 1 displays the Authentication mode setup.

50
SQL Server logins

In order to connect to SQL Server, one must have access to SQL Server. Access is granted
via a login. A login is also known as a security principal, and is stored in the master
database. There is one exception, and that is accessing a contained database

There are three types of logins that are stored in the master database: Windows user,

A Windows user login provides access for a single Windows user. When creating this type of
login, no password is needed when defining the login in SQL Server. This type of login
requires the user to first validate their login by logging into the Windows domain. The
Windows domain stores the password.

A SQL Server login is similar to a Windows login in that it provides access to SQL Server for a single
user, but it is different than a Windows login because the password for a SQL login is stored in the
master database.

The last type of login, a Windows group login, is similar to a Windows login but slightly different.
A Windows group login provides access to a SQL Server instance for every Windows login that is a
member of the group. Windows groups are a great way to provide access to many Windows logins
with only having to define a single login in SQL Server. Using a Windows group, access to the SQL

51
Server instance can be maintained by adding or removing group members. Using Windows groups
helps minimize security management efforts and troubleshooting login related security issues.

Windows logins are considered more secure because of the way the password for the login is stored.
The password for a Windows login is stored using true encryption. Where as the password for a
SQL Login is not encrypted, instead it is hashed. Because a SQL login is hashed makes it easier to
crack

as SQL logins the database administrators set up the login and password. By having the domain
passwords provides another layer of security, commonly called separation
of
duties. By separating the duties of creating and managing Windows logins from managing
databases and access to databases, provides an additional security controls to gain access to data
stored in SQL Server.

provide users access to any data in the different databases on the server. For a login to read and/or
write data to a database, the login will need access to one or more databases. A login can be set up
to have access to many databases on an instance if required.

Database users
A database user is not the same as a login. A login provides to a user or application the ability to
connect to a SQL Server instance, whereas a database user provides the login rights to access a
database. Each database a login needs access to will require a database user to be defined, except
when a login has been given sysadmin rights.

Creating a database user while creating a new login

52
A red box shows the list of databases in Figure 5, where my new login can be mapped. In order to
-

Creating a new database user and mapping it to an existing login


There are times when a login has already been created, and it just needs access to one more
database. For example, suppose I now wanted my established Red-Gate SQL Server login to access
the
-Gate login additional database access, I have a
number of options. One option would be to just modify the user mappings by changing the
properties on the login. This would be similar to how I just added the user mapping when I created
the Red-Gate login.

53
Adding a new database user

There are four other types: SQL user without login, User mapped to a certificate, User mapped to an
asymmetric key, and Window users. Since I am creating a database user that will be mapped to a SQL
login, I use the default. Next, I enter the database user name for the user I am creating. It could be any
name, but I prefer to make the database user name match the same name as the login it is associated
-

The last item needed is to define a default schema for this login. A schema name is associated with a
database object collection owned by a database user. By default, each database has a schema named
specify a schema when you define a new
database user.

54
Exp No: 10
XML DATABASE SECURITY
(Date)

Aim:
The aim of this experiment is to assess and verify the system requirements for utilizing
Oracle XML Security. Specifically, the focus is on ensuring that the environment meets the
necessary conditions for the effective deployment of Oracle XML Security. The primary
requirement identified is the necessity of having JDK 5 (Java Development Kit) or a higher
version installed on the system.

Objective:
The primary objective of this experiment is to evaluate and confirm the system's
compatibility and readiness for deploying Oracle XML Security. The specific focus is on the
verification of a key system requirement, which mandates the presence of JDK 5 or a
higher version

System Requirements

In order to use Oracle XML Security, you must have JDK 5 or higher

Decide How to Sign Binary Data

It is also possible to sign binary data. To do this you must make the binary data available through a URI.
Oracle XML Security allows any URIs that can be resolved by the JDK, such as http:, file:, and zip: URIs.

55
You need to create a separate XML document which will hold the Signature element, and this
signature will refer to the binary data using this URI.

Indeed you can sign XML data using this mechanism as well, provided your XML data can be accessed
by a URI. But for XML you can decide to either treat it as binary data and sign as is, or apply
canonicalization and sign as XML. To apply canonicalization you need to add a canonicalization
transform.

If your binary data is present as a base64 encoded string in your XML document, you can use an ID-
based or an Xpath-based reference to it, and then use a Base64DecodeTransform to decode the data and
sign the binary.

Sign Multiple XML Fragments with a Signature

You can include multiple XML fragments into the same signature. For example, you can have two
ID- based references, and include both of them in the same signature. Or you can use an Xpath
expression which resolves to multiple subtrees.

You can also mix and match local ID-based references with remote URI references, and have all of them
in the same signature.

In fact it is recommended that you include multiple parts into the same signature to cryptographically bind
them together; for example, if you are using an XML signature to sign a purchase order approval, you must
include the items that are being purchased, the user who approved it, and time it was approved, all in the
same signature. If you forget to include the user, somebody can potentially steal this message, change the
user name, resubmit it, and the signature will still verify.

Decide on a Signing Key

Once you have decided what to sign, and how to reference it, you need to decide on a signing key. Options
include:

Use a X509Certificate.

56
This is the most common mechanism. You sign with the private key, and anybody who has your
public key can verify with it.

Use a raw asymmetric signing key, like a DSA, RSA, or DH key.

When you are signing with an X509certificate, you are in fact signing with the DSA/RSA/DH
signing key that is associated with the certificate. You can also sign with DSA/RSA/DH signing
key that is not associated with any certificate, although there is no good reason for doing so.

Use a symmetric key.

You can also do HMAC signing with a symmetric key. This is useful when you and the verifier
already share a symmetric key; it could be a key derived from a password, or it could be from a
kerberos system which uses symmetric keys. The Oracle Security Developer Tools WS Security
APIs provide explicit APIs for password-based keys and kerberos keys.

Provide a Receiver Hint

You also need to provide a hint to the receiver so that it knows how to verify your signature. This will
be in the <dsig:KeyInfo> tag inside the <dsig:Signature>. This can be accomplished in different ways:

You can provide no hint at all. This perfectly acceptable, if you have already communicated the
key to the receiver, and the receiver is expecting all signatures to be signed by this key.
However this is not a likely situation.
When signing with an X509Certificate, you can provide one or more of the following:
The entire X509Certificate. This is the most common usage.
The Subject DN of the certificate This is useful when the receiver has access to a
LDAP directory, and it can look up the certificate based on the DN.
The SubjectKeyIdentifier or the IssuerDN/Serial number pair This is useful when
the receiver is only expecting a signatures from a set of certificates, and it every
time it has to verify a signature, it can loop over all the certificates and find the one
with matching SKI or IssuerSerial.

How Data is Verified

This section explains the concepts behind data verification.

Once you understand how to create a signature, you can use similar steps to verify the signature. The basic
steps are as follows:

1. Search for the signature element, and check what was signed

When you first search for the signature element in the XML document. Oracle XML
Security provides a method (put in link here) to list the elements included in this signature.
Verify that those are the elements you were expecting to be signed.

2. Fetch the verification key

Next identify the key with which the signature was signed. To do this, examine
the <dsig:KeyInfo> for the certificate, raw public key, or symmetric key that should be used for
verification.

57
Identify what to Encrypt: -

The most common encryption scenario is to encrypt and replace. When you are encrypting a part of the
document, replacing the document with the encrypted bytes.

If you encrypt the importantInfo element

Here the entire <importantInfo> and all its contents are replaced by an EncryptedData element which
essentially contains a large base64 string, which is the base64 encoding of the
encrypted <importantInfo> element.

The Content Only Encryption Mode

There is also a "Content only" encryption mode where the element tag itself is not encrypted, but all its
contents are encrypted.

<myDoc>

<importantInfo>

<xenc:EncryptedData>

...

</xenc:EncryptedData>

</importantInfo>

</myDoc>

Use the "Content Only" mode if it is appropriate for everyone to know that the <importantInfo> exists;
only the intended party will know how to decrypt and look at the contents of the <importantInfo> element.

58
Encrypting Binary Data

If you are encrypting binary data present as a base64 encoded string, you can encrypt it as if it were regular
XML data.

However if you are encrypting external binary data (that is, data outside the XML document), your options
depend on where you will store the encrypted data.

Store Externally

One option is to store the encrypted data externally as well. For SOAP Attachments refer to the WS
Security SOAP Attachments (insert link) which specifies a mechanism to encrypt attachments and store
the encrypted data back as an attachment.

To store the encrypted data externally, you need to use a xenc:CipherReference, which is a subelement
of xencEncryptedData and uses a URI to refer to the encrypted bytes.

Store Internally

The other option is to store the encrypted bytes inside the EncryptedData, just as you would with in-place
XML encryption

How Data is Decrypted

Data decryption follows the same process as for data encryption, but in reverse. The basic steps are as
follows:

If the data was encrypted with a simple encryption in place, locate the EncryptedData element and look at
its KeyInfo.

If it is directly encrypted with a known symmetric key, decrypt

it. Otherwise if it is encrypted with a random symmetric key:

locate the corresponding EncryptedKey,


decrypt it first, and
use this decrypted random symmetric key to decrypt the EncryptedData.

Construct the Wrapper Object

To construct a wrapper object from the DOM element, simply invoke the

constructor. For example:

Element sigElem =

(Element)doc.getElementsByTagNameNS(XMLURI.ns_dsig, "Signature").item(0);

XSSignature sig = new XSSignature(sigElem);

59
To construct a Wrapper object when the DOM element does not exist, you can either:

create a DOM element, and use the above method,


or use a newInstance method
XSSignature sig = XSSignature.newInstance(doc, null);

Parse Complex Elements

Whenever there are complex elements containing a hierarchy of subelements, there will also be an
equivalent hierarchy of wrapper objects. For example, suppose you have an incoming document
containing a signature:

<dsig:Signature>

<dsig:SignedInfo>

<dsig:CanonicalizationMethod ... />

...

<dsig:SignedInfo>

<dsig:SignatureValue>..</dsig:SignatureValue>

...

</dsig:Signature>

Most of these elements have a corresponding wrapper class, such as dsig:Signature -> XSSignature,
dsig:SignedInfo -> XSSignedInfo, dsig:SignatureValue -> XSSignatureValue and so on.

But when you construct the XSSignedInfo object from the dsig:Signature DOM element, it does not
construct any of the child objects, in fact it does not even look at any of the child elements. The
new XSSignature(sigElem) is a quick call which simply creates an object with the data member pointing to
the sigElem. The child objects are created every time. So when you call XSSignature.getSignedInfo() it
searches the child elements of dsig:Signature to find the dsig:SignedInfo element, constructs a wrapper
object on that element, and returns it.

Variations on the Basic Signing Procedure

Variations on the basic signing procedure include multiple references, enveloped signatures, XPath
expressions, certificate hints, and HMAC key signing.

8.8.2.1 Multiple References

To include multiple references in a signature, simply add more XSReference objects to


the XSSignedInfo object. Each XSReference object needs its own list of transforms.

8.8.2.2 Enveloped Signature

To use an enveloped signature, add the enveloped signature transform to the reference. This means
inserting the following code just before the code that adds the exclusive transform:

60
XSAlgorithmIdentifier transform1 =

new XSAlgorithmIdentifier(doc, "Transform",

XMLURI.alg_envelopedSignature);

ref.addTransform(transform1);

Basic Procedure to Check What is Signed

To verify a signature, first locate the <dsig:Signature> element in your document, then use it to construct
the XSSignature wrapper object.

XSSignature sig = new XSSignature(sigElem);

Next, fetch the KeyInfo of the signature and examine the key to determine if you trust the signer. There are
different ways to deal with the KeyInfo:

For very simple cases, you may already know the verification key in advance, and you do not
need to look at the KeyInfo at all.
In most cases, however, you should look at the KeyInfo. One way is to set up callbacks, so
when you call XSSignature.verify() you call it with no verification key. Internally, the Oracle
Security Developer Tools look at the KeyInfo to see if it invokes a callback to fetch the key.
The other option is to proactively look into the KeyInfo and determine the key yourself.

Set Up Callbacks

If the KeyInfo Contains the Signing Certificate

If you expect the KeyInfo to contain the signing certificate, and you do not already have this certificate,
but you have set up the trust points, you just need to set a certificate validator callback.

// Create your certificate validator

CertificateValidator myValidator

= new CertificateValidator() {

public void validateCert(CertPath cp) {

// Code to validate the certificate

};

KeyRetriever.setCertificateValidator(myValidator);

61
The Oracle Security Developer Tools API retrieves the certificate from the KeyInfo and invokes your
callback; if the callback returns true, it will verify with that certificate.

If the KeyInfo Contains a Hint

If you expect the KeyInfo to contain only a hint to the signing certificate, that is, the subjectDN or
Issuer Serial or subject key identifier, write a KeyRetriever to fetch a certificate from a certificate store
given this hint.

Write a Custom Key Retriever

If these built in retrievers are not suitable, you can write a custom KeyRetriever by deriving from
the KeyRetriever class; for example you could do this when you expect the KeyInfo to contain
a subjectDN, and you will look up an LDAP directory to find the certificate for that DN.

KeyRetriever myRetriever = new KeyRetriever() {

X509Certificate retrieveCertificate (KeyInfoData keyInfo) {

// write code to fetch the certificate from

// the certificate store based on keyInfo

PublicKey retrieveCertificate (KeyInfoData keyInfo) {

// write code to fetch the PublicKey from

// the certificate store based on keyInfo

};

KeyRetriever.addKeyRetriever(myRetriever);

62

You might also like