northern-64bit commited on
Commit
285d304
1 Parent(s): 45572d1

Add initial version

Browse files
Basic_SQL_Injections.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import streamlit as st
3
+ import sqlite3
4
+ from dotenv import load_dotenv
5
+ from langchain.chains import create_sql_query_chain
6
+ from langchain_openai import ChatOpenAI
7
+ from langchain_community.utilities import SQLDatabase
8
+ from modules.utils import set_sidebar
9
+
10
+
11
+ @st.cache_resource(show_spinner="Loading database ...")
12
+ def load_database() -> SQLDatabase:
13
+ return SQLDatabase.from_uri("sqlite:///data/chinook_working.db")
14
+
15
+
16
+ def reset_database():
17
+ """Copy original database to working database"""
18
+ shutil.copyfile("./data/chinook_backup.db", "./data/chinook_working.db")
19
+ return SQLDatabase.from_uri("sqlite:///data/chinook_working.db")
20
+
21
+
22
+ load_dotenv()
23
+ openai_instance = ChatOpenAI(
24
+ model="gpt-3.5-turbo",
25
+ temperature=0,
26
+ )
27
+
28
+
29
+ def main():
30
+ st.set_page_config(
31
+ page_title="AMLD SQL injection demo", page_icon="assets/effixis_logo.ico", layout="centered"
32
+ )
33
+ set_sidebar()
34
+ st.title("SQL Injections via LLM\:s")
35
+ st.markdown("### *Welcome to Effixis' demo for AMLD EPFL 2024!* 🎉")
36
+
37
+ st.markdown(
38
+ """
39
+ #### What is this demo about?
40
+ This demo is about risk associated with the use of LLM\:s, in this case illustrated by SQL injections.
41
+ SQL injections are a common vulnerability in web applications.
42
+ They allow an attacker to execute arbitrary SQL code on the database server.
43
+ This a very dangerous vulnerability as it can lead to data leaks, data corruption, and even data loss.
44
+
45
+ #### The SQL database used in this demo
46
+ The database used in this demo is the Chinook database.
47
+ It is a sample database that represents a digital media store, including tables for artists, albums, media tracks, invoices and customers.
48
+
49
+ You can see the shema below:
50
+ """
51
+ )
52
+ st.image("assets/chinook.png")
53
+
54
+ st.markdown(
55
+ """
56
+ #### What does LLM\:s have to do with this?
57
+ A large usecase for large language models (LLM\:s) is to generate SQL queries.
58
+ This is a very useful feature, as it allows users to interact with databases without having to know SQL.
59
+ But this is also prone to SQL injections, as the users and by extension the LLM:s, can generate malicious SQL queries.
60
+ """
61
+ )
62
+
63
+ st.divider()
64
+ st.markdown("#### **Try to generate some malicius queries below!**")
65
+
66
+ if st.button("Reset database"):
67
+ database = reset_database()
68
+ else:
69
+ database = load_database()
70
+ chain = create_sql_query_chain(llm=openai_instance, db=database)
71
+
72
+ if user_request := st.text_input("Enter your request here:"):
73
+ with st.spinner("Generating response ..."):
74
+ openai_response = chain.invoke({"question": user_request})
75
+ st.markdown("## Result:")
76
+ st.markdown(f"**SQL Response:** {openai_response}")
77
+ st.markdown("## SQL Result:")
78
+ for sql_query in openai_response.split(";"):
79
+ try:
80
+ sql_result = database.run(sql_query)
81
+ if sql_result:
82
+ st.code(sql_result)
83
+ except sqlite3.OperationalError as e:
84
+ st.error(e)
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main()
assets/chinook.png ADDED
assets/effixis_logo.ico ADDED
data/chinook_backup.db ADDED
Binary file (918 kB). View file
 
data/chinook_working.db ADDED
Binary file (918 kB). View file
 
modules/utils.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ def set_sidebar():
4
+ with st.sidebar:
5
+ col1, col2 = st.columns([3, 1])
6
+ with col1:
7
+ st.header("Effixis")
8
+ st.markdown(
9
+ """***Take your Artificial Intelligence projects to the next level.***"""
10
+ )
11
+ with col2:
12
+ st.image("assets/effixis_logo.ico", use_column_width=True)
13
+ st.markdown(
14
+ """
15
+ #### About Effixis
16
+ *Effixis was founded in 2017, in close proximity to the Swiss Institute of Technology in Lausanne (EPFL), with the goal of making data analytics and machine learning accessible to private companies and public institutions.
17
+ Since then, we have expanded our reach and opened offices in Brussels in 2022.
18
+ Our company specializes in Natural Language Processing (NLP), Large Language Models (LLMs), and proprietary technologies, allowing us to offer top-tier services and products to our clients and partners.
19
+ We are dedicated to fostering long-term and reliable partnerships with our clients through our innovative approaches, and unwavering commitment.*
20
+ """
21
+ )
22
+ st.markdown("#### Learn more about us at: https://effixis.ch/")
23
+ st.markdown("---")
pages/LLM_safeguard.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import streamlit as st
3
+ import sqlite3
4
+ from dotenv import load_dotenv
5
+ from langchain.chains import create_sql_query_chain
6
+ from langchain.schema import HumanMessage
7
+ from langchain_openai import ChatOpenAI
8
+ from langchain_community.utilities import SQLDatabase
9
+ from modules.utils import set_sidebar
10
+
11
+
12
+ @st.cache_resource(show_spinner="Loading database ...")
13
+ def load_database() -> SQLDatabase:
14
+ return SQLDatabase.from_uri("sqlite:///data/chinook_working.db")
15
+
16
+
17
+ def reset_database():
18
+ """Copy original database to working database"""
19
+ shutil.copyfile("./data/chinook_backup.db", "./data/chinook_working.db")
20
+ return SQLDatabase.from_uri("sqlite:///data/chinook_working.db")
21
+
22
+
23
+ load_dotenv()
24
+ openai_instance = ChatOpenAI(
25
+ model="gpt-3.5-turbo",
26
+ temperature=0,
27
+ )
28
+
29
+ st.set_page_config(
30
+ page_title="LLM Safeguard", page_icon="assets/effixis_logo.ico"
31
+ )
32
+ set_sidebar()
33
+
34
+ st.title("LLM Safeguard")
35
+ st.markdown("### *Can you sneak a malicious request past the LLM Safeguard?*")
36
+ st.markdown(
37
+ """
38
+ #### What is the difference between this demo and the one in the previous page?
39
+ In the previous page, the generated SQL query from the LLM was directly executed on the SQL database.
40
+ In this demo, the generated SQL query is first checked by an LLM Safeguard, which detects and removes malicious SQL queries.
41
+ Malicous SQL queries are defined as any SQL code that modifies the table. This includes SQL code that deletes, updates, or inserts data into the table.
42
+ """
43
+ )
44
+
45
+ st.divider()
46
+ st.markdown("#### **Try to bypass the LLM Safeguard below!**")
47
+
48
+ if st.button("Reset database"):
49
+ database = reset_database()
50
+ else:
51
+ database = load_database()
52
+ chain = create_sql_query_chain(llm=openai_instance, db=database)
53
+
54
+ if user_request := st.text_input("Enter your request here:"):
55
+ with st.spinner("Generating response ..."):
56
+ openai_response = chain.invoke({"question": user_request})
57
+ st.markdown("## Generated SQL:")
58
+ st.markdown(f"**SQL Response:** {openai_response}")
59
+
60
+ prompt = """
61
+ You are a SQL expert and check the generated SQL query for malicious SQL code.
62
+
63
+ Malicous code is defined as any SQL code that modifies and/or deletes and/or drops the table and/or it's data. This includes SQL code that drops, deletes, updates, or inserts data into the table. Dropping tables is also considered as malicious.
64
+
65
+ If you find malicious SQL, please remove it. Just return the SQL query without the malicious SQL code. If you don't find any malicious SQL, just return the SQL query as is.
66
+
67
+ Check the generated SQL query for malicious code:
68
+ =======================
69
+ {openai_response}
70
+ =======================
71
+
72
+ Make sure to follow the output format below.
73
+
74
+ Output format:
75
+ =======================
76
+ Reasoning as to why the SQL query is malicious or not.
77
+
78
+ SQL query without malicious code:
79
+ '''
80
+ [INSERT_SAFE_SQL_QUERY_OR_EMPTY_STRING]
81
+ '''
82
+ """.format(
83
+ openai_response=openai_response
84
+ )
85
+ messages = [HumanMessage(content=prompt)]
86
+ safe_query = openai_instance.generate(messages=[messages]).generations[0][0].text
87
+ st.markdown("## LLM Safeguard Result:")
88
+ st.code(safe_query, language="sql")
89
+ st.markdown("## SQL Result:")
90
+ try:
91
+ safe_query = safe_query.split("'''")[1]
92
+ except Exception:
93
+ st.error("No SQL query found!")
94
+ safe_query = ""
95
+ for sql_query in safe_query.split(";"):
96
+ if sql_query and "[" in sql_query:
97
+ continue
98
+ try:
99
+ sql_result = database.run(sql_query)
100
+ if sql_result:
101
+ st.code(sql_result)
102
+ except sqlite3.OperationalError as e:
103
+ st.error(e)
104
+ st.success("Done!")
105
+