Possible SQL Injection with redirect to webpage if injected query is correct - sql

Under the authorization of my friend, I am testing his website against potential vulnerabilities.
I was trying to find if I was able to inject a SQL query into a POST request parameter hi' or 1=1 --:
query=hi'%20or%201%3d1%20--
I found that the document prints out:
<div class="error">index job,query: syntax error, unexpected '-' near '-'</div>
while with ' or 0=0 -- I get:
<div class="error">index job,query: syntax error, unexpected '|' near ' | 0=0) --'</div>
does this mean that it's vulnerable to SQL Injection? If yes, how can I make it print server system data (like information, etc.)? By the way, if the string is correct it gets redirected to another webpage (I think that's why SQLMap tells me the parameter is not SQL-injectable).
EDIT: I can see the query works just if the URL gets redirected, but I won't see the query output. If the URL doesn't get redirected, I can see these SQL query errors. I'm trying to see how to get the output and do something more useful to attack the website, or even make it detectable from sqlmap.
The current command I'm using is sqlmap -r thework.txt -p query --dbs. thework.txt contains the full valid POST request.

SQL injection isn't only about malicious attacks that read data or change data on your site.
The majority of SQL injections are simply errors like the one you saw. They might not even be malicious. What if you have an SQL injection vulnerability that simply causes an error when someone wants to register their last name as "O'Reilly"? The user is well-intentioned, but your site breaks when they use their real name.
That's reason enough to detect and fix cases of SQL injection in your code.
You didn't post your code that builds the SQL query from this input, so what you have shown is only circumstantial evidence. But I do infer that you are copying a GET input into your SQL query without proper escaping or the preferred method, using a query parameter.

Wish I had 50 reps so I could put this in comments. But yes the site is most likely vulnerable. To be sure ask your friend to allow you to run an initial exploit.
sqlmap.py -u < Target Address> --dbs
If you successfully pull up the data base you have found the vulnerability or at least have confirmed there is a vulnerability.

Related

How to receive SQL syntax error using SQL injection?

I'm doing some webpentesting exercises and there is this one task saying that I need to make a new account with this name and this password by using SQL injection. On the web page there is a text input username and another text input 'password'. I can enter whatever characters I want inside the username text-input but inside the password text input I need to type a specific injection.
I know I need to inject insert query but the thing is I don't know the table name. In order to insert a new user I need to know the table name so I'm wondering how can I make the web showing me an error with tablename revealed.
The error showing should be like:
Unexpected end of command in statement [SELECT * FROM (tablename) WHERE...]
I tried to enter with just one character (maybe >1 chars are required) inside the password field to make the error show or even delete the parameter text input password. But it just won't show the SQL syntax error.
So the question is: How can I make use of the exploit to make the web page view the SQL syntax error with table name revealed?
And why doesn't injection work on username field but it does on password field?
The first thing is understand the difference between "application" errors (for example, "the user doesn't exist") and execution errors, in which the application fails itself, like the "Unexpected end of command" you mention. The first case is not usually a problem from the security point of view (unless the application is very badly programmed), the second one is what could allow hacking.
A well programmed web application should ideally only have application errors, but the more realistic approach is cope with unexpected execution errors in way that don't make it vulnerable. Also, application should process any user input in a way that don't cause an execution error.
It seems that they are teaching you the most flagrant case that allows SQL injection, apps than don't do any processing to user input (so it's very easy put text in an input field that cause an execution error), and that don't cope with execution errors (in this case, showing the internal execution message to the user).
A common mistake in web applications is constructing the SQL query with string concatenation, so the simplest way of make it fail is using the string delimiter (') in a field, causing the string value to end prematurely. In an sloppy web app it would cause an execution error that shows the full error message, usually including the table name.
From there you craft a SQL query in the input field that insert the user in the table, you could find examples online (note that you need at least basic knowledge on SQL and PHP (or ASP, Java, etc.), in order to do SQL injection, since you need to know how the database access works in order to make it fail).
Finally, SQL injection could work in any input field that is not properly processed, but it depends on how the application is programmed. I suppose that both fields would work but it will be easy do that with the password field because probably is the last one in the SQL query.

Sql Injection queries

I have a website which contains sql injection vulnerability but i can exploit it, just because of some filtration by the web server.
So i have a payload order by 4 to find the columns but i can't find. I don't know whats happening but when i use this payload it works
' order by 4--+ when this payload executes i get the column error.
So what happens with the second one? The main doubt is what is the work of the --+ and why is it necessary to put a single tick (') in second payload?
I think that the -- in sql means : comment what is forwarding.
You should use a ' to don't get sql syntaxe errors on your injection and to see the result.
If you use PHP, just take a look for The Documentation. Wish it could help you.
Good luck

php pdo how to update records in mysql database using pdo php [duplicate]

This is my PHP SQL statement and it's returning false while var dumping
$sql = $dbh->prepare('INSERT INTO users(full_name, e_mail, username, password) VALUES (:fullname, :email, :username, :password)');
$result = $sql->execute(array(
':fullname' => $_GET['fullname'],
':email' => $_GET['email'],
':username' => $_GET['username'],
':password' => $password_hash));
TL;DR
Always have set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION in your PDO connection code. It will let the database tell you what the actual problem is, be it with query, server, database or whatever. Also, make sure you can see PHP errors in general.
Always replace every PHP variable in the SQL query with a question mark, and execute the query using prepared statement. It will help to avoid syntax errors of all sorts.
Explanation
Sometimes your PDO code produces an error like Call to a member function execute() or similar. Or even without any error but the query doesn't work all the same. It means that your query failed to execute.
Every time a query fails, MySQL has an error message that explains the reason. Unfortunately, by default such errors are not transferred to PHP, and all you have is a silence or a cryptic error message mentioned above. Hence it is very important to configure PHP and PDO to report you MySQL errors. And once you get the error message, it will be a no-brainer to fix the issue.
In order to get the detailed information about the problem, either put the following line in your code right after connect
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
(where $dbh is the name of your PDO instance variable) or - better - add this parameter as a connection option. After that all database errors will be translated into PDO exceptions which, if left alone, would act just as regular PHP errors.
After getting the error message, you have to read and comprehend it. It sounds too obvious, but learners often overlook the meaning of the error message. Yet most of time it explains the problem pretty straightforward:
Say, if it says that a particular table doesn't exist, you have to check spelling, typos, letter case. Also you have to make sure that your PHP script connects to a correct database
Or, if it says there is an error in the SQL syntax, then you have to examine your SQL. And the problem spot is right before the query part cited in the error message.
You have to also trust the error message. If it says that number of tokens doesn't match the number of bound variables then it is so. Same goes for absent tables or columns. Given the choice, whether it's your own mistake or the error message is wrong, always stick to the former. Again it sounds condescending, but hundreds of questions on this very site prove this advice extremely useful.
Note that in order to see PDO errors, you have to be able to see PHP errors in general. To do so, you have to configure PHP depends on the site environment:
on a development server it is very handy to have errors right on the screen, for which displaying errors have to be turned on:
error_reporting(E_ALL);
ini_set('display_errors',1);
while on a live site, all errors have to be logged, but never shown to the client. For this, configure PHP this way:
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
Note that error_reporting should be set to E_ALL all the time.
Also note that despite the common delusion, no try-catch have to be used for the error reporting. PHP will report you PDO errors already, and in a way better form. An uncaught exception is very good for development, yet if you want to show a customized error page, still don't use try catch for this, but just set a custom error handler. In a nutshell, you don't have to treat PDO errors as something special but regard them as any other error in your code.
P.S.
Sometimes there is no error but no results either. Then it means, there is no data to match your criteria. So you have to admit this fact, even if you can swear the data and the criteria are all right. They are not. You have to check them again. I've short answer that would help you to pinpoint the matching issue, Having issue with matching rows in the database using PDO. Just follow this instruction, and the linked tutorial step by step and either have your problem solved or have an answerable question for Stack Overflow.
Some time ago I had the same problem of not seeing any error messages from mysql. After a research it turned out that the problem has got nothing to do with PHP itself, but with mysql server configuration. The default value of the variable lc_messages_dir pointed to non existing directory. After adding a line in mysqld.cnf, then restarted the mysql server, and finally I was able to see the error messages. For me the following was the right one:
lc_messages_dir=/usr/share/mysql
It is described in the mysql reference manual: https://dev.mysql.com/doc/refman/5.7/en/error-message-language.html

MySql NetScaler DataStream Content Switching failing to detect select

We are using the new DataStream feature introduced in NetScaler 9 (we're on v10) to do content switching (described here: http://support.citrix.com/proddocs/topic/netscaler/ns-dbproxy-wrapper-con.html). We have a read-only virtual server that balances across several read-only MySql slaves. We use our Content Switching to send all "Selects" over to the read-only server.
the policy is configured as such:
mysql.req.query.command.contains("select")
our users send multi-part queries to our database server. Most often they are simple, like:
use database;
select col1 from table1;
Sometimes they will put comments at the head of the query. for example:
-- this is my query
select col1 from table1;
What we've found is that if the query simply starts with a select, everything works swimmingly. However, in the cases where there is a use statement or comments preceding the query, the content swticher fails to detect that this is a select query and it bypasses our read-only virtual server.
I am about to tell all of our developers that they must fully alias every table in every query and avoid use statements (yes, this is a good thing anyway), and also that they cannot use comments in their sql (that's just silly).
Does anyone know how I can configure my NetScaler DataStream Content Switching to ignore comments and use statements?
The decision on where to send the query is done on the first line received after successful authentication... so ignoring the comment won't work.
You could setup a responder policy which sends back an error message saying "Please don't use SQL Comments in commands sent to the Load Balanced VIP". A bit draconian, but your devs would get the message fairly quick.. but there's no way to ignore the comment, but still base a decision on the select statement. However, I was under the impression that the select statement is up to the first semi colon... so in your example above, it should (in theory) still find the select statement. I'd need to test that to be certain of the behaviour however.
Also - the USE statement is critical. This is the DB on which all subsequent commands are issued.
It would be best practice to NOT use the USE statement, but instead, change the select statement to:
select col1 from database.table1;
Once the USE statement is seen, it prevents any subsequent commands being pipelined down the same connection... So if there are a lot of Use statements, you will not get to enjoy the connection multiplexing functionality that comes with DataStream.
We learned that Block Level comments are acceptable, but single line comments are not.
This is properly ignored:
/* my comment */
These comment styles are treated as part of the query:
-- my comment
# my comment
kind of ridiculous when having SET autocommit=0 is perfectly reasonable. What about in that situation.

cgi generic sql injection problems

I was scanning a site when the following vulnerability popped up: CGI Generic SQL Injection
nessus sais that An attacker may exploit this flaw to bypass authentication, read confidential data, modify the remote database, or even take control of the remote operating system.
So i continued reading and found out that the vulnerability sits in this piece of code:
Using the POST HTTP method, Nessus found that :
The following resources may be vulnerable to SQL injection :
The '_codeTextBox' parameter of the /LoginTeacherForm.aspx CGI :
/LoginTeacherForm.aspx [loginButton=Login&_VIEWSTATE=dDwtMTU2NDIxMDkwN
Ts7Pg%3d%3d&btnChangePassword=Wijzig%20Pincode&_pinCodeTextBox=&_codeTex
tBox='+convert(int,convert(varchar,0x7b5d))+']
-------- output --------
Exception Details: System.Data.SqlClient.SqlException: String or
binary data would be truncated.
The statement has been terminated.
But i'm wondering how an attacker can exploit this vulnerability, because when i paste that piece of code it just give me the error.
So my question is how would an attack be able to actually hack into the site and bypass login etc. (Educational purpose only of course)
It looks like a false positive caused by the Nessus request causing your page to insert too long a string into a field. Nessus has detected the error was a SQL server error and has said that it may be a SQL injection vulnerability.
To test yourself try the request with _codeTextBox= set to a single quote to see if you still get a SqlException. If so amend this to two single quotes and if the error then goes away you are probably vulnerable.
The error System.Data.SqlClient.SqlException indicates an error in your SQL query statement. This implies that value stored in the _codeTextBox parameter is not validated or otherwised sanitized before being put into the query.
This would have varying implications depending on the query and logic surrounding its return value. It is impossible to determine the worst case scenario without a thorough understanding of the web application. Suffice it to say, this issue should be fixed by the developer. Fortunately, it is usually easy to fix once identified.
In this case, it looks like the _codeTextBox parameter is being passed to the convert function. I doubt anyone could exploit this. But, this indicates insecure coding practices that probably appear in other areas that Nessus is not aware of. Read below for more info.
I see this most often when the programmer simply concatenates the values with the SQL query string:
Unsafe Example (java) (Source OWASP)
String query = "SELECT account_balance FROM user_data WHERE user_name = "
+ request.getParameter("customerName");
try {
Statement statement = connection.createStatement( … );
ResultSet results = statement.executeQuery( query );
}
Since the value simply gets appended to the end of the query, the user can change query to do something nefarious like login as any user or view all transactions. In the above example, the user could change the customer name parameter to something like '' or 1=1 or worse.
Expected query:
SELECT account_balance FROM user_data WHERE user_name = someuser
Bad query:
SELECT account_balance FROM user_data WHERE user_name = '' OR 1=1
OWASP recommends the following defensive measures. Your situation will dictate what is appropriate:
Primary Defenses:
Use of Prepared Statements (Parameterized Queries)
Use of Stored Procedures
Escaping all User Supplied Input
Additional Defenses:
Also Enforce: Least Privilege
Also Perform: White List Input Validation
You really need to check out OWASP's site and read more about SQL injection.