<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Graphite Community</title>
    <description>The latest articles on Forem by Graphite Community (@graphitecommunity).</description>
    <link>https://forem.com/graphitecommunity</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1979511%2F5f03939c-5ba7-42c3-a8d8-511086bf6aed.png</url>
      <title>Forem: Graphite Community</title>
      <link>https://forem.com/graphitecommunity</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/graphitecommunity"/>
    <language>en</language>
    <item>
      <title>PREVENT YOUR BACKEND FROM SQL INJECTION</title>
      <dc:creator>Graphite Community</dc:creator>
      <pubDate>Mon, 26 Aug 2024 13:29:37 +0000</pubDate>
      <link>https://forem.com/graphitecommunity/prevent-your-backend-from-sql-injection-34kl</link>
      <guid>https://forem.com/graphitecommunity/prevent-your-backend-from-sql-injection-34kl</guid>
      <description>&lt;p&gt;This is a series of short articles by &lt;a href="https://www.instagram.com/graphitecommunity/" rel="noopener noreferrer"&gt;Graphite Community&lt;/a&gt; on software engineering and security.&lt;/p&gt;

&lt;h2&gt;
  
  
  WHAT IS SQL INJECTION
&lt;/h2&gt;

&lt;p&gt;SQL injection is an injection attack (usually from a malicious source) that uses input from the client side to perform operations on an application's database (backend/server side). &lt;/p&gt;

&lt;p&gt;This attack is common with PHP and ASP applications but needs to be looked out for and prevented when building the backend of an application.&lt;/p&gt;

&lt;h2&gt;
  
  
  RISKS POSED BY SQL INJECTION
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Privacy&lt;/strong&gt;: This attack can be used to view users' data in the database hence, breaching privacy.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Authentication&lt;/strong&gt;: This attack can be used to view users' login details hence, unauthorized access can be gotten to a user's account.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Authorization&lt;/strong&gt;: This attack can be used to view users with higher-level permission granting the hacker unauthorized access to the application. This kind of access will put the hacker in a position to perform operations which can cause more damage.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Integrity&lt;/strong&gt;: This attack can be used to tamper (write or delete) the data in the database.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  SAMPLE CODE
&lt;/h2&gt;

&lt;p&gt;This is an SQL injection caused by a dynamic query (concatenating a variable to an SQL query string)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import sqlite3

def connect_to_db():
    connection = sqlite3.connect('user_data.db')

    return connection

def get_user_input():
    customer = input("Enter a name")
    return customer

def print_result(results):

    try:
        for row in results:
            print(row)
    except TypeError as error:
        print(error)

def create_table():
    connection = connect_to_db().cursor()

    try:
        query = "create table user_data (firstname, lastname)"

        connection.execute(query)

        connection.close()

        print("Table crated successfully")

    except sqlite3.OperationalError as error:

        print(error)
        delete_data()
        create_table()

def insert_data():
    connection = connect_to_db()
    cursor = connection.cursor()

    try:
        query = "INSERT INTO user_data VALUES ('Qowiyyu', 'Adelaja'), ('Qudus', 'Babalola'), ('Tom', 'Blue')"
        cursor.execute(query)
        connection.commit()
        connection.close()
        print("Data Added to table successfully")

    except sqlite3.OperationalError as error:
        print(error)

def delete_data():
    connection = connect_to_db()
    cursor = connection.cursor()

    try:
        query = "DROP TABLE user_data"
        cursor.execute(query)
        connection.commit()
        connection.close()
        print("All data Deleted")
    except sqlite3.OperationalError as error:
        print(error)

def vulnerable_code(name):

    try:
        print(f"The entered name is {name}")
        query = f"SELECT firstname, lastname FROM user_data WHERE firstname = '{name}'"

        cursor = connect_to_db().cursor()
        cursor.execute(query)
        return cursor.fetchall()

    except sqlite3.OperationalError as error:
        print(error)


def non_vulnerable_code(name):

    try:
        print(f"The entered name is {name}")
        query = f"SELECT firstname, lastname FROM user_data WHERE firstname = ?"

        connection = connect_to_db()
        cursor = connection.cursor()
        cursor.execute(query, (name,))
        return cursor.fetchall()

    except sqlite3.OperationalError as error:
        print(error)

if __name__ == "__main__":
    create_table()
    insert_data()
    name = get_user_input()
    print("VULNERABLE CODE RESULT TO FIND Qowiyyu IN THE DATABASE")
    result = vulnerable_code(name)
    print_result(result)

    print("NON-VULNERABLE CODE RESULT TO FIND Qowiyyu IN THE DATABASE")
    result = non_vulnerable_code(name)
    print_result(result)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Results
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;When a valid non-attack intended input is submitted&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2nj5nlej6424t5rakkk4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2nj5nlej6424t5rakkk4.png" alt="No SQL injection case" width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It can be seen that without an attack input, both the code vulnerable and non-vulnerable to an SQL injection gave the expected output.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When an attack input is submitted&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqk5g5iwk7yvlor33e5va.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqk5g5iwk7yvlor33e5va.png" alt="SQL injection case" width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It can be seen that with an attack input submitted, the vulnerable code was tricked by the input to return all the users' info in the database while the non-vulnerable code did not return anything.&lt;/p&gt;

&lt;p&gt;Source code here: &lt;a href="https://github.com/graphitecommunity/sql-injection" rel="noopener noreferrer"&gt;Graphite Academy SQL Injection Lab&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  ORMs (Object-Relational Mapping)
&lt;/h2&gt;

&lt;p&gt;ORMs like SQLAlchemy, SQLModel, Django ORM also help in preventing SQL injection by providing an object-oriented interface which automatically generates the SQL query. &lt;/p&gt;

&lt;p&gt;Like and share this article to help others discover it. Don't forget to follow us so you're notified whenever we release new content.&lt;/p&gt;

&lt;p&gt;Thank you for your support!&lt;/p&gt;

</description>
      <category>sql</category>
      <category>security</category>
      <category>softwareengineering</category>
      <category>backend</category>
    </item>
  </channel>
</rss>
