to fix URL content based SQL injection - sql

I was trying to fix SQL injection for my Application. SQL query I am using to get the details is
"SELECT accountNumber, balance FROM accounts WHERE reg_id = "
+ request.getParameter("reg_id");
I know this query is vulnerable and that's why I was trying to use bind parameters to fix this but the issue is reg_id is Alphanumeric data along with "-" (hyphen as special symbol e.g.- 1abh34-dfg465-aw234)and I can't use statement.setInt() and statement.setString() method to validate reg_id.
My Question is, is there any method I can use to validate Alphanumeric data?
My java code is
String accountBalanceQuery =
"SELECT accountNumber, balance FROM accounts WHERE reg_id = "
+ request.getParameter("reg_id");
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(accountBalanceQuery);
while (rs.next()) {
page.addTableRow(rs.getInt("accountNumber"), rs.getFloat("balance"));
}
} catch (SQLException e) { ... }
Or is there any other way I can fix this vulnerability without bind parameters. Any lead on this will be much appreciated.

Related

SqlCommmand parameters not adding to UPDATE statement (C#, MVC)

If you look at the stuff commented out, I can easily get this to work by adding user input directly in to the query, but when I try to parameterize it, none of the values are being added to the parameters...
This code is throwing an error
Must define table variable #formTable
but the issue is none of the values are adding, not just the table variable (verified by replacing table name variable with static text).
I have many insert statements in this project structured exactly like this one which work perfectly. What am I doing wrong here?
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
//string query = "UPDATE " + s.formTable + " SET " + s.column + " = '" + s.cellValue + "' WHERE MasterID = '" + s.id + "'";
string query = "UPDATE #formTable SET #column = #cellValue WHERE MasterID = #id;";
using (SqlCommand cmd = new SqlCommand(query))
{
//SqlParameter param = new SqlParameter("#formTable", s.formTable);
//cmd.Parameters.Add(param);
cmd.Parameters.AddWithValue("#formTable", s.formTable);
cmd.Parameters.AddWithValue("#column", s.column);
cmd.Parameters.AddWithValue("#cellValue", s.cellValue.ToString());
cmd.Parameters.AddWithValue("#id", s.id.ToString());
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Parameters are for values, not object identifiers (tables, columns, etc.), so the only valid parameters you have are #cellValue and #id.
If you want to dynamically set table/column names based on user input, you're likely looking at string concatenation. However, that doesn't necessarily mean SQL injection. All you need to do is validate the user input against a set of known values and use the known value in the concatenation.
For example, suppose you have a List<string> with all of your table names. It can be hard-coded if your tables are never going to change, or you can make it more dynamic by querying some system/schema tables in the database to populate it.
When a user inputs a value for a table name, check if it's in the list. If it is, use that matching value from the list. If it isn't, handle the error condition (such as showing a message to the user). So, even though you're using string concatenation, no actual user input is ever entered into the string. You're just concatenating known good values which is no different than the string literals you have now.

Delphi 10 - SQL statement Syntax error Update

I have no idea whats wrong with my Code it keeps giving my an Synxtax error in UPDATE statement here is the code :
adoQueryUsers.SQL.Clear;
adoQueryUsers.SQL.Add('Update Users SET Password = "' +
EdtPassword.Text + '" where Username = "' + sUsername + '" ');
adoQueryUsers.Active := true;
adoQueryUsers.ExecSQL;
I did try using adoQueryUsers.SQL.Text : = but it gives me the exact same problem.
Remove your 'adoQueryUsers.Active := true;'. This is an update statement and don't return a recordset. Only your ExecSQL is needed.
Also, I would use parameters instead of parsing the password and user directly into the query or you're exposed to SQL injection
You have several issues in your code.
Let's start with the inappropriate call to
adoQueryUsers.Active := true;
You only use TADOQuery.Active or TADOQuery.Open on a SQL statement that returns a rowset. Your statement does not do so, so remove that statement. The TADOQuery.ExecSQL is the only one that is relevant here.
Next, stop trying to concatenate SQL, and use parameters instead. It's no more code and it properly handles things like quoting values, formatting dates, etc. It also prevents SQL injection issues for you.
adoQueryUsers.SQL.Clear;
adoQueryUsers.SQL.Add('Update Users SET Password = :Password')
adoQueryUsers.SQL.Add('Where UserName = :UserName');
adoQueryUsers.Parameters.ParamByName('Password').Value := EdtPassword.Text;
adoQueryUsers.Parameters.ParamByName('UserName').Value := sUserName;
adoQueryUsers.ExecSQL;

IF-ELSE Alternative for Multiple SQL criteria for use in BIRT

I want to create a report by using BIRT. I have 5 SQL criterias as the parameter for the report. Usually when I have 3 criterias, I am using nested if-else for the WHERE statement with javascript.
Since right now I have more criteria it becomes more difficult to write the code and also check the possibilities, especially for debug purposes.
For example the criteria for table employee, having these 5 criterias : age, city, department, title and education. All criteria will be dynamic, you can leave it blank to show all contents.
Do anyone know the alternative of this method?
There is a magical way to handle this without any script, which makes reports much easier to maintain! We can use this kind of SQL query:
SELECT *
FROM mytable
WHERE (?='' OR city=? )
AND (?=-1 OR age>? )
AND (?='' OR department=? )
AND (?='' OR title=? )
So each criteria has two dataset parameters, with a "OR" clause allowing to ignore a criteria when the parameter gets a specific value, an empty value or a null value as you like. All those "OR" clauses are evaluated with a constant value, therefore performances of queries can't be affected.
In this example we should have 4 report parameters, 8 dataset parameters (each report parameter is bound to 2 dataset parameters) and 0 script. See a live example of a report using this approach here.
If there are many more criteria i would recommend to use a stored procedure, hence we can do the same with just one dataset parameter per criteria.
Integer parameter handling
If we need to handle a "all" value for an integer column such age: we can declare report parameter "age" as a String type and dataset parameters "age" as an integer. Then, in parameters tab of the dataset use a value expression instead of a "linked to report parameters". For example if we like a robust input which handles both "all" "null" and empty values here is the expression to enter:
(params["age"].value=="all" || params["age"].value=="" || params["age"].value==null)?-1:params["age"].value
The sample report can be downloaded here (v 4.3.1)
Depending on the report requirements and audiance you may find this helpful.
Use text box paramaters and make the defualt value % (which is a wild card)
SELECT *
FROM mytable
WHERE city like ?
AND age like ?
AND department like ?
AND title like ?
This also allows your users to search for partial names. if the value in the city text box is %ville% it would return all the cities with "ville" anyplace in the city name.
If report parameters to be included in SQL-WHERE clause would be named according to some naming convention, for instance query_employee_[table column name], you could write Java-Script code in a generic way, so that you will not have to change it when new reporters being added.
for each param in params {
if param.name starts with query_employee_ {
where_clause += " and " + param.name.substring(after query_employee) + " == '" + param.value + "'";
}
}
You will have to check type of a parameter to make a decision whether you have to quote the parameter value.
The event handler could look as follows (implemented in Java, but it should be possible to port it to JavaScript, if you really need it to be in JavaScript):
public class WhereConditionEventHandler extends DataSetEventAdapter {
#Override
public void beforeOpen(IDataSetInstance dataSet,
IReportContext reportContext) throws ScriptException {
super.beforeOpen(dataSet, reportContext);
String whereClause = " where 1 = 1 ";
SlotHandle prms = reportContext.getDesignHandle().getParameters();
for (int i = 0; i < prms.getCount(); i++) {
if (prms.get(i) instanceof ScalarParameterHandle) {
ScalarParameterHandle prm = (ScalarParameterHandle) prms.get(i);
int n = prm.getName().indexOf("sql_customer_");
if (n > -1) {
String prmValue = "" + reportContext.getParameterValue(prm.getName());
if (DesignChoiceConstants.PARAM_TYPE_STRING.equals(prm.getDataType())) {
prmValue = "'" + prmValue + "'";
}
whereClause += " and " + prm.getName().substring("sql_customer_".length()) + " = " + prmValue;
}
}
}
System.out.println("sql: " + whereClause);
dataSet.setQueryText(dataSet.getQueryText() + whereClause);
}
}
By the way, you can pass in parameters that are not registered as report parameters in the BIRT report design. BIRT will nevertheless put them into "params" array.

JavaFX SQL query Data Type Mismatch (String)

I'm querying an MS Access database and getting the following error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
The relevant code:
private SimpleStringProperty getProduct(String bc) {
Connection conn;
String dbDriver;
Statement st;
ResultSet rs;
SimpleStringProperty prod = new SimpleStringProperty();
System.out.println("BC sent to db is: " + bc.toString());
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbDriver = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};"
+ "DBQ=Inventario.mdb;";
conn = DriverManager.getConnection(dbDriver, "", "");
st = conn.createStatement();
String getProduct = "SELECT * FROM Articulos "
+ "WHERE BarCode = " + bc; // .toString();
Where bc is a parameter obtained from a TextField box as a string, passed to this method as a string and the BarCode field in MS Access is of type Text.
As an aside, I am obviously working with a bar code, which is a number, but some of my bar codes have leading 0s, which is why I have it as text. Is there a way to work with bar codes of varying lengths and varying amounts of significant leading zeros as anything other than text/string? As you can see in my code, I even tried explicitly sending bc.toString() from JavaFX to MS Access, but I keep getting the data type mismatch error.
Final note: at various points I have placed System.out.println() to see what data is being passed, and at all points it appears correct. I have even taken out the criteria clause and just printed my result set, and all the proper data is coming back from Access.
I suppose that your querystate ment is wrong...
You could try to sourround your bc with '
String getProduct = "SELECT * FROM Articulos "
+ "WHERE BarCode = '" + bc+"'";
Try this tutorial http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
If you have excessive use of Databases i also would recommend you JPA.

Keyword search to include Uniqueidentifier field

I'm wanting to let a user search rows in a database by specifying a keyword to look for. There are a few fields I would like to look in for this keyword, one of which is a uniqueidentifier. The problem is, if the keyword is not a GUID, I get the following error message:
Conversion failed when converting from a character string to uniqueidentifier
The SQL I'm using to run the search looks something like this:
// do not use
string sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
WARNING: this is just example code - DO NOT write sql commands like this as it creates a security risk
How do I write my SQL select statement such that it will not fail when keyword is not a GUID?
string sql;
Guid id;
if (Guid.TryParse(keyword, out id))
{
sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
}
else
{
sql = //search by other way
}
Does this work for you?
string sql = #"SELECT *
FROM [MyTable]
WHERE convert(varchar,[MyTable].[TableID]) = '" + keyword + "'";
I know this doesn't really help you today, but may help future readers. In SQL Server 2012 you will be able to use TRY_CONVERT:
string sql = #"SELECT *
FROM dbo.[MyTable]
WHERE [TableID] = TRY_CONVERT(UNIQUEIDENTIFIER, '" + keyword + "');";
But what you really should be doing is passing the parameter as a strongly typed GUID, and handling the error (using try/catch) in the client program when someone enters something that isn't a GUID.