Protecting against Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF)

Protecting against Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF)

PHP programming is crucial for protecting a web application from any type of system attack like cross-site scripting (XSS) and cross-site request forgery (CSRF) or for maintaining the security and integrity of any web application. For any developed website or web app, cross-site scripting (XSS) and cross-site request forgery (CSRF) are essential elements in maintaining the reliability and real-time behaviour of the website or application.

Protecting against Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF)

So, let’s take a closer look at the cross-site scripting (XSS) and cross-site request forgery (CSRF) features in PHP programming.

Cross-site scripting (XSS) in PHP programming.

What are XSS features?

Cross-site scripting (XSS) activities are performed on any website or web app when a malicious user intruder attacker intentionally creates or inserts infected web script, typically JavaScript source code, into a website, which is then executed in the web browser by another web visitor or attacker user.

Damage to websites or web apps can include.

  • Hijacking existing website sessions and stealing information such as login session cookies, user tokens, etc.
  • Redirecting random web visitors to infected malicious websites or apps.
  • Stealing data from websites or apps, such as authenticating user input or login credentials, and then demanding ransom.

Types of XSS in PHP

  • Stored XSS – Malicious JavaScript source code is permanently stored on a targeted web server, such as a web or app database, and later provided to the user.
  • Reflected XSS – Malicious JavaScript source code is reflected directly from the web server, such as through query parameters, without being stored on the backend web server.
  • DOM-based XSS – This attack occurs when malicious JavaScript source code is executed by a web visitor’s web browser due to user modifications to the DOM (Document Object Model) on the Internet.

How to protect against XSS attacks in PHP.

  • Escape output – Escape HTML, JavaScript, and CSS in output to prevent the execution of any malicious JavaScript source code.
  • HTML escaping – This method uses a function like htmlspecialchars() in PHP to convert special characters into HTML entities.
  • JavaScript Escaping – This process uses a function like json_encode() to escape dynamic values ​​when inputting or entering them in JavaScript programming.

Example of preventing XSS attacks in PHP.

<?php

// Let’s create a program to output escaping in PHP to prevent XSS attack

$visitor_input = $_POST[‘visitor_input’];

echo htmlspecialchars($visitor_input, ENT_QUOTES, ‘UTF-8’);

?>

The fix here is that any web visitor input is presented as text in a secure format, not as execution-compatible HTML or JavaScript source code format.

Content Security Policy (CSP) concept in PHP.

CSP features help protect the system from XSS attacks by allowing web visitors to determine which sources are trustworthy when exploring web content. For example, “Reliable Web Script Sources” prevents unauthorized web scripts from running in the current web environment.

Example of a Secure header.

Content-Security-Policy: script-src ‘self’ https://trusted-source.com

This restricts JavaScript programming in the Secure header to only loading from the trusted-source.com domain and the current origin (‘self’).

Cleanse user input in web systems.

When accepting web visitor user input, such as random user comments, user-filled form data, or data from a backend server, clean user input to remove any potentially harmful web scripts.

To keep web systems operational, built-in libraries like HTMLPurifier (PHP) or DOMPurify (JavaScript) help clean and activate HTML content information.

Use a framework with built-in security in your web system.

Modern web frameworks, such as Laravel, Django, React, and Agular, automatically escape output, reducing the risk of XSS vulnerabilities in web systems.

Cross-site request forgery (CSRF) concept in PHP.

What is the CSRF concept in PHP?

Web application cross-site request forgery (CSRF) occurs when a malicious Internet user forces an authenticated user to perform an intentional task on a website. Forcing actions where the user is already logged in, such as modifying account settings, transferring funds, etc., involves the visitor’s web browser automatically including the web user’s credentials (cookies) in the request, allowing the attacker to perform unwanted actions as the authenticated user.

How to protect against CSRF attacks in PHP.

Use a PHP CSRF token.

Generate a unique CSRF token for each form or Ajax request in your web application or website and ensure that this token is included in every system request.

The web server checks the token against the token stored in each user’s login session. If these tokens do not match, the request is rejected.

Example of generating a CSRF token in PHP.

<?php

// Let’s begin the session and generate a CSRF token

session_start();

if (empty($web_SESSION[‘csrf_token’])) {

$web_SESSION[‘csrf_token’] = bin2hex(random_bytes(32)); // Here it generates a secure random token for web requests

}

?>

Example of including a token in an HTML form.

<form method=”POST” action=”process_form.php”>

<input type=”hidden” emp_name=”csrf_token” value=”<?php echo $web_SESSION[‘csrf_token’]; ?>”>

<!– let add sme Other form fields –>

<button type=”submit”>Submit value</button>

</form>

Example of verifying a CSRF token in a PHP program.

<?php

//let create the form handling code

session_start();

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) {

if (isset($_POST[‘csrf_token’]) && $_POST[‘csrf_token’] === $_SESSION[‘csrf_token’]) {

// Here it processes the form safely to verify the CSRF token

} else {

// It checks the unauthorized CSRF token – reject the user request

die(“unauthorized CSRF token”);

}

}

?>

Explanation of verifying a CSRF token.

  • In this program, the CSRF token is stored in the user session and added to the form as a hidden input field in the web script.
  • When a form is submitted by an online web visitor, the web server checks whether the user token submitted in the current system matches the token stored in the session. If these do not match the existing token, the web request is rejected.

Using SameSite cookies in PHP.

Apply SameSite attributes to web cookies to prevent multiple client web browsers from sending cookies with cross-origin user requests.

Example of SameSite cookies.

setcookie(‘session_id’, $session_id, [

‘samesite’ => ‘Strict’,

‘secure’ => true, // here it fixes it’s sent over HTTPS

‘httponly’ => true, // here it restricts access from JavaScript

]);

SameSite cookies can be set to.

  • Strict – In this process, the web cookie is sent only in first-party references. For example, it is not sent with cross-origin requests.
  • Loose – In this process, the cookie is sent with top-level navigation and GET user requests.
  • None – This method sends a web cookie with all web visitor requests. This is not recommended unless the web visitor requires cross-origin cookies.

Ensure POST requests for sensitive actions in PHP.

To prevent CSRF attacks in web scripts, it is essential that sensitive system activities, such as changing online passwords or making online payments, are only accessible through POST web requests, not GET requests.

Double-Submit Cookies Concept.

This is another popular double-submit cookie pattern method. In this method, a CSRF token is sent in both the web cookie and the user request parameters. The web server checks whether the two token values ​​match.

This method works properly, but using a CSRF token in the form is generally more secure and reliable.

Combining both XSS and CSRF protection in PHP.

  • Following secure coding concepts in any web app or website can mitigate both XSS and CSRF risks.
  • Always sanitize and escape web visitor input to prevent XSS attacks on your website or app.
  • Apply CSRF tokens to forms and Ajax requests to prevent CSRF attacks on your website or app.
  • Use secure HTTP header mechanisms like Content-Security-Policy to protect against XSS attacks on your web system or server.
  • Apply SameSite cookie attributes to help protect your website from CSRF.

A summary of XSS protection and CSRF protection in PHP.

PHP XSS protection features.

  • Escape output – This method replaces user input with code in the session data value. Use the htmlspecialchars() function in PHP and the equivalent method in other programming languages.
  • Content Security Policy (CSP) – Apply a CSP method to limit who can load web scripts from within a web app or website.
  • Sanitize input – Use built-in libraries like HTMLPurifier or DOMPurify to sanitize user-supplied HTML input in a live web session.
  • Use a secure framework – To protect against these threats or web attacks, use modern advanced web frameworks like Laravel, React, and Agular, which automatically manage various XSS vulnerabilities in online backend systems.

CSRF protection concepts in PHP.

  • Use CSRF tokens – Add a unique CSRF token to the HTML forms you design on your website and validate them server-side in the backend.
  • SameSite cookies – Set the SameSite attribute on cookies in your web system to prevent them from being sent with cross-origin system requests.
  • Use POST for sensitive actions – Ensure sensitive actions use the POST method instead of the GET PHP method.
  • Validate requests – Always validate the source and method of system requests that modify user data.

Leave a Reply