# Web security The basic structure of a web app or website is based on HTTP(S) protocol. It's very important in this context to filter and validate client input carefully. It's common to assume that all the clients are attackers, since the client is the only part of the software that the attacker can use. ## SQL Injection SQLi can happen every time the input fields are not-sanitized input in web forms. Closing a string with the caracter `'` or the query injecting `;`, as well as commenting ( `--`) or using operators such as `UNION` and `INTERSECTION` can be exploited to bypass password checking or completely bypass the query system. Examples: ````sql SELECT name, phone, address FROM Users WHERE Id='userinput'; ```` can become: ````sql SELECT name, phone,address FROM Users WHERE Id='' or '1'='1' ;--'; ```` injecting `' or '1'='1' ;--` . Also `UNION` operator permits to concatenate the output of multiple queries, even a query on a different table from the original one. **SQL injection prevention**: - **Prepared statement**: generate a query with placeholders where the users input is seen as parameter and not as SQL. **Not** build queries by string concatenation. - properly sanitize input - limit query privileges to limit damages ### Blind SQLi Blind SQLi is similar to normal SQLi injection but involves retrieving data not directly but posing a series of queries to the database. An example is: ```sql Username = "whatever' AND EXISTS (SELECT * FROM User WHERE username='martino' AND password LIKE 'a%')" ``` This injection uses the `EXISTS` statement to check if a password exists that starts with the letter "a". If username password indeed begins with "a", the login attempt will be successful. Otherwise, the login will fail. To discover the entire password, the attacker can employ a bruteforce technique. By trying different starting letters for the password in the injection code, the attacker can determine the correct value through trial and error. ## XSS We can call XSS (Cross Site Scripting) any stuff that can be exploited by the attacker to inject into a web page a script. There are three types from an higher point of view: - **Stored XSS**: the attacker input is stored on the target server's database. This happens if the malicious code is not filtered out. - **Reflected XSS**: the malicious code is not stored on the server. An example of reflected XSS involves appending a parameter and a JavaScript script to a URL via a GET request. If the input is not sanitized, this can be risky as the script is treated as a parameter and may result in an error page or load a generic page containing the injected script. Example: Let's say the search term gets reflected in the page of the website in case of error. The URL for the search is like this: `www.example.com/search?term=test`. An attacker could craft a URL like `www.example.com/search?term=<script>malicious_code_here</script>` and trick a user into clicking it, causing the execution in the user's browser. - **DOM-based XSS**: basically the previous one ... the only big difference is that the attack remains completely in the user's browser. Examples: ### XSS bypasses Same Origin Policy **SOP** is a paradigm which is based on the rule: > "all client-side code (e.g., JavaScript) loaded from origin **A** should only be able to access data from origin **A**" where an origin is identified by the tuple: `<PROTOCOL,HOST,PORT`. It's easy to see that XSS bypass this simple rule and also in nowadays it's not rare that applications permits to share resources to enhance services. A solution could be to blackilist everything that may be misinterpreted but it's not a good approach. ### CSP **CSP3** (Content Security Policy) is the most valid defensive measure to mitigate XSS. It's a set of directives sent by the server to the client in the form of HTTP response headers which specifies what should be trusted and what shouldn't. CSP in theory is effective against XSS, but since the policies are written manually by devs and they must be to keep updated, they often are not effective to mitigate such attacks. ## Cookies Cookies are commonly used to store information about the HTTP session (making it "stateful"). Cookies are basically small text files on a user's browser. They can also be used to track the user across different websites. However, this can create security vulnerabilities. For example, a server can generate a SessionID as a cookie on the client to identify and store conversational data about them. It is essential to ensure that session tokens are crafted in a secure manner to prevent exploitation. If used for authentication, sensitive data should **not be stored in plaintext**. If used for session identification, they should **not be predictable**. Additionally, session tokens should have a clear and different **expiration date** from the cookie itself. ### Cross-Site Request Forgery (CSRF) A CSRF attack exploits cookies to force a user to execute unwanted actions on a web application in which he is currently authenticated using ambient credentials (**cookies**). In theory, CSRF attacks occur when a state-changing action is allowed based on cookie validation. The attack involves four steps: 1) victim signs in on a website using cookies 2) victim visits a malicious site or clicks on a link 3) malicious site generates a fake request using XSS techniques 4) the victim's web client executes the malicious web request, tricking the original website's authentication by using ambient variables. ![](images/Pasted%20image%2020230622105038.png) Another way to use CSRF is to **steal** a session cookie: the attacker can gain access to the admin's session by exploiting session cookies. They do this inserting in a vulnerable page a XSS code designed to extract and publish in the website as a comment/post the session cookie. This allows the attacker to collect the session cookie of the admin. #### CSRF Mitigation Techniques CSRF attacks can be mitigated using techniques such as CSRF token and Same Site Cookies policy. The CSRF token method involves generating **random** tokens associated with the user's session. These tokens are regenerated for every request. The client sends these tokens to the server, and the requests are only confirmed if they match the tokens stored on the server. It is crucial that the token is implemented correctly! For example in some old exams, the CSRF token was static and not saved in the database, making it vulnerable to SQL injection attacks. The **Same Site** Cookies policy works by setting an additional 'SameSite' attribute when the cookie is created. This attribute instructs the browser to attach the cookie only to same-site requests, rendering CSRF attacks ineffective.