MITM, CSRF, and XSS: How to Prevent Famous Cyber Attacks
What every web developer should never ever miss
--
These are some of the very famous attacks that could happen to any website. We will cover a summary of these attacks and how you can protect against them.
MITM
Man-In-The-Middle. It happens when an attacker is between the client and the server and listening to all their communications.
Famously happens when the client has malicious software like cracks and trojan code or downloads an unknown application sent via Whatsapp or Email.
These attacks can steal sensitive information or alter the request data.
To protect against it:
- Always use requests with TLS to encrypt the data and you can generate these certificates for free using Let’s Encrypt.
- Set
Set-Cookie
header to havesecure
in order to only pass cookies while in HTTPS mode - Redirect all HTTP to HTTPS on the server level
- Use HSTS by setting
Strict-Transport-Security
header to force redirecting the client to use HTTPS for all subsequent requests
CSRF
Cross-Site Request Forgery. It happens when an attacker phishing website shows an identical design of the website and sends requests to the server on behave of the client. The server won’t have an idea that this the attacker.
To solve this:
- Set
Set-Cookie
header to havesameSite=lax
to prevent the attacker from attaching cookies when sending requests to the server. - Use CSRF token middleware to generate a random token for the user session and attached to the client requests to verify these requests generated from the correct client.
XSS
Cross-Site Scripting. It happens when a script is injected into the client UI and it gains access to read sensitive information or send requests on behave of the client.
It can happen if the client has an unsanitized input control that prints text things directly to the UI or sends requests to the server without sanitization.
An example can be a contact form that could run a script on the backend and hijack admin data or prevent the user from even logging in. (This one happened to one of my clients)
To Solve this:
- Set
Set-Cookie
to havehttpOnly
to prevent Javascript from accessing the cookies usingDocument.cookie
- Add
Content-Strict-Policy
header to specify which external content can the client uses. This can be set for images, scripts, styles, and media.