# WEB ATTACKS ### What do you mean by web attacks? Imagine this: you're at a computer rental shop, engrossed in a game or chatting with friends online. Suddenly, the screen goes dark, cutting you off mid-task. You reboot, only to find strange posts on your Facebook timeline—posts you didn't make. It happened to me. At first, I brushed it off as a prank, but it was a stark wake-up call to the dangers of web attacks. In today's digital age, our every click and keystroke is vulnerable to exploitation. From stolen passwords to hijacked accounts, the risks are real. But awareness is key. By strengthening passwords and staying vigilant online, we can protect ourselves from falling victim to cyber threats. It's not just about safeguarding our accounts—it's about safeguarding ourselves. ### Understanding Web Attacks Imagine you're building a sandcastle on the beach. It's your little corner of paradise, where you can relax and have fun. But then, out of nowhere, a sneaky wave comes crashing down, threatening to wash away your creation. That's kind of what web attacks are like, they're malicious waves that try to ruin the fun of browsing the internet. ### Types of Web Attacks There are many different types of web attacks out there, each with its own unique set of tricks and tactics. From phishing scams that lure you into revealing sensitive information to malware that infects your computer with nasty viruses, these attacks come in all shapes and sizes. One particularly sneaky type of web attack is called SQL Injection. It's like a stealthy ninja slipping through the cracks in your website's defenses. By injecting malicious code into vulnerable parts of a website, hackers can gain unauthorized access to databases and steal sensitive information. You might have heard about a recent incident at CTU (no, not the Counter Terrorist Unit from that TV show). In this case, hackers used SQL Injection to break into the university's payroll system, gaining access to confidential data like employee's records and financial information. It was a wake-up call for everyone to tighten up security measures and protect against these kinds of attacks. ### Web Attacks IRL In a chilling real-life incident of a web attack, the Cebu Technological University found itself at the mercy of hackers wielding SQL injection. The hackers, delivering a direct message to Mr. Gil Piramide, the university was warned previously to address vulnerabilities within their systems. While some issues were rectified, the critical SQL injection flaw in the payroll system's login page remained unattended. With a pointed message, the hackers proceeded to unveil the "sweldo reveal" of all university employees. Shockingly, the post included actual payslips, adding insult to injury. Not only did the hackers expose sensitive information, but they also highlighted the negligent storage of passwords in plain text—a glaring security oversight. Despite the lack of physical damage, the repercussions were significant. Beyond the compromised data and compromised trust, the incident underscored the importance of robust cybersecurity measures. The hackers signed off with a list of aliases, a reminder of the shadowy world of cyber threats lurking beyond the digital veil. This incident serves as a stark reminder of the ever-present dangers of web attacks. It emphasizes the critical need for organizations to prioritize cybersecurity and address vulnerabilities promptly. Failure to do so not only jeopardizes sensitive information but also risks irreparable damage to reputation and trust. ![440323141_122146535282196586_8891349419065897985_n](https://hackmd.io/_uploads/HJfgT0hMR.jpg)![440465112_122146535060196586_8522463647061485662_n](https://hackmd.io/_uploads/HkFgpR3GC.jpg) ![440470916_122146535396196586_1053290076009068669_n](https://hackmd.io/_uploads/r1TeaC2zC.jpg) --- Examples of Web Attacks: [CTU on SQL Injection](https://www.facebook.com/photo/?fbid=323467550771787&set=a.123889147396296) -- --- Using a simple website, let us demonstrate the different type of web attacks a website could face. -- ## SQL Injection SQL Injection is a type of web attack which involves injecting malicious SQL code into input fields or URLs of a web application. This exploits the vulnerabilities of an application's code that does not properly validate or sanitize user input. Consider the sample code below. ```python def login(): cur = con.cursor() if request.method == "GET": if request.cookies.get("session_token"): res = cur.execute("SELECT username FROM users INNER JOIN sessions ON " + "users.id = sessions.user WHERE sessions.token = '" + request.cookies.get("session_token") + "'") user = res.fetchone() if user: return redirect("/home") return render_template("login.html") else: res = cur.execute("SELECT id from users WHERE username = '" + request.form["username"] + "' AND password = '" + request.form["password"] + "'") user = res.fetchone() if user: token = secrets.token_hex() cur.execute("INSERT INTO sessions (user, token) VALUES (" + str(user[0]) + ", '" + token + "');") con.commit() response = redirect("/home") response.set_cookie("session_token", token) return response else: return render_template("login.html", error="Invalid username and/or password!") ``` The function `login` above implements a basic login functionality where users can login using their username and password. Let's focus first on the part of the code where the method is POST. We can notice that the code executes an sql query `"SELECT id from users WHERE username = ? AND password = ?", (request.form["username"], request.form["password"]` wherein it concatenates the user inputs username and password in the query. Inputting a valid username and password, for instance 'alice' and '12345678', will execute the sql query `SELECT id from users WHERE username = 'alice' AND password = '12345678'` which returns an id if the username and password exists in the database. Now, here's the catch. There is a way to trick this query to always return an id as long as there exists a user in the database. By entering the value of username = `' or 1=1 --`, the sql query will now be `SELECT id from users WHERE username = '' or 1=1 -- AND password = '12345678'` which always return an id (as long as there exists one) because the condition 1=1 holds true and `--` comments out the rest of the query. There are other conditions similar to `1=1` like `true` to bypass or retrieve information from the database without knowing the exact values. This is what it would look like in DB Browser. User table: ![image](https://hackmd.io/_uploads/rkeYyC3fC.png) Query: ![image](https://hackmd.io/_uploads/S1RV1AnMA.png) Result: ![image](https://hackmd.io/_uploads/BJmUkA2f0.png) The same also holds true to the GET method part of the code where it retrieves the username associated with a session token from the users table by performing an inner join with the sessions table based on the id of the user. Similar to the query on username and password, the provided SQL query is vulnerable to SQL injection due to the way it constructs the SQL string by concatenating user-controlled input (request.cookies.get("session_token")) directly into the query. By changing the session token to `' or 1=1 --`, the SQL query will be `"SELECT username FROM users INNER JOIN sessions ON users.id = sessions.user WHERE sessions.token = '' or 1=1 -- ';"` which will return the usernames of all users in the system, regardless of the validity of the session token. Note that there must be a logged in user for this to work. You might ask, how do we change the session token on our browser. Session tokens are stored in the application tab of the browser's developer tools. I will be using Edge Version 124.0.2478.80 for this example. A logged-in user would normally have their session token stored in the application tab as ![image](https://hackmd.io/_uploads/BktuSypGA.png) Given that user James is logged in, his session token will be stored in the database as shown below. ![image](https://hackmd.io/_uploads/H1W8P1TGA.png) ![image](https://hackmd.io/_uploads/HyCfDy6fC.png) ![image](https://hackmd.io/_uploads/SJcXwk6MA.png) If we perform an sql injection in the session token, we will have the following ![msedge_V6byiSOdG2](https://hackmd.io/_uploads/rJBADk6zR.gif) Voila! Since James' session token exists in the database, sql injection will retrieve his session token thus will log in to his account. Scary right? Or is it? Well, the answer is very simple. **PARAMETERIZE AND SANITIZE** To address SQL Injection attack, we must avoid directly concatenating user inputs with the sql query. This can be achieved by parameterizing queries. Instead of ```python= res = cur.execute("SELECT id from users WHERE username = '" + request.form["username"] + "' AND password = '" + request.form["password"] + "'") ``` parameterize inputs ```python= # Construct the SQL query with placeholders sql_query = "SELECT id FROM users WHERE username = ? AND password = ?" # Execute the query with the username and password as parameters cur.execute(sql_query, (request.form["username"], request.form["password"])) ``` You might think that we can still pass `' or 1=1 --` to the parameterized version. You're wrong, because in the parameterized version, escaping is automatically handled hence it will treat all user inputs as string. This prevents user input from being interpreted as SQL commands, even if it contains special characters or SQL syntax. **CONGRATULATIONS YOU ARE NOW SAFE FROM SQL INJECTION ATTACK** --- ## Cross-Site Scripting (XSS) Attack XSS attack is another type of web attack which exploits the unsanitized inputs of a web application. Consider the example XSS vulnerable site below. ![msedge_ZMUDYOlnXW](https://hackmd.io/_uploads/H1ht9epzA.gif) Code Snippet: ```html= <!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h2>Welcome, {{username}}!</h2> <a href="/logout">Logout</a> <h3>Posts</h3> <form method="post" action="/posts"> <input type="text" name="message"> <input type="submit" value="Post!"> </form> <ul> {% if not posts %} No posts. {% endif %} {% for post in posts %} <li>{{ post[0] | safe }}</li> {% endfor %} </ul> </body> </html> ``` ```python= @app.route("/posts", methods=["POST"]) def posts(): cur = con.cursor() session_token = request.cookies.get("session_token") if session_token: res = cur.execute("SELECT users.id, username FROM users INNER JOIN sessions ON users.id = sessions.user WHERE sessions.token = ?", (session_token,)) user = res.fetchone() if user: user_id = user[0] message = request.form["message"] cur.execute("INSERT INTO posts (message, user) VALUES (?, ?)", (message, user_id)) con.commit() return redirect("/home") return redirect("/login") ``` Notice that when we input `<script>alert("you've been hacked")</script>` in the posts' input box and proceeded with post, it executed the input as a script showing the actual alert modal. The script is now stored in the database and everytime we load the website, it will always execute the script. This is a sample of stored XSS. ![image](https://hackmd.io/_uploads/HJCehe6GC.png) Imagine if this is a serious malicious script, the effect would be devastating. Hence, it is important to always implement input sanitization to escape special characters and converting special symbols to their corresponding plaintext representation treating them as a plaintext, thus preventing script injection. To fix the code above, we will use the markupsafe library of python which mitigates script injection attacks by escaping and replacing characters. Fixed Code: ```python= from markupsafe import Markup, escape @app.route("/posts", methods=["POST"]) def posts(): cur = con.cursor() session_token = request.cookies.get("session_token") if session_token: res = cur.execute("SELECT users.id, username FROM users INNER JOIN sessions ON users.id = sessions.user WHERE sessions.token = ?", (session_token,)) user = res.fetchone() if user: user_id = user[0] message = escape(request.form["message"]) cur.execute("INSERT INTO posts (message, user) VALUES (?, ?)", (message, user_id)) con.commit() return redirect("/home") return redirect("/login") ``` Basically what we did here is just enclosing the input message from the form with escape to sanitize the input. Script inputs will now be treated as a text and will not be executed. ![image](https://hackmd.io/_uploads/BJsK-WpM0.png) ![image](https://hackmd.io/_uploads/rJe2teZpG0.png) Cross-Site Scripting attacks may seem like harmless pranks, but they can have serious consequences if left unchecked. By staying informed, practicing good cybersecurity habits, and implementing proper input sanitization techniques, we can protect ourselves and others from falling victim to these sneaky tricks. So, the next time you're browsing the web, remember to keep an eye out for those sneaky scripts and stay safe out there! **Congratulations, you are now invulnerable form XSS Attack!!!** --- ## Cross-Site Request Forgery Cross-Site Request Forgery (CSRF) is a type of web security vulnerability that allows an attacker to trick a user into executing unintended actions on a web application in which they are authenticated. In a CSRF attack, the attacker crafts a malicious request and tricks the victim into unknowingly submitting that request, typically by luring them to click on a specially crafted link or visit a malicious website while authenticated to the target web application. When the victim's browser sends the request, it includes any credentials (such as session cookies) associated with the target web application, making it appear as if the request originated from the victim. CSRF attacks can have serious consequences, such as unauthorized actions performed on behalf of the victim, including changing account settings, making financial transactions, or even performing actions with administrative privileges if the victim is an administrator. To mitigate CSRF attacks, web applications typically use CSRF tokens. These tokens are unique, randomly generated values that are included in forms or URLs generated by the application. When the user submits a form or clicks a link, the server verifies that the CSRF token is valid, ensuring that the request originates from the legitimate user and not from an attacker. To mitigate this type of attack, we will use python's itsdangerous library which is used for creating signed cookies, and protecting against CSRF attacks. `serializer = URLSafeSerializer(secrets.token_hex(32))` generates the CSRF token. CSRF attacks may seem like something out of a spy movie, but they're a real threat lurking in the shadows of the internet. By staying vigilant, being cautious of suspicious links, and relying on trusted websites, we can protect ourselves from falling victim to these cunning tricks. So, the next time you're exploring the digital jungle, keep your guard up and watch out for those sneaky CSRF traps!