Issue with cakePHP running unit tests - mysql

I've have the weirdest issue while trying to test something in my cakePHP 2.0 app. I have a function inside a model that queries the database to check if the app has already sent a notification in the last 25 days:
public function checkIfNotified($userId){
$query = 'SELECT count(`user_id`) AS notify '.
'FROM `churn_stats` '.
'WHERE `user_id` = '. $userId.' '.
'AND `notified` = 1 '.
'AND TIME_TO_SEC(TIMEDIFF(NOW(),`created`)) <= 2160000 ';
$this->log($query);
$result = $this->query($query);
return $result;
}
I'm doing some Unit tests to check if the method works, so I'm creating a record and trying to test it return return true like so:
$data['notified'] = 1;
$data['user_id'] = $userId;
$this->ChurnStats->create();
$this->ChurnStats->save($data);
$notified = $this->ChurnStats->checkIfNotified($userId);
print_r($notified);
After the result is (which is the wrong result since I've already inserted a row!):
Array
(
[0] => Array
(
[0] => Array
(
[notify] => 0
)
)
)
However I run the exact query generated by the code in the DB and the result is:
I've already lost a lot of time and I don't have any idea what's wrong :(.

After testing and checking everything it was another test function that somehow was changing the DB or the query of the next test, however the weird part was that the other test called the same query but didn't have any insert, update or delete that could modify the results or enviroment of the next test.
After checking everything it all reduced to something: Query Cache, by default CakePHP caches all the $this->query("..."); calls so the fix was quite easy: Deactivate it!
$result = $this->query($query, false);

Related

how to inject sql in login process

I've received an old application which completely lacks user input sanitization and is vulnerable to sql injection. To prove gravity of the situation i need to give client an example and what can be better to scare him than the login process. I've tried standard techniques but the problem with them is that they return multiple rows and due to nature of the code it returns an error instead of logging him in. What sql should i inject so that only a single row is returned and the execution reaches "return $access" line in order to pass the value of this "access" column to code calling this login function. The request is made via POST method and magic quotes are off on the server. Please let me know if you need any other information.
function login($username, $pw)
{
global $dbname, $connection, $sqluser, $sqlpw;
$db = mysql_connect($connection,$sqluser,$sqlpw);
mysql_select_db($dbname);
if(!($dba = mysql_query("select * from users where username = '$username' AND password = '$pw'"))){
printf("%s", sprintf("internal error5 %d:%s\n", mysql_errno(), mysql_error()));
exit();
}
$row = mysql_fetch_array($dba);
$access = $row['access'];
if ($access != ''){
return $access;
} else {
return "error occured";
}
mysql_close ($db);
}
Note: it turns out that magic_quotes_gpc is turned on and the php version is 5.2.17
Thanks
Starting with the goal query:
SELECT *
FROM users
WHERE username = '' OR '1'='1'
AND password = '' OR 1=1 LIMIT 1;#'
We get username is ' OR '1'='1 and password is ' OR 1=1 LIMIT 1;#
It depends what values the login function is called with. If there's sanitation before passing it to the function it might actually be safe. However it's better to filter it right before the query so you can see that your built query is safe.
However if you have something like this:
login($_POST['user'], $_POST['pass']);
In that case just put foo' OR 1=1 OR ' in the user field in the login form :)

Prepared statement fetches all the results in db, but not one I ask for

Trying to make my blog secure and learning prepared statements.
Although I set the variable, I still get all the entries from database. $escapedGet is real variable when I print it out. It's obviously a rookie mistake, but I cant seem to find an answer.
I need to get the data where postlink is $escapedGet not all the data.
$escapedGet = mysql_real_escape_string($_GET['article']);
// Create statement object
$stmt = $con->stmt_init();
// Create a prepared statement
if($stmt->prepare("SELECT `title`, `description`, `keywords` FROM `post` WHERE `postlink` = ?")) {
// Bind your variable to replace the ?
$stmt->bind_param('i', $postlink);
// Set your variable
$postlink = $escapedGet;
// Execute query
$stmt->execute();
$stmt->bind_result($articleTitle, $articleDescription, $articleKeywords);
while($stmt->fetch()) {
echo $articleTitle, $articleDescription, $articleKeywords;
}
// Close statement object
$stmt->close();
}
just tryed this: echo $escapedGet;
echo $_Get['artcile']
and got - some_other
thats the same entry that I have saved in database as postlink
tried to shande postlink to id, and then it worked. but why not with postlink tab?
When you are binding your data using 'i' modifier, it gets bound as integer.
Means string will be cast to 0 in the final statement.
But as mysql does type casting, your strings become zeroes in this query:
SELECT title FROM post WHERE postlink = 0;
try it and see - for the textual postlinks you will have all your records returned (as well as a bunch of warnings).
So, bind strings using s modifier, not i

Perl fetch without execute error - at end of execution

My current perl code is running through all of the rows of the database query and then throwing a
DBD::mysql::st fetchrow_hashref failed: fetch() without execute() at ./recieveTxn.cgi
line 168.
At the end. It almost is like there's something that's not telling the loop to stop at the end of the rows, but I have written it just as the others.
So for example: The query would pull up
shortcode1
shortcode2
shortcode3
then throw the error here
$sql = "
SELECT
aPI.folder AS aPIfolder,
aPI.rowNum AS aPIrowNum,
hasInput,
evalCode
FROM
aPersonalItems as aPI
LEFT JOIN
pItems_special_inputs as SI
ON
aPI.folder = SI.folder AND
aPI.rowNum = SI.rowNum
WHERE
hasInput=1 AND
aPI.folder='$FORM{'folder'}'
ORDER BY
aPI.rowNum
";
$sth = $dbh->prepare( $sql );
$sth->execute();
my ($shortcoderow, $row);
my $shortcodeSQL = "
SELECT
*
FROM
pItemsShortCodes
WHERE
folder='$FORM{'folder'}'
ORDER BY
rowNum
";
my $shortcodeSTH = $dbh->prepare( $shortcodeSQL );
$shortcodeSTH->execute();
while( my $ref = $sth->fetchrow_hashref() ) {
my $shortCode;
my $isblank = 1;
my $rowNum = $ref->{'aPIrowNum'};
while(my $shortcodeRef = $shortcodeSTH->fetchrow_hashref())
#&& $rowNum == $shortcodeRef->{'rowNum'}) #line 168 above
{
$shortCode=$shortcodeRef->{'shortcode'};
print $shortCode."\n";
}
$shortcodeSTH->finish();
}
The problem is that you are processing more than one row from $sth.
Your code fetches a row from $sth, and then your code loops through every row from $shortcodeSTH, until there are no more rows. Then your code calls the finish() method on $shortcodeSTH. (Which is the normative pattern, since you've already fetched all the rows.)
Then, your code starts through the outer loop a second time, fetching a second row from $sth. When your code attempts to start through the $shortcodeSTH loop a second time, you've already fetched all of the rows and closed the statement handle. There aren't any more rows to retrieve. (The error returned would be different if you hadn't issued the call to the finish() method; the error message would be something about fetching past the end of the cursor, or already fetched last row, or something to that effect.)

$this->db->affected_rows() returns -1 after query in codeigniter

I have a query like this in codeigniter
$update= $this->db->query("update aas set aa = 'aa' where no=" . $this->db->escape($No) . "");
When I run
echo $this->db->affected_rows() or echo $this->db->affected_rows($update)
it returns -1
When updating any row which exists I get -1
Even when I have no row to update it still shows -1.
What is the issue? I am using codeigniter 2.1.0 with mysqli drivers
I have tried running it in phpmyadmin and it gives me the proper 0 or 1 rows affected as per the data.But when i run it through codeigniter I get -1 even when The value to be updated has changed or remained same
The query is true always in codeigniter
Is it because I have turned on codeigniter mysqli drivers
Displays the number of affected rows, when doing "write" type queries
(insert, update, etc.).
Reference: Here.
Incorrect (quotes) in your sql statement (so not being executed)
$update= $this->db->query("update aas set aa = 'aa' where no=" . $this->db->escape($No) . "");
should be
$update = $this->db->query("update aas set aa = 'aa' where no = '{$this->db->escape($No) }'");
echo $this->db->affected_rows();
It's totally up to you, but you could also convert this query into CodeIgniter's Active Record Class. Not only does it escape everything for you automatically, its easier to use for simple queries and avoid a potential issue with incorrect quotes in your SQL statements.
So, for Active Record, it would look like this:
$data = array(
'aa' => 'aa'
);
$this->db->where('no', $No)->update('aas', $data);
echo $this->db->affected_rows(); // this should return 1 now

How to get Ruby MySQL returning PHP like DB SELECT result

So I use the PDO for a DB connection like this:
$this->dsn[$key] = array('mysql:host=' . $creds['SRVR'] . ';dbname=' . $db, $creds['USER'], $creds['PWD']);
$this->db[$key] = new PDO($this->dsn[$key]);
Using PDO I can then execute a MySQL SELECT using something like this:
$sql = "SELECT * FROM table WHERE id = ?";
$st = $db->prepare($sql);
$st->execute($id);
$result = $st->fetchAll();
The $result variable will then return an array of arrays where each row is given a incremental key - the first row having the array key 0. And then that data will have an array the DB data like this:
$result (array(2)
[0]=>[0=>1, "id"=>1, 1=>"stuff", "field1"=>"stuff", 2=>"more stuff", "field2"=>"more stuff" ...],
[1]=>[0=>2, "id"=>2, 1=>"yet more stuff", "field1"=>"yet more stuff", 2=>"even more stuff", "field2"=>"even more stuff"]);
In this example the DB table's field names would be id, field1 and field2. And the result allows you to spin through the array of data rows and then access the data using either a index (0, 1, 2) or the field name ("id", "field1", "field2"). Most of the time I prefer to access the data via the field names but access via both means is useful.
So I'm learning the ruby-mysql gem right now and I can retrieve the data from the DB. However, I cannot get the field names. I could probably extract it from the SQL statement given but that requires a fair bit of coding for error trapping and only works so long as I'm not using SELECT * FROM ... as my SELECT statement.
So I'm using a table full of State names and their abbreviations for my testing. When I use "SELECT State, Abbr FROM states" with the following code
st = #db.prepare(sql)
if empty(where)
st.execute()
else
st.execute(where)
end
rows = []
while row = st.fetch do
rows << row
end
st.close
return rows
I get a result like this:
[["Alabama", "AL"], ["Alaska", "AK"], ...]
And I'm wanting a result like this:
[[0=>"Alabama", "State"=>"Alabama", 1=>"AL", "Abbr"=>"AL"], ...]
I'm guessing I don't have the way inspect would display it quite right but I'm hoping you get the idea by now.
Anyway to do this? I've seen some reference to doing this type of thing but it appears to require the DBI module. I guess that isn't the end of the world but is that the only way? Or can I do it with ruby-mysql alone?
I've been digging into all the methods I can find without success. Hopefully you guys can help.
Thanks
Gabe
You can do this yourself without too much effort:
expanded_rows = rows.map do |r|
{ 0 => r[0], 'State' => r[0], 1 => r[1], 'Abbr' => r[1] }
end
Or a more general approach that you could wrap up in a method:
columns = ['State', 'Abbr']
expanded_rows = rows.map do |r|
0.upto(names.length - 1).each_with_object({}) do |i, h|
h[names[i]] = h[i] = r[i]
end
end
So you could collect up the rows as you are now and then pump that array of arrays through something like what's above and you should get the sort of data structure you're looking for out the other side.
There are other methods on the row you get from st.fetch as well:
http://rubydoc.info/gems/mysql/2.8.1/Mysql/Result
But you'll have to experiment a little to see what exactly they return as the documentation is, um, a little thin.
You should be able to get the column names out of row or st:
http://rubydoc.info/gems/mysql/2.8.1/Mysql/Stmt
but again, you'll have to experiment to figure out the API. Sorry, I don't have anything set up to play around with the MySQL API that you're using so I can't be more specific.
I realize that php programmers are all cowboys who think using a db layer is cheating, but you should really consider activerecord.