Database Security Lab Manual
Database Security Lab Manual
ENGINEERING
Lab Manual
Type
CSD5003 Database Security LTP 4
Index
Exp. Name of the Experiment Date Page Remark
No. Number
Objective:
Algorithm: N/A
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.
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:
To set the default tablespace for the user, you can use the DEFAULT
TABLESPACE clause:
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.
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.
Make sure you are connected to your database as a user with administrative
privileges, such as a DBA account.
3
Step-3> Grant the necessary privileges to the role:
b. Grant the privilege to create, alter, and drop tables, sequences, and views in
the IST469 schema:
d. Commit
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.
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:
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)
Objective:
Introduction:
Algorithm:
N/A
Description: Attackers inject malicious SQL code into input fields or parameters to
manipulate the database.
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:
Prevention: Implement proper access controls, and use the principle of least privilege.
Prevention: Use strong and complex passwords, implement account lockout policies,
and use multi-factor authentication.
1. Dictionary Attack
2. Malware Injection
3. Botnet
4. Hydra
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).
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.
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:
Prevention: Keep software up-to-date, use secure coding practices, and conduct regular
security assessments.
Prevention: Implement rate limiting, use firewalls, and have a disaster recovery plan.
11
Insecure Direct Object References (IDOR):
Prevention: Implement proper access controls, validate user input, and avoid exposing
internal object references.
12
Prevention: Validate user input, use whitelisting for file inclusions, and restrict file
system access.
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:
3. SQL Injection Testing: Simulate SQL injection attacks to test the database's defenses
against this common cyberattack.
Resources Used:
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
Using a web security testing tool, like OWASP's Burp Suite, to intercept and
analyze the HTTP requests passing through the web browser.
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.
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.
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
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.
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.
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.
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
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.
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.
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: -
24
Access Control: -
Access to the database and the decrypted data should be strictly controlled.
Data Integrity: -
25
Secure Transmission: -
Data should also be encrypted during transmission between the database and applications
to protect it from interception.
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.
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: -
27
Exp No: 5 SQLite Cipher encryption
Date:
Aim/Title:
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
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)
Objective:
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:
SELECT * FROM Users WHERE Username = 'Attacker' OR 1=1 --' AND Password = '123456';
2. Tampering:
3. Repudiation:
33
Delete database event logs:
4. Information Disclosure:
5. Denial of Service:
DROP TABLE Users; --Caution: This will delete the Users table
6. Elevation of Privilege:
SELECT * FROM Admins WHERE Username = 'Admin' --' AND Password = 'AdminPassword';
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.
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.
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:
Tampering:
Repudiation:
35
Removed certain event logs from the system.
Information Disclosure:
Denial of Service:
Attempted termination of the SQL server process, potentially causing system downtime.
Elevation of Privilege:
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.
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
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.
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.
$eq = Equal to
$in = Check if the required data is present in a data structure such as pointer or array, etc.
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
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.
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.
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:
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.
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
Setting up and managing SQL Server security is an important part of building and maintaining your
SQL Server environment.
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.
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.
52
A red box shows the list of databases in Figure 5, where my new login can be mapped. In order to
-
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
To construct a wrapper object from the DOM element, simply invoke the
Element sigElem =
(Element)doc.getElementsByTagNameNS(XMLURI.ns_dsig, "Signature").item(0);
59
To construct a Wrapper object when the DOM element does not exist, you can either:
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: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 include multiple references, enveloped signatures, XPath
expressions, certificate hints, and HMAC key signing.
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 =
XMLURI.alg_envelopedSignature);
ref.addTransform(transform1);
To verify a signature, first locate the <dsig:Signature> element in your document, then use it to construct
the XSSignature wrapper object.
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 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.
CertificateValidator myValidator
= new CertificateValidator() {
};
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 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.
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.addKeyRetriever(myRetriever);
62