Lavalair Sql Injection Blocker

Started on the old forum in March 2009 · view the original in the archive · old links redirect here

41 replies · 7,140 views · started 17 years ago · 1 min read

31 participants
subzero Super moderator Fellow · 3,954 posts #2

You should have magic quotes turned on in your php.ini file if you don't already:

magic_quotes_gpc = On

This will prevent a lot of problems.

And avoid using $_REQUEST or $_POST directly in your code. It's better to create a function to retrieve a value. Then you know that if that function is written properly there is no chance of injections happening anywhere within the site. It's also good if you need to change the way the retrievals work, you don't have to change it everywhere in your code.

e.g.

function get($name) {
if (isset($_REQUEST[$name]))
/* if you don't have magic quotes on 
return addslashes($_REQUEST[$name]);
*/
return $_REQUEST[$name];
else
return false;
}

Visit: Chat4u.mobi - The New Lay Of being a site of your dreams! Visit: WapMasterz Coming Back Soon!


SCRIPTS FOR SALE BY SUBZERO Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders. FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others... _______…

anderson Developer · 146 posts #3
  1. validate all the input fields.
  2. use this function, mysql_real_escape_string . PHP team made it only to prevent sql injections. The function containg 24 characters may protect your valuable DB!!

Wait...

jsyguy23 Developer · 134 posts #6

$uid=mysql_real_escape_string( $_GET["uid"] );

something else Fellow · 2,296 posts #7

Try not to Register globals oneither because if you do:

$uid=mysql_real_escape_string( $_GET["uid"] );

wont stop hackers from POSTing sql into your script instead

eg:

<form method="**post**" action="**<http://yoursite.com>**/web/genproc.php?action=profile&sid=c37c0f63cb584676b9599191ffa91256"> <input name="**uid**"/> <input type="Submit" value="Go" Name="Submit"/> </form>

(because you have got globals on information can be collected either by GETor POST) hence why turning globals on is dodgy...... might be a quick fix to solve all your problems in 1 hit. but can give you 1 hell of a headache at a later date 🙂

also same reason why try to avoid using $uid = $_REQUEST["uid"];

sweetangel Lead · 885 posts #8
//protect against sql injections and remove $ sign
if( !get_magic_quotes_gpc() )
{
    if( is_array($_GET) )
    {
        while( list($k, $v) = each($_GET) )
        {
            if( is_array($_GET[$k]) )
            {
                while( list($k2, $v2) = each($_GET[$k]) )
                {
                    $_GET[$k][$k2] = addslashes($v2);
                }
                @reset($_GET[$k]);
            }
            else
            {
                $_GET[$k] = addslashes($v);
            }
        }
        @reset($_GET);
    }

    if( is_array($_POST) )
    {
        while( list($k, $v) = each($_POST) )
        {
            if( is_array($_POST[$k]) )
            {
                while( list($k2, $v2) = each($_POST[$k]) )
                {
                    $_POST[$k][$k2] = addslashes($v2);
                }
                @reset($_POST[$k]);
            }
            else
            {
                $_POST[$k] = addslashes($v);
            }
        }
        @reset($_POST);
    }
}

this is 1 code found 😉

if like my post click:

External image (may be gone)

djlee Developer · 224 posts #9

magic_quotes = bad .. and im pretty sure subzero was the one commenting on one of my posts saying that it wont work in PHP6, how can u change ur stand point on PHP6 integrity coding on a per post basis ?

the answer to this is simple

  1. do not rely on magic quotes
  2. do not rely on register global
  3. do not rely on global fixes.

By global fixes i mean the code above that mimics magic quotes when they are disabled. Treat EVERY variable independantly. And as for nost using POST's directly in queries, forget that. Yes you can using a POST in a query is the same as using a var. Except defining a new var takes up extra ram space during script execution. As long as you sanitise your variables you will be fine . for example

mysql_query("SELECT * FROM users WHERE gender = ". $_POST['gender']);

and

$gender = $_POST['gender'];
mysql_query("SELECT * FROM users WHERE gender=$gender");

nothing is different, apart from the second uses more ram space (not enough to make a difference but it all adds up, plus it keeps files shorter and nicer to read IMO)

so how would we clean up that code , pretty simple is sanitisation. There are many ways to sanitise data. A large XSS fix i once used, checks an array for allowed POST's and GET's. in this example its not needed however if you had a larger possible list of allowed terms its a good method (so you maybe searching users for their martial status where it could around 5 different thing)

the array fix

$allowed = array("m", "f");
if(!in_array($_POST['gender'], $allowed)
 die("Gender ".htmlspecialchars($_POST['gender'])." not found!");

this will only allow m and f to be passed as a gender, notice how i used the POSTed var in my error statement. Generally this is bad. If you do not need to use user submitted data for display then dont. The less you do this the less areas people have the chance to test out their new xss strings that may at some point break htmlentities or chars. The user knows what they posted, so why tell them that, in this case it would be more wise to just say "gender not found". i did it like that only as an example of how to sanitise user submitted data

Ok so the array fix isnt good for that example as we only accept two things. maybe we could

mysql_query("SELECT * FROM users WHERE gender = ".($_POST['gender'] == "m" ? "m" : "f"));

here we dont actually use the variable in our statement, so we fully control what the query does. If the gender requested is M then it uses that, anything else it uses F.. we dont need to worry about if they sumbit an invalid gender, you design the interface so normal members can only post M or F.. if they post anything else then who cares if they get a resultset they didnt ask for, there not interested in it anyway

ok so thats 2 ways to santise data in the respects that we only allow what we want. but wat if we want to use submitted data that could be anything such as a avatar or profile message. heres one way

function sqlesc($x)
return "'".mysql_real_escape_string($x)."'";

mysql_query("UPDATE users SET profile=".sqlesc($_POST['prof'])." WHERE uid=".(0+$_POST['uid'])." LIMIT 1");

note: i have added an esacpe function i always use, it auto adds our quotes to the data to save us time and escapes it, plus its shorter to type which is always good

So here we have 2 posted vars, the first we simply sqlesc() it so none of the characters can break the statement, depending on your style of programming you may want to add more checks, but that is all u really need, anything else can be done on display which is what i usually do. u also have the uid to update, notice we 0+ it , you could also use (int) .. up to you. both typecast the var to a integer, we only need integers so typecast it. if there is letters in there that are intended to break the query then the int will be 0 and usually u have no user of id 0 and no users will be found/updated.

There is also one simple security trick here that many over look. thats the limit. If you only want to update one row then tell it so, first it increases speed as it wont look for other rows to update after the first, secondly any malicious code that does magically make itself through will only work on one account, stopping it being spawned to other accounts, so a delete command maliciously inserted wont work as wll as the attacker had hoped.

Now i kno the limit isnt be all end all for security. but in a limited number of situations it will help. We can all think of attacks that this wouldnt be any good for but if u have half a brain u can think of at least one attack string it would perform some help to avoid global spawning attacks. and even if it only helps protect against 1 in 100 attacks.. is it not worth those extra few characters ???

ok so i think thats enough info, just remember 1 basic rule... SANTISE DATA. as long as you sanitise data on input and output you will usually be fine. the very basic of this means, sql escape on input and htmlspecialchars on output

if you have a small example of insecure code which u would like an example on how to secure then post it along with what it does and i'll see if i can help you understand how to secure stuff.


Edit:

the get function subzero posted isnt too bad tbh. personally i dont like using functions, i learnt my PHP from some of the best in the business and i guess my coding style derives from theres. Maybe functions arent any different, but when i think about using such things i think to myself why dont they use it.. and it makes me stray away. One way that get could be imporved while still using request gloabls is like this

funtion getVar($var, $t) 
{
return ($t == 1 ? $_REQUEST[$var] : ($t == 2 ? (int)$_REQUEST[$var] : ($t == 3 && $_REQUEST[$var] == true ? true : false)));
}

note: $t = 1 (string) $t = 2 (int) $t = 3 (Boolean)

so what this does is take the requested variable and typecasts it, if its a string then it just passes it back, if its an int , it typecasts it to an into, and if its a bool it typecats it setting the return value as either bool(true) or bool(false)

this isnt once again be all end all of security, u will still need to atleast sanitise the string data on return, maybe use it as sqlesc(getVar("gender"));

but using inline sanitisation imo is always better in the long run, plus u get used to sanitising data if u have to keep doing it and you will learn much quicker on better methods, rather than having to keep asking about it

subzero Super moderator Fellow · 3,954 posts #10

yes i did...

Also my way you dont need both

magic quotes register global global fixes

Also djlee will work fine

Visit: Chat4u.mobi - The New Lay Of being a site of your dreams! Visit: WapMasterz Coming Back Soon!


SCRIPTS FOR SALE BY SUBZERO Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders. FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others... _______…

subzero Super moderator Fellow · 3,954 posts #12

You cant put/sql or get user sid or get there info my members are safe 🙂

also it all done with function

lol

Visit: Chat4u.mobi - The New Lay Of being a site of your dreams! Visit: WapMasterz Coming Back Soon!


SCRIPTS FOR SALE BY SUBZERO Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders. FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others... _______…

ozziemale31 Lead · 861 posts #13

to protect your file share folders from php pages being uploaded make a htaccess page and put in it the following

IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti*

<Limit GET POST>
order deny,allow
deny from all
allow from all
</Limit>

<Limit PUT DELETE>
order deny,allow
deny from all
</Limit>

<Files images>
deny from all
</Files>

<Files *.php>
deny from all
</Files>

<Files *.php.*>
deny from all
</Files>

<Files *.php.php.*>
deny from all
</Files>

when a php page is uploaded in that directory and the hacker goes to open it they end up with a nice 403 error page not found even though their script to hack may be there lol thanks to gum for that lil trick

External image (may be gone) External image (may be gone)

External image (may be gone)

*****

**Dont Ask Me Dumb Questions.Or you'l get a Dumb Answer.. Want A Profesional Logo or Theme For Your wap site Pm Me.If I Have The Time Ill Make It For Free ***

ori Lead · 512 posts #14

i use

function get_var($var)
{
$myvar=$_REQUEST["$var"];
if(is_array($myvar))$var=$myvar[0];
else $var=htmlspecialchars(trim($_REQUEST["$var"]),ENT_QUOTES);
return $var;
}

for data posted to mysql or to a string that way when data is called it wont be passed for special characters again as this would cause probs lol

kiss Senior · 294 posts #15

sweetangel wrote:

//protect against sql injections and remove $ sign
if( !get_magic_quotes_gpc() )
{
    if( is_array($_GET) )
    {
        while( list($k, $v) = each($_GET) )
        {
            if( is_array($_GET[$k]) )
            {
                while( list($k2, $v2) = each($_GET[$k]) )
                {
                    $_GET[$k][$k2] = addslashes($v2);
                }
                @reset($_GET[$k]);
            }
            else
            {
                $_GET[$k] = addslashes($v);
            }
        }
        @reset($_GET);
    }

    if( is_array($_POST) )
    {
        while( list($k, $v) = each($_POST) )
        {
            if( is_array($_POST[$k]) )
            {
                while( list($k2, $v2) = each($_POST[$k]) )
                {
                    $_POST[$k][$k2] = addslashes($v2);
                }
                @reset($_POST[$k]);
            }
            else
            {
                $_POST[$k] = addslashes($v);
            }
        }
        @reset($_POST);
    }
}

this is 1 code found ;)

or how about:

<?php
if (get_magic_quotes_gpc()) 
{
	$in = array(&$_GET, &$_POST, &$_COOKIE);
	while (list($k,$v) = each($in)) 
	{
		foreach ($v as $key => $val) 
		{
			if (!is_array($val)) 
			{
				$in[$k][$key] = stripslashes($val);
				continue;
			}
			$in[] =& $in[$k][$key];
		}
	}
	unset($in);
}
?>

www.inbuzunar.mobi -Your mobile portal pocket

spiderwebs Developer · 193 posts #17

I Uses this when i used to use lavalair

ini_set("display_errors", "0");
if(!get_magic_quotes_gpc())
{
$_GET = array_map('trim', $_GET);
$_POST = array_map('trim', $_POST);
$_COOKIE = array_map('trim', $_COOKIE);

$_GET = array_map('addslashes', $_GET);
$_POST = array_map('addslashes', $_POST);
$_COOKIE = array_map('addslashes', $_COOKIE);
} 

E107 Security Team Leader Proudly Support AccountLab Plus Billing Software

Want your Apps to be Developed ??? mail us your requirement at info@csarlab.com

cedwap Developer · 64 posts #18

where to put that?

PROUD TO BE PINOY! just PM me if you have questions about installing/coding script...feel free to PM me if your asking to be your coder....i want helping others so i decided to be a personal coder without asking asking for an exchange...PM now..

Pablo Developer · 164 posts #20

yes it is in core.php

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close