1 of 26

Web Applications – 3

CSE 598 Advanced Security of the Web

Fish Wang

Fall 2026

2 of 26

Web Applications and Databases

  • Pros
    • ACID compliance
      • Atomicity, consistency, isolation and durability
    • Concurrency
    • Separation of concerns
      • Can run database on another server
      • Can have multiple web application processes connecting to the same database
  • Cons
    • More complicated to build and deploy
    • Adding another language to web technology (SQL)

2

3 of 26

LAMP Stack

  • Classic web application model
    • Linux
    • Apache (Nginx)
    • MySQL
    • PHP (Python)
  • LAMP is pretty obsolete, but it’s still a ice way to think of web applications, as each component can be mixed and swapped
    • Underlying OS
    • Web server
    • Database
    • Web application language/framework

​

3

4 of 26

MySQL

  • Currently most used open-source relational database
  • First release on May 23rd 1995
    • Same day that Sun released first version of Java
  • Sun eventually purchased MySQL (the company) for $1 billion in January 2008
  • Then … Oracle acquired it in 2010 (~$5.6 billion)
    • MariaDB is an open-source fork of MySQL at the time of acquisition

4

5 of 26

Structured Query Language

  • Special purpose language to interact with a relational database
  • Multiple commands
    • SELECT
    • UPDATE
    • INSERT
  • Some slight differences between SQL implementations

5

6 of 26

SQL Examples

  • SELECT * FROM Users WHERE userName = 'fish';
  • SELECT * FROM Book WHERE price > 100.00 ORDER BY title;
  • SELECT isbn, title, price FROM Book WHERE price < (SELECT AVG(price) FROM Book) ORDER BY title;
  • INSERT INTO example (field1, field2, field3) VALUES ('test', 'N', NULL);
  • UPDATE example SET field1 = 'updated value' WHERE field2 = 'N';
  • (SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

6

7 of 26

Python Flask and MySQL

  • Install the extension��pip install Flask Flask-SQLAlchemy pymysql

​

  • Configuration��app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:your_password@localhost/my_flask_db'�

7

8 of 26

Python Flask and MySQL

# Define a Database Model

class User(db.Model):

id = db.Column(db.Integer, primary_key=True)

username = db.Column(db.String(80), unique=True, nullable=False)

email = db.Column(db.String(120), unique=True, nullable=False)

​

​

# Initialize Database (Run once to create tables)

with app.app_context():

db.create_all()

8

9 of 26

Python Flask and MySQL

# Fetch Data

@app.route('/users', methods=['GET’])

def get_users():

users = User.query.all()

return jsonify([user.to_dict() for user in users])

​

# Add Data

@app.route('/users', methods=['POST’])

def add_user():

data = request.json

new_user = User(username=data['username'], email=data['email’])

db.session.add(new_user)

db.session.commit()

return jsonify({"message": "User created successfully!"}), 201

9

10 of 26

Raw SQL queries

  • ORM is amazing and secure, but it’s not always enough
    • Developers fall back to using raw SQL queries

​

@app.route('/users/<status>', methods=['GET’])

def get_users(status):

query = text("SELECT id, username, email FROM users WHERE status = " + status)

result = db.session.execute(query)

users = [{"id": row.id, "username": row.username, "email": row.email} for row in result]

return jsonify(users)

10

11 of 26

The Form

<form action="/login" method="post">

<table>

<tr><td>Username:</td>

<td><input type="text" name="username"></td></tr>

<tr><td>Password:</td>

<td><input type=password name="password"></td></tr>

</table>

<input type="submit" value="Submit">

<input type="reset" value="Reset">

</form>

11

12 of 26

The Login Script

@app.route("/login", methods=["POST"])

def login():

data = request.form

username = data.get("username")

password = data.get("password")

​

query = text(f"SELECT * FROM user WHERE username = \"{username}\" AND password = \"{password}\"")

result = db.session.execute(query).fetchone()

​

if result:

return "Login successful!", 200

else:

return "Invalid credentials.", 401

12

13 of 26

The Database

13

id

username

password

0

mok

e80b5017098950fc58aad83c8c14978e

1

user

ee11cbb19052e40b07aac0ca060c23ee

2

admin

bed128365216c019988915ed3add75fb

3

fish

cb2c1945ba526b12b7775730943eef76

14 of 26

The [' or 1=1 -- ] Technique

  • Given the SQL query string:� select * from user \� where username = "name" and \� password = "password";
  • By entering�' or 1=1 -- �as the username (and any password) results in the string:�select * from user where username="" or 1=1 -- " and password= ""
  • Parsed by the MySQL server as
    • select * from user where username="" or 1=1 -- " and password= ""
  • The conditional statement username = "" or 1=1 is true whether or not username is equal to ""
  • The "-- " makes sure that the rest of the SQL statement is interpreted as a comment and therefore password = "" is not evaluated
  • MySQL requires a SPACE after --!

14

15 of 26

Different types of SQL queries

  • SQL injection can modify any type of query such as
    • SELECT statements
      • SELECT * FROM accounts WHERE user="{u}" AND pass="{p}"
    • INSERT statements
      • INSERT INTO accounts (user, pass) VALUES("{u}", "{p}")
        • Note that in this case one must figure out how many values to insert
    • UPDATE statements
      • UPDATE accounts SET pass="{np}" WHERE user= "{u}" AND pass="{p}"
    • DELETE statements
      • DELETE * FROM accounts WHERE user="{u}"

15

16 of 26

Inject Different Queries

  • What is the SQL query separator?
    • ;
  • If the SQL server allows it, you can use ; to inject multiple, arbitrary, queries
    • select * from user where username=''; insert into user ('user', 'password') values ('fish', 'test'); -- ' and password= ''

​

16

17 of 26

Identifying SQL Injection

  • A SQL injection vulnerability can be identified in different ways
    • Negative approach: special-meaning characters in the query will cause an error (for example: user=" ’ ")
    • Positive approach: provide an expression that would NOT cause an error (for example: “17+5” instead of “22”, or a string concatenation, �such as “‘ ’Foo” instead of “Foo”

17

18 of 26

The UNION Operator

  • The UNION operator is used to merge the results of two separate queries
    • SELECT REPEAT('a', 1) UNION SELECT REPEAT('b', 10);
      • 'a'
      • 'bbbbbbbbbb'
  • In a SQL injection attack this can be exploited to extract additional information from the database
  • Original query:
    • SELECT id, name, price FROM products WHERE brand='{b}'
  • Modified query passing b="foo' UNION…":
    • SELECT id, name, price FROM products WHERE brand='foo' UNION SELECT user, pass, NULL FROM accounts -- '
  • For this attack to work, the attacker must know
    • The structure of the query (number of parameters and types must be compatible: NULL can be used if the type is not known)
    • The name of the table and columns

18

19 of 26

Determining Number and Type of Query Parameters

  • The number of columns in a query can be determined using progressively longer NULL columns until the correct query is returned
    • UNION SELECT NULL
    • UNION SELECT NULL, NULL
    • UNION SELECT NULL, NULL, NULL
  • The type of columns can be be determined using a similar technique
    • For example, to determine the column that has a string type one would execute:
      • UNION SELECT 'foo', NULL, NULL
      • UNION SELECT NULL, 'foo', NULL
      • UNION SELECT NULL, NULL, 'foo'

19

20 of 26

Determining Table and Column Names

  • To determine table and column names one has to rely on techniques that are database-specific
    • MSSQL
      • By using the sysobjects table one can extract information about the tables in the database
      • By using the syscolumns table one can extract the names of the columns associated with a table
    • MySQL
      • By using the information_schema.tables table one can extract information about the table names
      • By using the information_schema.columns table one can extract the names of the columns associated with a table

20

21 of 26

Blind SQL Injection

  • A typical countermeasure is to prohibit the display of error messages. But, is this enough?
    • No, a web application may still be vulnerable to blind SQL injection
  • Example: a news site
    • Press releases are accessed with pressRelease.jsp?id=5
    • A SQL query is created and sent to the database:
      • select title, description FROM pressReleases where id=5;
    • All error messages are filtered by the application

21

22 of 26

Blind SQL Injection

  • How can we inject statements into the application and exploit it?
    • We do not receive feedback from the application so we can use a trial-and-error approach
    • We try to inject pressRelease?id=5 AND 1=1
    • The SQL query is created and sent to the database:
      • select title, description FROM pressReleases where id=5 AND 1=1;
    • If there is a SQL injection vulnerability, the same press release should be returned
    • If input is validated, id=5 AND 1=1 should be treated as the value

22

23 of 26

Blind SQL Injection

  • When testing for vulnerability, we know 1=1 is always true
    • However, when we inject other statements, we do not have any information
    • What we know: If the same record is returned, the statement must have been true
    • For example, we can ask server if the current user is “h4x0r”:
      • pressRelease?id=5 AND user_name()='h4x0r'
  • By combining subqueries and functions, we can ask more complex questions (e.g., extract the name of a database table character by character)
    • pressRelease?id=5 AND SUBSTRING(user_name(), 1, 1) < '?'

​

23

24 of 26

Second Order SQL Injection

  • SQL code is injected into an application, but the SQL statement is invoked at a later point in time
    • e.g., Guestbook, statistics page, etc.
  • Even if application escapes single quotes, second order SQL injection might be possible
    • Attacker sets user name to: john'--, application safely escapes value to john\'-- on insertion into the database
    • At a later point, attacker changes password :

update users set password= … where username ='john'--'

24

25 of 26

How to defend?

  • Parameterized SQL queries!
    • Statements are compiled into SQL statements before user input is added
  • Developers must never allow client-supplied data to modify SQL statements
  • Stored procedures
    • Isolate applications from SQL
    • All SQL statements required by the application are stored procedures on the database server

25

26 of 26

26