How to avoid the sql injection in createNativeQuery? [duplicate] - sql

I'm working with JPA. How could my application be SQL injection safe if I'm using a native sql query (not entity query)? I need to build the native sql query with the data submitted by a user from a html form.
If I use parameters in the native sql I can avoid SQL injection attacks, but my problem is that I can't be sure how many data fields are being submitted by the user.

You should use positional parameters binding:
String queryString = "select * from EMP e where e.name = ?1";
Query query = em.createNativeQuery(queryString, Employee.class);
query.setParameter(1, "Mickey");
Please note that you should not use named parameters binding (:empName) in your query as JPA Spec says
Only positional parameter binding may be portably used for native queries.
This should secure you from SQL Injection attacks.

Related

Mulesoft not able to pass dynamic SQL queries based on environments

Hello for demonstration purposes I trimmed out my actual sql query.
I have a SQL query
SELECT *
FROM dbdev.training.courses
where dbdev is my DEV database table name. When I migrate to TEST env, I want my query to dynamically change to
SELECT *
FROM dbtest.training.courses
I tried using input parameters like {env: p('db_name')} and using in the query as
SELECT * FROM :env.training.courses
or
SELECT * FROM (:env).training.courses
but none of them worked. I don't want my SQL query in properties file.
Can you please suggest a way to write my SQL query dynamically based on environment?
The only alternative way is to deploy separate jars for different environments with different code.
You can set the value of the property to a variable and then use the variable with string interpolation.
Warning: creating dynamic SQL queries using any kind of string manipulation may expose your application to SQL injection security vulnerabilities.
Example:
#['SELECT * FROM $(vars.database default "dbtest").training.courses']
Actually, you can do a completely dynamic or partially dynamic query using the MuleSoft DB connector.
Please see this repo:
https://github.com/TheComputerClassroom/dynamicSQLGETandPATCH
Also, I'm about to post an update that allows joins.
At a high level, this is a "Query Builder" where the code that builds the query is written in DataWeave 2. I'm working on another version that allows joins between entities, too.
If you have questions, feel free to reply.
One way to do it is :
Create a variable before DB Connector:
getTableName - ${env}.training.courses
Write SQL Query :
Select * from $(getTableName);

FromSqlRaw injection EF Core 3.0

I am wondering how safe the fromSqlRaw method is. I am doing the following in my code, where the person id is a parameter from the method itself:
string sql = String.Format("SELECT * FROM [users].[user] WHERE Id LIKE {0}", id)
var list = this.context.Person.FromSqlRaw<Person>(sql).ToList();
Is this code safe to SQL injection? And is there other security vulnerabilities that I should know of when using this?
Use proper parametrization for your input.
After clarifications in comments, it seems that your parameter is user-input string, this is a wide door opened for injection attacks.
Usually, you can create a SqlCommand, and provide some SqlParameter in it.
In EFCore, FromSqlRaw and FromSqlInterpolated (in 3.0, replacement for FromSql in EFCore < 3.0) allow you to shorten this syntax, see the documentation.
string sql = "SELECT * FROM [users].[user] WHERE Id LIKE {0}"
var list = this.context.Person.FromSqlRaw<Person>(sql, "42")
Note that this looks very similar to what you did in the question... But the difference is clearly emphasized in the documentation:
Warning
Always use parameterization for raw SQL queries
When introducing any user-provided values into a raw SQL query, care
must be taken to avoid SQL injection attacks. In addition to
validating that such values don't contain invalid characters, always
use parameterization which sends the values separate from the SQL
text.
In particular, never pass a concatenated or interpolated string ($"")
with non-validated user-provided values into FromSqlRaw or
ExecuteSqlRaw. The FromSqlInterpolated and ExecuteSqlInterpolated
methods allow using string interpolation syntax in a way that protects
against SQL injection attacks.
Indeed, in your case, the string was first interpolated as a string (without any sanity-check), then executed as-is.
FromSqlRaw had no idea that the "Id" part was coming from a parameter.

Laravel query builder: is this command excused from SQL injections?

Some time ago I've read here on Stackoverflow an accepted answer which was claiming that select("sql query") is excused from SQL injection, while select(raw("sql query")) isn't. In my case I have the following code:
$request; // Illuminate\Http\Request
DB::connection('default')->select("
SELECT *
FROM `some_table`
WHERE `some_col` = '$request->some_val'
");
Is that command excused from SQL injection? If yes, I can't understand how does query builder knows how to prepare the statement? :thinking:
For not permit sql injection You must be use this code
DB::::connection('default')
->select('SELECT * FROM `some_table` WHERE `some_col` = ?', [$request->some_val]);
You should use:
DB::connection('default')->select("
SELECT *
FROM `some_table`
WHERE `some_col` = ?
", [$request->some_val]);
to avoid SQL injection.
You can read:
Parameter binding provides protection against SQL injection.
on documentation page.
If you execute SQL queries as you shown in your question that you might suffer from SQL injection.
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
You can refer to below links:
Laravel Eloquent: is SQL injection prevention done automatically?
https://laravel.com/docs/5.6/queries#introduction

Textbox Value for where Clause

SELECT verlog.bearerid, detail.snum
FROM verlog
INNER JOIN detail
ON verlog.txnid = detail.txnid
WHERE verlog.bearerid ='"+ TextBox1.Text +"'
is this the right way to obtain the value of a text box and use it in a where clause?
By constructing the statement in this way you open yourself up to SQL injection attacks in which users may be able to run additional sql against your database.
You can protect against this by using parameterised sql. Then pass both the query and the parameters when executing.
SELECT verlog.bearerid, detail.snum
FROM verlog
INNER JOIN detail
ON verlog.txnid = detail.txnid
WHERE verlog.bearerid = #bearerid
Further details can be read here: http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06
Alternatively you can use an ORM which will handle this for you.
I seggest not to write scripts as you mentioned; that would pave the way of injection. If not using any ORM technology such as Entity framework which in turn calls for its own security issues as well, always stick into parametric ado.net queries. Look at this link

JPA Query - sql injection in positional parameters jpa native query

As I read in a lot of articles, when I use JPA/Hibernate query it is good to set parameters in my queries so SQL injection is avoided. Like:
select user from User user where user.name = :name and user.surname = :surname
My problem is that in some cases I need to use native query when I create my query.
I will use my entity manager and createNativeQuery. But in this case the parameters will be positional. Like:
select * from users where user_name = ? and user_surname = ?
Then in my query I will use the method setParameter(1, "name") etc. So is this case "sql injection proof" like when in the parameterized query?
if you do not use string operations for building your query like
"SELECT foo FROM bar Where id="+myParameter+" more sql ..."
, then you will not have any vulnerabilities.
Currently (community correct me if I am wrong) no vulnerabilities exist within the latest PDO database abstraction layer.
However testing your queries for known and unknowns while sanitizing and filtering input will help eliminate the possibility of an injection in the event of a zero day exploit.
I currently use a combination of filtering input, charset expectations, stored procedures and strict requirements on their arguments prior to any and all dynamically created queries