I am developing mobile application in which I have used WebSql as local database. Now I am creating a search functionality where I want to escape "_" when the user will search the records. I tried using the MS-SQL approach by passing it in square bracket "[ _ ]"
Below are my code example
if ($.trim($('#txtPolicy').val()).length > 0) {
policy = $.trim($('#txtPolicy').val());
if (policy.indexOf("_") >= 0)
policy = policy.replace(/_/g, "[_]");
query += " (";
var arrploicy = policy.split(',');
for (var j = 0; j < arrploicy.length; j++) {
query += " policy like ? or ";
arr[i] = "%" + arrploicy[j] + "%";
++i;
}
query = query.substring(0, query.length - 3);
query += ") ";
}
I have a records which has data as 1234_456789. But it does not return any records, probably because it might be considering it as string.
You can use parameterized query without requering uou to escape. It is more secure too.
Related
I am using the SqliteModernCpp library. I have a data access object pattern, including the following function:
void movie_data_access_object::update_movie(movie to_update)
{
// connect to the database
sqlite::database db(this->connection_string);
// execute the query
std::string query = "UPDATE movies SET title = " + to_update.get_title() + " WHERE rowid = " + std::to_string(to_update.get_id());
db << query;
}
Essentially, I want to update the record in the database whose rowid (the PK) has the value that the object to_update has in its parameter (which is returned by get_id()).
This code yields an SQL logic error. What is the cause of this?
It turned out single quotes (') within the query string being created were missing. The line should be:
std::string query = "UPDATE movies SET title = '" + to_update.get_title() + "' WHERE rowid = " + std::to_string(to_update.get_id());
Since there is no UPDATE example in the official docs on github, This is how UPDATE queries should be implemented with prepared statements and binding
#define MODERN_SQLITE_STD_OPTIONAL_SUPPORT
#include "sqlite_modern_cpp.h"
struct Book {
int id;
string title;
string details;
Book(int id_, string title_, string details_):
id(std::move(id_)),
title(std::move(title_)),
details(std::move(details_)) {}
}
int main() {
Book book = Book(0, "foo", "bar")
sqlite::database db("stackoverflow.db");
// Assuming there is a record in table `book` that we want to `update`
db <<
" UPDATE book SET "
" title = ?, "
" details = ? "
" WHERE id = ?; "
<< book.title
<< book.details
<< book.id;
return 0;
}
I want to build a SELECT statement using a list of conditions that come from the query string of a REST api. I wrote this function, but maybe it is vulnerable to SQL injection. Can someone tell me if this is vulnerable how to fix it? Perhaps I should use some kind of SQLBuilder package? or is there a way to do it with just dotNet. I'm using dotNet 4.6.1
string BuildSelect(NameValueCollection query)
{
var result = "SELECT * FROM MYTABLE";
if (query.Count == 0) return result;
var logic = " WHERE ";
foreach (string key in query)
foreach (string v in query.GetValues(key))
{
result += logic + key + " = " + v;
logic = " AND ";
}
return result;
}
Yes it is vulnerable to SQL injection attack. You could build your query to use parameters instead (you are simply using an = check only).
Since you know the tablename, that means you also know what the columns (keys) can be. Thus, you could loop your columns, if the collection has that key then add it to the where as a parameterized statement BUT value part is NOT passed as a string, you parse it to the type it should be (or let the backend do the conversion and get error if cannot be converted). In pseudocode:
List<string> clauses = new List<string>();
var result = "SELECT * FROM MYTABLE";
foreach( var col in myTable.Columns )
{
if (query.ContainsKey(col.Name))
{
clauses.Add( $"{col.Name} = #{col.Name}";
string v = query[col.Name];
command.Parameters.Add( $"#{col.Name}", col.Type).Value = typeParse(v);
}
}
if (clauses.Any())
{
result += " WHERE " + string.Join( " AND ", clauses );
}
return result;
HTH
I am trying to code an array list that contains information from a text file that should add all the characters of the names together to give me a total. I have done it but it adds the spaces to, i have tried using .split(" "); but it still didnt work.
here is my code so far
String tempLatinName = " ";
String latinLength = " ";
int letters = 0;
for (int i = 0; i < info.size(); i++) {
tempLatinName = info.get(i).getLatinName();
tempLatinName.split(" ");
latinLength = tempLatinName;
letters += latinLength.length();
}
System.out.println("Total number of letters in all Latin names = " + letters);
any suggestions?
If you want to get the number of characters in your string, instead of tempLatinName.split(" "); you should try latinLength = tempLatinName.replace(" ",""); and then you would get the length with the string without spaces with latinLength.Length
More about replace here
More about Length here
based from here
have you tried the following:
tempLatinName.split(' ');
or
tempLatinName.split();
Hello I jsut wondering if its posibble to have a query on web sql cause im using a phonegap for phone development and i have an error on this code
tx.executeSql("SELECT * FROM DEMO WHERE log=(\"?\")", [_searchtext], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status2').innerHTML += msg;
for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status2').innerHTML += msg;
}
}, null);
and I can't have any result but on SELECT * FROM DEMO i have a lot of result.
all I am doing is to get all data and put on the loop and condition the data to the searchtext. but i love to make it on the websql. thanks.
Is this code sufficient to protect me from SQL injection attacks, and PHP injection attacks?
I have this function in an include file of functions:
function strclean ($string) {
$outstr = '';
if (strlen ($string) > 0) {
$ix = 0;
$char = substr ($string, $ix, 1);
// strip leading spaces
while ($char == ' ') {
$ix = $ix + 1;
$char = substr ($string, $ix, 1);
}
// disarm naughty characters
while ($ix < strlen ($string)) {
$char = substr ($string, $ix, 1);
if ($char == '<') $char = '<';
else if ($char == '>') $char = '>';
else if ($char == '"') $char = '"';
else if ($char == '&') $char = '&';
else if ($char < chr(20)) $char = '';
$outstr = $outstr . $char;
$ix = $ix + 1;
}
// strip trailing spaces
while (substr ($outstr, strlen ($outstr) - 1, 1) == ' ' && strlen ($outstr) > 0) {
$outstr = substr ($outstr, 0, strlen ($outstr) - 1);
}
$outstr = mysql_real_escape_string ($outstr);
}
return $outstr;
}
Later on in my page, I have various strings returned from form input such as this example:
$username = strclean ($_POST['username']);
$password = strclean ($_POST['password']);
And even later, I have the following SQL:
$result = mysql_query ('SELECT * FROM users WHERE
username = "' . $username . '"', $dbconn) or die (mysql_error());
I don't search for username and password together in the query. A few lines after this, I check for a valid password like this:
if ($rowsfound == 1) {
$userrow = mysql_fetch_array ($result);
$userword = $userrow ["password"];
if ($userword == $password) {
// logon
}
else {
// incorrect password
}
}
else if ($rowsfound == 0) {
// unknown user
}
else {
// something strange happened! possible sql injection attack?
}
The general rule is to deny everything and allow through only valid characters, rather than removing what you consider to be invalid.
The most important aspect is what you do with these string afterwards. If you have a line later saying:
tsql = "SELECT * FROM Users WHERE Username='" . $username . "' AND "
then this is the primary area of risk, although mysql_real_escape_string should avoid this.
By using a libraries or features that allow passing of parameters to the database there can never be any sql injection, as the database parameters can't be interpreted into TSQL, leaving only PHP/Javascript injection as a possibility.
Basically, look at the bind_param functions as the only true protection.
Whenever displaying data on-screen, consider something like htmlspecialchars() to convert it to HTML. There's no point in storing something escaped if you need it un-escaped later, and raw data in the database poses no risk as long as you always consider it raw.
In summary, the code you list may or may not reduce injection, but there are too many combinations to exclude every possibility, including aspects such as a user using single quotes (you're only replacing double quotes).
All user input data is potentially dangerous. Feel free to store it raw, but whenever USING it make sure your operations are protected using one of the above options.
My PHP is a bit rusty now, but exactly the same rules apply to SQL Server, Oracle, .NET, Java any any other database/language.