Possible SQL Injection in AJAX request? - java

I am developing search indexing using PHP and AJAX to make it powerful.
When I scan it using burpsuit or other security scanner, SQL injection appears in AJAX code and I can't find any solution for it. The code is below:
<?php
require_once 'Connections/connect.php';
if($_GET['type'] == 'mobile'){
$result = mysql_query("SELECT mobilep FROM dictionary where mobilep LIKE '".$_GET['name_startsWith']."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row['mobilep']);
}
echo json_encode($data);
}
?>

This is very bad... you're using the deprecated mysql adapter.
http://php.net/manual/en/book.pdo.php
Use pdo and binds, here's a full prototype:
class MySql
{
private $sDbName = '';
private $sUsername = '';
private $sPassword = '';
private $sHost = '';
private $oConnection = null;
public function __construct()
{
$this->oConnection = new PDO(
'mysql:host='
. $this->sHost
. ';dbname='
. $this->sDbName,
$this->sUsername,
$this->sPassword
);
}
public function getDb()
{
return $this->oConnection;
}
}
$aReturn[ 'data' ] = '';
if( !empty( $_GET[ 'type' ] )
&& ( !empty( $_GET[ 'name_startsWith' ] )
&& ( $_GET['type'] == 'mobile' )
)
{
$oMySql = new MySql;
$oDb = $oMySql->getDb();
$sSql = "SELECT mobilep FROM dictionary where mobilep LIKE :name";
$aBinds[ ':name' ] = $_GET[ 'name_startsWith' ] . '%';
$oStmp = $oDb->prepare( $sSql );
$oMySql->bindVariables( $oStmp, $aBinds );
$oStmp->execute();
$oResults = $oStmp->fetchall();
if( !empty( $oResults ) )
{
// var_dump( $aResults );
$oErrors = $oStmp->errorInfo();
// var_dump( $oErrors );
$aReturn[ 'data' ] = $aResults;
}
}
$sJson = json_encode( $aReturn, 1 );
header( 'Content-type', 'application/json' );
echo $sJson;

(Yes, this is question over a year old. But there is no selected answer. I ran across this question in a search...)
If you are stuck with mysql_ interface functions, and can't migrate to mysqli or PDO, the best you can do is to use the mysql_real_escape_string function.
existing code:
= mysql_query(" ... LIKE '". $_GET['name_startsWith'] ."%'");
to properly escape a potentially unsafe value, before it's incorporated into the SQL text, use the mysql_real_escape_string function...
= mysql_query(" ... LIKE '". mysql_real_escape_string( $_GET['name_startsWith'] )."%'");
^^^^^^^^^^^^^^^^^^^^^^^^^ ^

Related

How to pass dynamic value in .apned in reactjs

I m using file upload with react and axios and fileupload working fine. and currently i am using fixed id in data.append('customeId', '123456'); but i want to use id value dynamic bcz there are multiple user. i want to use this id like let customeId = localStorage.getItem("customeId");. please help me use id value dynamic.
i am currently using
uploadFile = ({ target: { files } }) =>{
console.log( files[0] )
let data = new FormData();
data.append('customeId', '123456');
data.append( 'file', files[0] )
// data.append = localStorage.getItem("brokerId");
const options = {
onUploadProgress: (progressEvent) => {
const {loaded, total} = progressEvent;
let percent = Math.floor( (loaded * 100) / total )
console.log( `${loaded}kb of ${total}kb | ${percent}%` );
if( percent < 100 ){
this.setState({ uploadPercentage: percent })
}
}
}
axios.post("https://apimarkp.com/user/", data, options).then(res => { }
What i want
uploadFile = ({ target: { files } }) =>{
let customeId = localStorage.getItem("customeId");
console.log( files[0] )
let data = new FormData();
data.append('customeId', 'customeId');
data.append( 'file', files[0] )
// data.append = localStorage.getItem("brokerId");
const options = {
onUploadProgress: (progressEvent) => {
const {loaded, total} = progressEvent;
let percent = Math.floor( (loaded * 100) / total )
console.log( `${loaded}kb of ${total}kb | ${percent}%` );
if( percent < 100 ){
this.setState({ uploadPercentage: percent })
}
}
}
axios.post("https://apimarkp.com/user/", data, options).then(res => { }
when you log in at the APP you should write on the localStorage
localStorage.setItem("customeId", customer.Id);
now you can use in your function:
uploadFile = ({ target: { files } }) =>{
let customeId = localStorage.getItem("customeId");

Magic Properties from PHP in Java

in PHP I have a Model class, that loads data from the database. Since many other classes use this Model, it's easy for me to load variables like this.
public function loadModel( $id ) {
$result = $this->queryData( self::RETURN_MODE_ASSOC, array(), array('id' => $id ));
if (count($result) > 0 ) {
$this->loadRow( $result[0] );
return true;
}
return false;
}
public function loadRow( $row ) {
foreach ($row as $key=>$val) {
$this->$key = $val;
}
}
Now, for each Class that uses the model. I can simply access these variables. How is that possible in Java? I have a class
User and a Model named Model.
I mean, I can't simply use this.key like this
JSONObject jsonObj = new JSONObject(result);
Iterator iter = jsonObj.keys();
while(iter.hasNext()){
this.key = (String)iter.next();
}
Is it possible in Java to do this/

JSON to Java Object without creating class (PHP way)

I am dealing with json data fetched from twitter API
on PHP I normally do something like:
$data = json_decode($response);
and the $data would be STD class object
I want to do the same thing in Java.
I took a look at Gson, but I need a second argument which seems like I need to create a specific class for the fetched data.
The basic question is how can I convert JSON to Standard Java Object like in PHP (STD Class Object)
Thank You
Read it into a map using Jackson then you can access whatever data you want. For instance, if your json looks like this
{ "name":"blah",
"address": {
"line1": "1234 my street",
"city": "my city",
"state": "my state"
}
}
Then you could:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> mystuff = mapper.readValue( jsonString, Map.class );
String name = (String)mystuff.get("name");
String city = ((Map<String, Object>)mystuff.get( "address" )).get( "city" );
If your JSON data does not follow a specific structure, don't use GSON, but a regular JSON library (like the one from json.org) that will give you an instance of a class like JSONObject, from which you can access data like jsonObject.getString("key").
There is no standard class object in Java and thus you need a class. You could dynamically create and compile the class at runtime but I doubt that's worth the trouble.
When json_encode doesn't exist on a PHP server, I use this:
<?php
if (!function_exists('json_encode'))
{
function json_encode($a=false)
{
if (is_null($a)) return 'null';
if ($a === false) return 'false';
if ($a === true) return 'true';
if (is_scalar($a))
{
if (is_float($a))
{
// Always use "." for floats.
return floatval(str_replace(",", ".", strval($a)));
}
if (is_string($a))
{
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
}
else
return $a;
}
$isList = true;
for ($i = 0, reset($a); $i < count($a); $i++, next($a))
{
if (key($a) !== $i)
{
$isList = false;
break;
}
}
$result = array();
if ($isList)
{
foreach ($a as $v) $result[] = json_encode($v);
return '[' . join(',', $result) . ']';
}
else
{
foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
return '{' . join(',', $result) . '}';
}
}
}
?>
If you could rewrite this in Java then it should to the trick for you.
Ref:(Dead link)http://snippets.dzone.com/posts/show/7487

Login-Authentication to a remote mysql database

I have this line of code here.
My java code:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
$public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters);
String res=response.toString();
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1")){
txtError.setText("Correct Username or Password");
//Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class);
//startActivity(i);
}
else {
txtError.setText("Sorry!! Incorrect Username or Password");
}
} catch (Exception e) {
txtUsername.setText(e.toString());
}
}
});
}
My php script code:
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
$user = ‘bduser’;
$pswd = ‘dbpwd’;
$db = ‘phplogin’;
$conn = mysql_connect("localhost","root","");
mysql_select_db($db, $conn);
$query = mysql_query("SELECT * FROM user WHERE username = '$un' AND password = '$pw'");
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
if(mysql_num_rows($result) == 1)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
I have a problem with this code. In my android code when I try to change the res.equals to contains. It always say correct password but if I will not change it, it says incorrect password. I don't know there is something wrong in my java code or in my php code. really need help.
It looks like the error is in the PHP code.
Change the following line:-
From:
$query = mysql_query("SELECT * FROM user WHERE username = '$un' AND password = '$pw'");
To:
$query = "SELECT * FROM user WHERE username = '$un' AND password = '$pw'";
You should also consider making changes to prevent SQL Injection:-
$query = sprintf("SELECT * FROM user WHERE username =
WHERE username='%s' AND password='%s'",
mysql_real_escape_string($un),
mysql_real_escape_string($pw));
In the code you are doing mysql_query(mysql_query()) I believe.
First try:
txtError.setText(res);
By the way: SQL injection. If you enter as password:
' UNION SELECT * FROM user WHERE username='admin
Change your PHP to 'select count(*)' and check for the actual numeric value of the result. This way you aren't trying to compare against a possible NULL which can throw off line counts.
Also check your PHP separately to make sure you're getting the correct response from the ECHO.
Be aware that your android code will block until it gets a result. You should probably recode it in a thread. Otherwise the device will throw 'non responsive' and exit if SQL is too slow.
EDIT: add some code - slightly different in that it checks for whether or not a specific value is set rather than whether anything was returned. Same idea, a few more lines of code.
/** Authenticate a login.
*
* #param string $Username
* #param string $Password
* #return int
*/
function login( $Username, $Password )
{
Logger::DEBUG( "Login attempt by '" . $Username . "'");
try
{
$conn = DBConnection::_getConsole2DB();
$query = "select LoginId, UserId, RoleId, ProjectMask, RestrictionMask from Users where LoginId = ? and Password = ? and Active = 1";
$st = $conn->prepare( $query );
$st->bindParam( 1, $Username );
$st->bindParam( 2, $Password );
$st->execute();
$row = $st->fetch( PDO::FETCH_ASSOC );
if( !isset( $row[ 'UserId' ])) return 0;
$this->userId = $row[ 'UserId' ];
$this->roleId = $row[ 'RoleId' ];
$this->projectMask = $row[ 'ProjectMask' ];
$this->restrictionMask = $row[ 'RestrictionMask' ];
$_SESSION[ 'userId' ] = $this->userId;
$_SESSION[ 'roleId' ] = $this->roleId;
$_SESSION[ 'projectMask' ] = $this->projectMask;
$_SESSION[ 'restrictionMask' ] = $this->restrictionMask;
$_SESSION[ 'loginId' ] = $row[ 'LoginId' ];
}
catch( PDOException $e )
{
Logger::PDO_ERROR( $e );
return -1; // error
}
return 1;
}
This uses PDO so there are some small syntax differences with what you're trying.

How can I port PHP preg_split to Java for the special case of unserializing a value in ADODB?

I need to port this function for unserializing a value in ADODB to Java.
$variables = array( );
$a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
for( $i = 0; $i < count( $a ); $i = $i+2 ) {
$variables[$a[$i]] = unserialize( $a[$i+1] );
}
I have a library to unserialize the values the php way, but I need help on porting over the preg_split. What would this regex look like in Java?
Equivalent java code :
import java.util.List;
import java.util.ArrayList;
// Test
String serialized_string = "foo|bar|coco123||cool|||";
// Split the test
String[] raw_results=serialized_string.split("\\|");// Trailing empty strings are removed but not internal ones
// Cleansing of the results
List<String> php_like_results = new ArrayList<String>();
for(String tmp : raw_results) {
if (tmp.length()>0) {
php_like_results.add(tmp);
}
}
// Output results
System.out.println(php_like_results);
This will produce :
[foo, bar, coco123, cool]

Categories