WebApplication Unit 3
WebApplication Unit 3
Authentication
Session management
Access control
Authentication
Authentication is the process of verifying the identity of a user or entity
attempting to access a system.
• Session IDs: Ensure session IDs are long, random, and unpredictable to prevent
session hijacking.
• Secure Transmission: Always transmit session IDs over HTTPS to protect them from
interception (e.g., use the Secure flag on cookies).
• Http Only Cookies: Use the Http Only flag to prevent client-side scripts from
accessing session cookies, reducing the risk of XSS attacks.
• Session Expiration: Implement session timeouts to limit the risk of unauthorized use
if a session ID is compromised.
• Session Regeneration: Regenerate session IDs upon privilege level changes (e.g.,
after login or privilege escalation) to prevent fixation attacks.
3. Access Control
Access control mechanisms determine what resources and actions a user is
allowed after they have been authenticated.
• Least Privilege Principle: Users should only have the minimum access
rights necessary to perform their tasks, reducing the impact of a
compromised account.
• Role-Based Access Control (RBAC): Assign permissions based on user
roles to simplify management and enforce consistent access controls.
• Horizontal and Vertical Access Control: Ensure proper checks to
prevent horizontal privilege escalation (accessing peer data) and vertical
privilege escalation (gaining higher-level access).
• Indirect Object References: Avoid exposing internal references (e.g., IDs)
directly to users; use indirect references (e.g., mapping IDs to tokens) to
prevent unauthorized access.
• Regular Audits: Perform regular reviews and audits of access control
policies and user permissions to ensure they are up-to-date and aligned
with the organization's needs.
1. Importance of Validating User Input
Ensure all input received from users is safe and does not lead to security
vulnerabilities.
Key Principle:
• Never trust user input; always validate and sanitize it before processing.
• Input Validation Techniques Whitelist Validation:Define acceptable patterns or
characters for input (e.g., only allow letters, numbers, or specific symbols).
• Ensure inputs conform to expected formats (e.g., email, phone number) by using
regular expressions.
Blacklist Validation: Use blacklists to block known dangerous inputs, though this is less secure as
attackers can find ways to bypass blacklists.
Type Validation: Ensure inputs match expected data types (e.g., numbers, strings) and reject any
mismatches.
3. Common Vulnerabilities from Improper Input Handling
SQL Injection: Occurs when user inputs are directly incorporated into SQL queries without proper
sanitization.
Mitigation: Use parameterized queries or prepared statements to prevent malicious SQL execution.
Cross-Site Scripting (XSS): Arises when untrusted user input is included in web pages without proper
encoding, allowing attackers to execute scripts in the victim's browser.
Mitigation: Ensure all user-supplied content is properly HTML-encoded before rendering it on the
page.
Command Injection: Happens when user inputs are passed to server-side shell
commands without validation, enabling the execution of arbitrary commands.
Mitigation: Use strict input validation and avoid directly using user inputs in system
commands.
4. Sanitization vs. EncodingSanitization:Clean user inputs to remove harmful characters
or patterns (e.g., stripping out HTML tags or SQL metacharacters).
• Apply context-specific sanitization based on where the input will be used (e.g., URL,
HTML, database).
• Encoding: Convert user input into a safe format to prevent malicious characters from
being interpreted (e.g., HTML, URL, or SQL encoding).
• Ensure inputs are encoded appropriately for their destination (e.g., HTML entities for
web content, URL encoding for URLs
5. Client-Side vs. Server-Side ValidationClient-Side Validation:Enhances user experience by
providing immediate feedback on input errors (e.g., form validation in browsers).
Caveat: Client-side validation is not enough for security, as it can be bypassed by attackers
Server-Side Validation :Perform strict validation on the server to ensure all inputs are
properly validated and sanitized. Server-side validation should be the primary security
measure for handling input.
Handling Input Length and TypeInput Length Limits:Set reasonable limits on input length
(e.g., restricting input fields to expected sizes to prevent buffer overflow or denial-of-
service attacks).
Type Constraints:Verify the type of input (e.g., ensuring numbers are numeric, dates are
valid) to prevent malformed data from being processed.
7. Handling File UploadsContent-Type Validation: Ensure the uploaded file's MIME type
matches the expected file type (e.g., images, documents).
File Size Limit: Restrict file sizes to prevent denial-of-service attacks through oversized file
uploads
Store Files Securely: Never execute uploaded files or allow them to be served directly from
user-accessible directories. Instead, store them securely and validate them before use.
8. Logging and Monitoring Inputs Log Malicious Input Attempts: Track suspicious inputs to
identify patterns of attacks or probing.
Monitoring: Implement real-time monitoring for abnormal inputs that may indicate
ongoing attacks, such as SQL injection or command injection attempts.
9. Context-Aware Input Handling Tailor input validation and sanitization based on the
context in which the input is used (e.g., database queries, HTML rendering, shell
commands).Use Framework-Specific Functions: Leverage security libraries or frameworks
to handle input safely in specific contexts (e.g., databases, template engines for HTML).
10. Consistent Input Handling Across Application Layers Ensure consistent validation,
sanitization, and encoding practices are applied at every point where user input is
processed, from form submission to backend data storage.
1. Boundary Validation Boundary validation involves checking whether user inputs fall within
predefined acceptable limits. This is a crucial aspect of input validation to prevent attackers from
exploiting excessive or unexpected input lengths, formats, or values that could lead to security
vulnerabilities like buffer overflows or injection attacks.
Set Minimum and Maximum Limits: Length Limits: Define acceptable input lengths to ensure they fit
within expected ranges. For instance, a username might be limited to 3–20 characters, or a postal
code limited to a specific number of digits.
Value Ranges: For numerical inputs, enforce boundaries by checking if the input falls within the
expected range (e.g., age between 0 and 120, or price not being negative).
Data Type Boundaries: Ensure inputs match the expected data types (e.g., integer, float, string).
Invalid data types can lead to errors or security vulnerabilities if the input is processed incorrectly.
Example: A form expecting a numeric value should reject alphanumeric inputs or special characters.
Pattern and Format Checking: Validate inputs based on their required formats, such as email
addresses, phone numbers, or dates.
Use regular expressions or other pattern matching methods to enforce valid formats. Example: An
email input should be checked against a regular expression to ensure it follows the format
[email protected].
Prevent Overflows and Underflows:Enforce validation to prevent buffer overflows (e.g., excessively
long inputs) or underflows
Example: Prevent attackers from entering a very large integer that could cause an arithmetic
overflow in the application logic.
2. Handling Attackers In addition to proper validation of user input, handling attackers means being
proactive in detecting and mitigating attempts to exploit vulnerabilities.
• Attackers will often probe applications for weak points, using malformed or malicious inputs to
exploit weaknesses.
Detect and Respond to Malicious InputInput Anomalies: Monitor for inputs that deviate
from expected norms (e.g., excessively long strings, inputs containing special characters
typically used in SQL injection, or XSS attacks like <script>).
Logging Malicious Attempts: Track failed or suspicious input validation attempts. Logging
these events can help identify attack patterns and aid in forensic analysis.
Example: If an attacker is attempting brute force or injection attacks, logging can provide
details such as the time of attack, IP address, and specific payloads used.
Rate Limiting and Lockout Mechanisms.
Rate Limiting: Restrict the number of requests a user or IP address can make in a short
time to prevent attackers from overwhelming the system with automated or brute force
attacks.
Example: Implement rate limiting on login forms to prevent brute force attacks that
attempt multiple password guesses.
Account Lockouts: After a certain number of failed login attempts, lock the account
temporarily to thwart brute force attacks.
Example: If an attacker tries 5 incorrect passwords, lock the account for 30 minutes or
until the user resets their password.
Reject and Sanitize Suspicious Inputs :
Reject Invalid Inputs: Upon detecting invalid inputs (e.g., an input length exceeds the
boundary, or the data format is incorrect), reject the input and provide a generic error
message to the user without revealing sensitive details.
Example: If an attacker tries to submit a script tag in a form field, reject the input and
display a message such as "Invalid input provided.
"Sanitization: Strip or escape harmful content that could be interpreted maliciously
(e.g., HTML tags, SQL commands) before storing or using it.
Example: Escape characters like <, >, &, which could be used to execute scripts if not
properly handled, especially in contexts like HTML rendering.
Honeytokens and Traps Honeytokens:
Embed hidden fields, fake forms, or dummy values in the application that attackers might
interact with. These honeytokens are designed to detect and flag malicious activity.
Example: A hidden form field could be created that no legitimate user would interact
with. If the field is tampered with, this indicates an attacker might be probing the site.
Trap Pages: Create decoy pages that attackers may try to access. These trap pages don't
contain real content but are designed to detect intrusions.
Example: If an attacker navigates to an administrative page that legitimate users cannot
access, it could trigger an alert.
Multistep Validation and Canonicalization
• A common problem encountered by input-handling mechanisms
arises when user-supplied input is manipulated across several steps
as part of the validation logic.
• If this process is not handled carefully, an attacker may be able to
construct crafted input that succeeds in smuggling malicious data
through the validation mechanism.
• One version of this problem occurs when an application attempts to
sanitize user input by removing or encoding certain characters or
expressions.