WEB security-SQL injection, CSRF cross-site forgery, OXX cross-site scripting

        

SQL injection attack

SQL injection is a type of cyber attack in which an attacker attempts to access, alter, or delete data in a database         by inserting malicious SQL code into input fields in a web application . This attack typically occurs when the application does not adequately validate or sanitize user input.

        As an example, for example, suppose there is a simple login form where the user needs to enter a username and password. On the backend, the application uses a SQL query to check if a matching user record exists in the database:

# 不安全的示例,不要在实际项目中使用
username = request.POST['username']
password = request.POST['password']

sql = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"

        The application directly inserts  username the sum  entered by the user password into the SQL query. This allows attackers to attempt SQL injection attacks by inserting malicious SQL code into input fields. as follows:

admin'--  # -- 是sql中的注释

         The SQL query becomes:

SELECT * FROM users WHERE username='admin'--' AND password=''

        "--" makes the rest of the query ( AND password='') commented out, makes the rest of the query ( AND password='') commented out.

        Python solves SQL injection

        To prevent SQL injection attacks, you should always validate and filter user input. In Python and many other programming languages, you can use parameterized queries or prepared statements to ensure that user input is not interpreted as SQL code. For example, using Python's SQLite library, you can do:

import sqlite3

# 安全的示例
username = request.POST['username']
password = request.POST['password']

conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()

sql = "SELECT * FROM users WHERE username=? AND password=?"
cursor.execute(sql, (username, password))

        Use  ? placeholders instead of inserting user input directly. Then, pass the user input as a parameter to  execute() the function. In this way, even if user input contains malicious SQL code, it will not be interpreted as SQL code, thereby preventing SQL injection attacks.

        Of course, it is also a method to reasonably control the input, such as checking the length, checking whether the characters are legal, and so on.

        

        Python's web development framework Django has a powerful ORM operation. The main ways Django ORM prevents SQL injection attacks include: using parameterized queries to generate and execute SQL statements, automatically escaping special characters in user input, providing advanced query APIs to write database queries more safely, and implementing database independence, So that developers do not need to care about the SQL dialect and security issues of specific databases. These features make Django ORM can effectively reduce the risk of SQL injection attacks.

CSRF cross-site forgery attack

        CSRF (Cross-Site Request Forgery, Cross-Site Request Forgery) is a means of network attack. Attackers induce users to perform unintended operations without awareness. This kind of attack usually occurs when the user has logged into the target website, and the attacker uses the user's login status to initiate a malicious request to achieve the purpose of the attack.

        Attack principle: The attacker constructs a malicious link or a third-party website embedded with malicious code to induce users to click or visit. When a user clicks a link or visits a website, the browser will automatically bring the login credentials (such as Cookie) of the target website to initiate a malicious request, resulting in unexpected operations.

        Suppose there is a bank website that users can access  http://bank.com/transfer?to=Bob&amount=100 to transfer money. Attackers can construct a malicious link to lure users to click:

<a href="http://bank.com/transfer?to=Attacker&amount=10000" target="_blank">
    点击领取优惠券
</a>

        When the user clicks on this link, if the user has already logged in to the bank website, the browser will bring the cookie of the bank website to initiate a request, causing the user to complete the transfer operation without knowing it. (usually happens on forms)

        In order to prevent CSRF attacks, the following methods are usually adopted:

  1. Use CSRF Token: When submitting the form, the server generates a random Token, stores it in the Session, and puts the Token in the hidden field of the form. When the user submits the form, the server will verify that the Token matches, thereby preventing cross-site requests. (Python's Django uses this)

  2. Use the SameSite Cookie attribute: Set the SameSite attribute of the cookie to Strict or Lax, so that the browser will not send cookies during cross-site requests, thereby preventing CSRF attacks.

  3. Verify Referer: Check that the requested Referer comes from a trusted source, but this method is not completely reliable, because the Referer may be tampered with or disabled.

Django prevents CSRF means

        The Django framework has a built-in CSRF protection mechanism, you only need to enable the middleware in the settings:

# settings.py
MIDDLEWARE = [
    # ...
    'django.middleware.csrf.CsrfViewMiddleware',  # 确保此中间件已启用
    # ...
]

        In the HTML template, use to {% csrf_token %}generate CSRF Token:

<form method="post">
  {% csrf_token %}
  <!-- 其他表单字段 -->
  <input type="submit" value="提交">
</form>

        When processing a form request, the framework will automatically verify the CSRF Token, and if the verification fails, the request will be refused to be processed.

        Are CSRF attacks only on forms?

        that is not.
        CSRF attacks mainly occur on form submission operations, because forms are usually used to perform sensitive operations, such as login, registration, password change, transfer, etc. But in fact, CSRF attacks are not limited to forms, it can happen to any HTTP request that can perform operations

        For example (1) Operations triggered by GET requests : Although GET requests should be idempotent, some websites may use GET requests to perform operations. Attackers can <img>trigger CSRF attacks by constructing malicious links or using tags to initiate GET requests.

<img src="http://example.com/delete?id=1" width="0" height="0" style="display:none;">

        When a user visits a web page containing this <img>tag, the browser will try to load the image, in fact, automatically initiate a GET request http://example.com/delete?id=1. Also, if the user is already logged in example.comand the server is not CSRF protected, this request could cause the user to unknowingly delete the article with ID 1.

        (2) Requests initiated through AJAX: Attackers can use JS to initiate AJAX requests on third-party websites to try to perform operations. Although the same-origin policy restricts cross-origin requests, attackers can still try to bypass the restrictions, or exploit browser vulnerabilities to initiate requests.

<script>
  function csrfAttack() {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://example.com/update");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.withCredentials = true; // 尝试发送Cookie
    xhr.send("id=1&content=Hacked");
  }
  csrfAttack();
</script>

        JavaScript example trying to launch a CSRF attack. When the user visits the webpage containing this code, the browser will automatically execute csrfAttack()the function, initiate an AJAX POST request http://example.com/update, and try to modify the content of the article with ID 1 as "Hacked".

OXX cross-site scripting attack

        XSS (Cross-Site Scripting, cross-site scripting attack) is a means of network attack. By injecting malicious scripts on the target website, when other users visit the website, the malicious scripts will be executed on the user's browser, thereby Steal user data, hijack user sessions, etc.

        There are two main types of XSS attacks: stored XSS and reflected XSS.

(1) Stored XSS: The attacker submits a malicious script to the database of the target website, and when other users visit the page containing the malicious script, the browser will execute the malicious script.

<script>/* 恶意代码 */</script>

(2) Reflected XSS: The attacker puts malicious scripts in URL parameters to induce users to click. When the user clicks on the link, the server returns the malicious script to the user's browser, and the browser executes the malicious script.

http://example.com/search?q=<script>/* 恶意代码 */</script>

        In Django templates, all variables are automatically escaped by default. This means that special characters (like angle brackets, quotes, etc.) are replaced with HTML entities, preventing malicious scripts from executing. Of course, validating and filtering user input is crucial.

{
   
   { hh }}

other attacks

        Session Hijacking: An attacker steals a user's session ID or cookie to access protected resources by posing as the user.

        Distributed Denial of Service (DDoS): The attacker overloads the target server with a large number of requests, causing normal users to be unable to access the website.

        Remote File Inclusion (RFI) and Local File Inclusion (LFI): Attackers exploit vulnerabilities in web applications to include malicious files onto servers to execute malicious code or steal sensitive information.

        Clickjacking: An attacker uses a transparent layer or iframe to trick a user into clicking a seemingly innocuous element that actually triggers a malicious action.

        etc.

 

Guess you like

Origin blog.csdn.net/lxd_max/article/details/132177320