Does CodeIgniter Query Builder protect against sql injection even in more complexed queries? - codeigniter-3

I know that using CodeIgniter's Query Builder should protect against SQL injection. The Manual says that it "allows for safer queries, since the values are escaped automatically by the system." But I'm not sure if by "values" they mean anything that goes through the Query Builder, or only values that are passed in simple stucture like : $this->db->where('name', $name);
For instance, if I use:
$this->db->select('student_id, concat(fname, " ",lname) as student_name');
$this->db->from('student');
$this->db->join('class_has_teacher',"student.class_id=class_has_teacher.class_id AND teacher_id=$teacher_id");
$query = $this->db->get();
Would the $teacher_id in the JOIN condition also be escaped?
(In case it matters, I'm using CodeIgniter 3.1.9)

Yes, $teacher_id would be escaped.

Related

Input string was not in correct formate while inserting data to postgresql through entityframework in .net core using dynamic query

I am getting error while inserting data to pgsql with .net core entity framework
error is Input string was not in correct format
this is my query executing
INSERT INTO public."MedQuantityVerification"("Id","MedId","ActivityBy","ActivityOn","Quantity","ActivityType","SupposedOn","Note") Values(7773866,248953,8887,'7/14/2018 10:43:43 PM','42.5 qty',5,NULL,'I counted forty two {point} five.')
anyhow when I run that query directly to postgresql browser it works fine
looks like issue on c# side it is but not know what?
also issue is with {point}
this is how I executing the dynamic query
db.Database.ExecuteSqlRaw(query);
You have to escape the curly brackets:
{point} should be {{point}}
ExecuteSqlRaw utilizes curly braces to parameterize the raw query so if your query naturally includes them like OP's does the function is going to try and parse them. Doubling up the braces like in Koen Schepens' answer acts as an escape sequence and tells the function not to parse it as a parameter.
The documentation for the function uses the following example as to the purpose of why it does what it does:
var userSuppliedSearchTerm = ".NET";
context.Database.ExecuteSqlRaw("UPDATE Blogs SET Rank = 50 WHERE Name = {0}", userSuppliedSearchTerm);
Note that you'll want to use this to your advantage any time you're accepting user-input and passing it to ExecuteSqlRaw. If the curly brace is in a parameter instead of the main string it doesn't need to be escaped.

EF Core raw query with Like clause

I want to create queries using EF FromSqlInterpolated or FromSqlRaw that allows me to use Like clauses, but I don't know what is the right way to do it without opening the application to SqlInjection attacks.
One first approach has took me to the following code
var results = _context.Categories.FromSqlInterpolated(
$"Select * from Category where name like {"%" + partialName + "%"}");
First test worked fine, it returns results when providing expected strings, and returns nothing when i provide something like ';select * from Category Where name='Notes'--%';
Still I don't know much about SqlInjection, at least not enough to feel safe with the query shown before.
Does someone know if the query is safe, or if there is a right way to do it?
Thanks
From this document
The FromSqlInterpolated and ExecuteSqlInterpolated methods allow using
string interpolation syntax in a way that protects against SQL injection attacks.
var results = _context.Categories.FromSqlInterpolated(
$"Select * from Category where name like {"%" + partialName + "%"}");
Or you can also change your query to Linq-to-Entity like this way
var results = _context.Categories.Where(p => p.name.Contains(partialName ));

How do I use a PostgreSQL function that returns a table as a CakePHP 3 Model?

Using Cake PHP 3.x and we have a PostgreSQL 9.6.3 db.
We make extensive use of PG functions that return tables - for example
select * from getStudies(cid,UID, SID);
Functions are used for various applications - one of them is more complex filtering of rows from a table - where Cake has difficulty.
One option is to implement the logic as a custom Cake Model method in PHP, but the SQL code and amount of joins makes it messy in PHP.
We think we should be able to create a Cake Model from the function and then pass the parameters via Cake Model methods but so far - it is unclear how to do that.
This code works but it returns the data without the columns and I have not been able to figure out how to use reflection to get the _columns properties from the Model schema.
public function getStudies($data = array()) {
$customer_id = $data['customer_id'];
$connection = ConnectionManager::get('default');
$sql = "select * from getStudies($customer_id)";
$results = $stmt->fetch();
return $results; }
So -
Option 1 - figure out how to model a function that returns tables as a cake model
Option 2 - use reflection to get the _columns and merge it with the query result
Thanks
As you've mentioned in the comments, the schema columns details can be accessed via its columns() method. You could process the results manually using the schema information, or use the function as the source, just like in your example.
The query builders from() method supports raw SQL as well as expressions, so you can basically add whatever you like, however expressions will be wrapped in parentheses, which will be invalid SQL in case of a function call, so you'd have to go with raw SQL, and bindings (please never inject (user)data into queries directly):
public function getStudies($customerId)
{
return $this
->find()
->from([
$this->alias() => 'getStudies(:customerId)'
])
->bind(':customerId', $customerId, 'integer');
}
That should generate a query similar to
SELECT
Alias.column1, Alias.column2, ...
FROM
getStudies(:customerId) Alias

How php/mysqli ( prepared statements + bind params ) protect against SQL Injection?

How php/mysqli ( with prepared statements + bind params ) protect against SQL Injection ?
Mysqli applies only "real_escape_string" for variables or do something else?
May i say that the function below is totally useless when using mysqli + prepared statements + bind params ?
function no_injection ( $data ) {
$data = trim(strip_tags($data)); // no htm in this case.
$data = get_magic_quotes_gpc() == 0 ? addslashes($data) : $data; // useless.
$data = preg_replace("#(--|\#|;)#s", """, $data); // <--- USELESS ?
return $data;
}
Thanks
addslashes() is NOT unicode aware. There's a fair number of unicode sequences that look like normal text, but turn into different things when processed by non-unicode aware code, allowing a malicious user to construct a "valid" unicode string that comes an SQL injection attack once addslashes trashes the string.
The same goes for your regex. You've not enabled unicode mode, so it can potentially allow malicious unicode characters to leak through and become regular iso8859 chars that'll break the query.
Beyond that, each database has its own escaping requirements. MySQL understands and honors the backslash for escaping, so ' becomes \'. But another database might use '' as the escaped ', and applying a MySQL escape sequence for that database will be useless.
Prepared statements allow a complete separation of query and data. When you write your own query manually, the DB server has absolutely no way of knowing that a part of the query string is potentially malicious and treat it specially. It just sees a query string.
With prepared statements, the query body and the data going into the query are kept separate up until they reach the database server, and the db server can handle the escaping itself.
In real world terms, it's the difference between handing someone a loaf of poisoned bread, and handing them a basket of milk, eggs, flour, bottle of poison, yeast, etc... There's no way to tell there's poison in the bread until after you've eaten it and drop dead. While with the ingredients (aka prepared statement), the DB server will see that bottle of poison and know how to handle it.
It also caches the queries which will increase performance with more "calls".
-> http://dev.mysql.com/doc/refman/5.1/en/c-api-prepared-statements.html
-> Should I use prepared statements for MySQL in PHP PERFORMANCE-WISE?

Play Framework - find Object with "Or" in the query

It is possible to use "AND" while querying for Objects in Entity like
Post.find("byTitleLikeAndAuthor", "%hello%", connectedUser).fetch();
but is it possible to user "OR" while querying, like
Post.find("byNameOrEmail", name, email).fetch();
Thank you
Fixed!!
Use Post.find(" name = ? or email ?", name, email).fetch();
While using "where" in the query, it fails saying "unexpected token"
It is indeed possible to use "And" clauses when constructing objects, but I'm not aware of a possibility in simplified query to use "Or".
However, play can be used in many ways. Instead of writing :
Post.find("byNameOrEmail", name, email).fetch();
You can write :
Post.find("name = ? or email = ?", name, email).fetch();
using JPQL syntax.
It's not possible to use simplified query with or. To enable it you must change the implementation of findByToJPQL in the class play.db.jpa.JPQL. Wrote test and enhance the documentation and create a patch.
How ever you can use the JPQL.