GreySec Forums

Full Version: Second Order SQL Injection Attacks
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i was learning second order sql injection attacks and found this article amazing so i am sharing it here.

credit goes to : bert wagner

 SQL injection attacks that delay execution until a secondary query are known as “second order”.
This means a malicious user can inject a query fragment into a query (that’s not necessarily vulnerable to injection), and then have that injected SQL execute in a second query that is vulnerable to SQL injection.

Let’s look at an example.

Doggo Pics
Imagine a website where dog owners can share pictures of their best friends:

[Image: 2018-03-18_07-05-34-768x603.png]

Now imagine that users of Doggo Pics can set a preference for what order they view pictures when they visit the website:

[Image: 2018-03-18_07-07-41.png]

When a user saves their sorting preference, the sort column and order get saved to a preferences table in the database:

[Image: 2018-03-18_07-13-46-1.png]

The next time the user goes to view the page, the doggo pictures will be sorted based on their saved preferences.  This works because the query pulling the pics/descriptions is dynamically sorting the data based on the user’s preference:

[Image: 2018-03-18_07-22-05.png]

[Image: 2018-03-18_07-19-53-768x603.png]

The above flow is how the website is supposed to function.  So how does a malicious user inject SQL code into these queries if the only query they directly save input into is the UpdateSortOrder procedure?

The Attack

So the developer of Doggo Pics was too busy enjoying pictures of doggos to implement any type of input validation on sort order preferences.  This means a hacker can do something like inject a SQL statement onto the end of the sort order dropdown:

[Image: injection-attack-1.gif]

When our dbo.UpdateSortOrder procedure executes on the backend, it looks like this:

[Image: 2018-03-18_07-45-26-1-1024x41.png]

See where this is going?  Now when our stored procedure that dynamically sorts the picture data executes, the hacker’s INSERT statement is going to execute as well:

[Image: 2018-03-18_07-46-33-1024x80.png]

What happens next is simple: The first time our malicious user goes to view the Doggo Pics, they receive the pictures in their preferred sort order. Additionally an INSERT INTO statement executes back on the server.

The second time the user views the Doggo Pics page, the values from that previously ran INSERT INTO statement are now visible on the screen:

[Image: injection-attack-passwords-2.gif]

So even though the first query the user encounters (saving sort order preferences) is entirely SQL injection free, our second order SQL injection attack occurs when our second SQL query dynamically executes the injected code that was stored in our user preferences table in the database.
Must have missed this thread, but thanks for sharing!