473,549 Members | 2,247 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

adding "addslahses " to already live project - best approach?

Having adopted someone else's PHP cope and completing a crash course in the
language I came across a (probably common) problem with the current code.

On a registration form, whenever users names have an apostrophe in them it
causes problems as they do not get added to the DB correctly for reasons
that immediately become apparent.

Before implementing my own workaround I noticed the functions.

addslashes, stripslashes and directive magic_quotes_gp c. These seem like
great ideas and I will now use them.

What is the best way of introducing this practise across all of the code for
this project. It is something I want to progressively, therefore as I make
changes when necessary, I will also add these changes, I do not want to
have to go through the entire code now changing everything.

Can I just do something like the following

On each new script I create do the following.

Check if the magic quotes directive is enabled, and if so do nothing, but if
not, manually run the addslashes function and wherever data is retrieved
from the database go in and add a stripslashes.

Actually I could just make the changes in the code that writes to and
retrieves info from the database rather then on each script that collects
form input. This would therefore lessen the need to make multiple changes to
the code.

Is that all I will need to do. Is there any implications that I am not aware
of by implementing this in a particular way?

Forgive the slight vagueness in this question, I am still surprised to find
this was not done in the start.

Kind regards

Dave
Jul 17 '05 #1
11 2273
Dave Smithz wrote:
On each new script I create do the following.

Check if the magic quotes directive is enabled, and if so do nothing, but if
not, manually run the addslashes function and wherever data is retrieved
from the database go in and add a stripslashes.
You should never have to run stripslashes on data taken _out_ of the
database. If you do, either your data was corrupt going in or you have
the 'magic_quotes_r untime' option on. magic_quotes_ru ntime will corrupt
data unpredictably and you should probably never use it.

In my experience the most reliable thing to do is to always escape data
*exactly when putting it an SQL command*, not earlier. Not all form
input is dumped into raw SQL commands, and not all data destined for SQL
commands comes directly from form input, so magic_quotes_gp c is very
unreliable.

In particular, note that if you process text after it comes from a form
and before putting it into an SQL command, the pre-added slashes may be
corrupted or removed. If you relied on the original slashes to be
present, you may become vulnerable to an SQL injection attack.

What I end up doing is running stripslashes() on all the form input when
magic_quotes_gp c is on, so that data can be passed around within my
program in its proper state, then ensuring that all generated SQL
statement generators escape their arguments.
Actually I could just make the changes in the code that writes to and
retrieves info from the database rather then on each script that collects
form input. This would therefore lessen the need to make multiple changes to
the code.
You should always escape data before inserting it into a raw SQL
statement as a literal value. addslashes() may or may not be correct,
depending on your database; use the appropriate function for your
database (such as mysql_real_esca pe_string). Consider also PEAR::DB's
helper functions which can often perform this step for you.
Is that all I will need to do. Is there any implications that I am not aware
of by implementing this in a particular way?


Some things you don't want to do:
* insufficient escaping -> SQL injection
* processing strings after escaping -> SQL injection
* double escaping -> data corruption
* using SQL-escaped strings in a non-SQL context -> data corruption

-- brion vibber (brion @ pobox.com)
Jul 17 '05 #2

"Dave Smithz" <SPAM FREE WORLD> wrote in message
news:42******** @news1.homechoi ce.co.uk...
Having adopted someone else's PHP cope and completing a crash course in
the
language I came across a (probably common) problem with the current code.

On a registration form, whenever users names have an apostrophe in them it
causes problems as they do not get added to the DB correctly for reasons
that immediately become apparent.

Before implementing my own workaround I noticed the functions.

addslashes, stripslashes and directive magic_quotes_gp c. These seem like
great ideas and I will now use them.

What is the best way of introducing this practise across all of the code
for
this project. It is something I want to progressively, therefore as I make
changes when necessary, I will also add these changes, I do not want to
have to go through the entire code now changing everything.

Can I just do something like the following

On each new script I create do the following.

Check if the magic quotes directive is enabled, and if so do nothing, but
if
not, manually run the addslashes function and wherever data is retrieved
from the database go in and add a stripslashes.

Actually I could just make the changes in the code that writes to and
retrieves info from the database rather then on each script that collects
form input. This would therefore lessen the need to make multiple changes
to
the code.

Is that all I will need to do. Is there any implications that I am not
aware
of by implementing this in a particular way?

Forgive the slight vagueness in this question, I am still surprised to
find
this was not done in the start.

Kind regards

Dave

I agree with Brian but I use the function htmlspecialchar s();
This changes the special chars like quotes ' and " and so on... to HTML
entities .
Eg.
'&' (ampersand) becomes '&amp;'
'"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
http://au2.php.net/htmlspecialchars

Brent Palmer.
Jul 17 '05 #3
I noticed that Message-ID: <42********@new s1.homechoice.c o.uk> from
"Dave Smithz" <SPAM FREE WORLD> contained the following:

<on measures that need to be taken to sanitise data input>

FAQ entry folks?

--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Jul 17 '05 #4
"Dave Smithz" <SPAM FREE WORLD> wrote:
addslashes, stripslashes and directive magic_quotes_gp c. These seem like
great ideas and I will now use them.


Don't. Please use
http://www.php.net/manual/en/functio...ape-string.php or the
database specific function for the database you are using instead. Also,
there is no need to use stripslashes(), ever. Instead, the database will
remove the necessary quotes upon insert, and you will retrieve properly
unquoted data from the database.

On a related note, please check your code for input sanitation. Just like
you encapsulate database access using a database "abstractio n" library, you
should encapsulate all data importing functionality from the user side of
your application and this encapsulation should perform strict sanity
checking on the data. That is, type and range should be enforced ("Is the
supposedly integer variable really containing a number?", "Is the select
input field actually returning a value from the available selection, or
something different?"), and data should be kept locally in your session
once it has been passed through the santiation once. Don't bounce data
using forms and hidden variables.

Kristian

Jul 17 '05 #5
Brent Palmer wrote:
I agree with Brian but I use the function htmlspecialchar s();
This changes the special chars like quotes ' and " and so on... to HTML
entities .
Eg.
'&' (ampersand) becomes '&amp;'
'"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
http://au2.php.net/htmlspecialchars


htmlspecialchar s() is a vital safety tool for putting text data into
HTML output. You should always use this (or htmlentities() or a similar
transformation) when outputting data to HTML to prevent JavaScript
injection attacks.

I hope you're not using it for constructing SQL statements, though.
Since it will pass other special characters such as the backslash, it
may be possible to create SQL injection attacks unless something else
protects against it.

For instance a query like:
SELECT field1,field2 FROM privatedata WHERE
username='O'Con nor' and year='2005'

could be used to return data from all rows in the table by turning it into:
SELECT field1,field2 FROM privatedata WHERE
username='\' AND year=' OR 1=1 /*'

-- brion vibber (brion @ pobox.com)
Jul 17 '05 #6
Geoff Berrow <bl******@ckdog .co.uk> wrote:
<on measures that need to be taken to sanitise data input>

FAQ entry folks?

Q. I'm getting extra \ in my form field
A. You are using Get/Post/Cookie (GPC) data without stripping the
magically [1] added quotes (which are on by default).
If aren't getting the data from GPC magic_quotes_ru ntime might be
on (off by default)

Q. When to escape?
A. Only use the right escape method at the moment it is needed.
What the right escape method actually is depends on where the data
will be used. If you are inserting the string $bar into eg mysql
you should escape it with mysql_real_esca pe_string() [2]
$query="UPDATE foo SET bar='".mysql_re al_escape_strin g($bar)."'";
the same base shoule be htmlescaped [3] when used in html
echo "<a href='foo.php?b ar=".urlencode( $bar)."'>".html specialchars($b ar,ENT_QUOTES). "</a>";
(also note that $bar needs to be urlescaped [4] if used in an URL)
So in oorder to make this work you should always keep the raw
unescaped values (this is why (IMHO) magic_quotes is evil). To make
sure you are actually working with the raw values you should sanitize
GPC data with something like this (untested and incomplete code):
function slashed($t)
{
if(get_magic_qu otes_gpc())
{
if(is_array($t) && count($t))
for($i=0;$i<cou nt($t);$i++)
$t[$i]=slashed($t[$i]);
else
$t=stripslashes ($t);
}
return $t;
}
$_GET=slashed($ _GET);
$_POST=slashed( $_POST);
$_REQUEST=slash ed($_REQUEST);
$_COOKIE=slashe d($_COOKIE);

Q. When and how to sanitize data
A. Like escaping it depends on usage. If know data in a sql row should
be an int, you could do something like this:
$query="UPDATE foo SET bar='".((int)$b ar)."'";
If the data should contain a dutch style postalcode:
if(!preg_match( "/^\d{4}\s*[A-Za-z]{2}$/",trim($zip ))
die("error in zip");
But IMHO you shouldn't try to fix obviously wrong data.

[1] http://nl2.php.net/manual/en/security.magicquotes.php
[2] http://nl2.php.net/manual/en/functio...ape-string.php
[3] http://nl2.php.net/manual/en/functio...ecialchars.php
[4] http://nl2.php.net/manual/en/function.urlencode.php
Jul 17 '05 #7
Brion Vibber wrote:
<snip>
I hope you're not using it for constructing SQL statements, though.
Since it will pass other special characters such as the backslash, it may be possible to create SQL injection attacks unless something else protects against it.

For instance a query like:
SELECT field1,field2 FROM privatedata WHERE
username='O'Con nor' and year='2005'

could be used to return data from all rows in the table by turning it into: SELECT field1,field2 FROM privatedata WHERE
username='\' AND year=' OR 1=1 /*'


Just curious, what's your suggestion to avoid this last case you
mentioned? Are you hinting to use
addslashes(html specialchars($_ POST['foo']))?

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/

Jul 17 '05 #8
R. Rajesh Jeba Anbiah wrote:
Brion Vibber wrote:
SELECT field1,field2 FROM privatedata WHERE
username='\' AND year=' OR 1=1 /*'


Just curious, what's your suggestion to avoid this last case you
mentioned? Are you hinting to use
addslashes(html specialchars($_ POST['foo']))?


Running htmlspecialchar s() on material being put into a database seems
pretty odd to begin with; normally I'd expect to see that done on output.

Just use the correct escaping function for your database, such as
mysql_real_esca pe_string() or PEAR::DB's escapeSimple() method.
addslashes() may often work, but isn't guaranteed to be correct
depending on your database. htmlspecialchar s() is never correct for this
purpose.

-- brion vibber (brion @ pobox.com)
Jul 17 '05 #9
"Kristian Köhntopp" <kr**@koehntopp .de> wrote in message
news:d1m74k$8rp $1@xn--abcdefghijklmno pqrstuvwxyzss-
Don't. Please use
http://www.php.net/manual/en/functio...ape-string.php or the
database specific function for the database you are using instead. Also,
there is no need to use stripslashes(), ever. Instead, the database will
remove the necessary quotes upon insert, and you will retrieve properly
unquoted data from the database.

On a related note, please check your code for input sanitation. Just like
you encapsulate database access using a database "abstractio n" library, you should encapsulate all data importing functionality from the user side of
your application and this encapsulation should perform strict sanity
checking on the data. That is, type and range should be enforced ("Is the
supposedly integer variable really containing a number?", "Is the select
input field actually returning a value from the available selection, or
something different?"), and data should be kept locally in your session
once it has been passed through the santiation once. Don't bounce data
using forms and hidden variables.

Kristian

Ok thank you for all the replies. Coming back to this topic after a little
break and I am confused. I have read your postings and am now not sure what
I should be doing. Now I originally was reading "PHP and MYSQL Web
development" by Welling and Thomas and they introduced to me sTripslashed
etc. They seem to encourage their use and I thought it looked great.

However on posting here I'm very confused. I get the impression that the way
I use this stuff should depend on what I am doing with a particular field.
But in practise this does not help.
The coding I am doing does not leave me as much time as I would like to have
the ultimate security. What I therefore need is a method that I can safely
apply to each field as the most secure measure. I kind of brute force
security approach so that if under pressure another person comes along at a
later time and adds a new field, there is a generic security filtering
applied to each field to prevent any attacks.

What is the best way of achieving this type of security. Is there not just
some standard agreed recommended practise?

Kind regards

Dave
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1851
by: Paul | last post by:
Hi. Just trying to find out the best approach as I beleive it might give me problems later on down the road. I have an ASP.NET application which references a shared database class which contains methods for serialising and de-serialising objects to the database storage. I put this as a shared class as multiple web clients will be using...
10
2781
by: DaveDiego | last post by:
I've had a user delete one of the client records, I do have a version of the DB with all records intact before the deletion occured. Whats the best approach to getting all the related records in each of the tables? I have about 12 tables to put data back into and multiple records for each. Would I need to make an append or update query for...
0
1275
by: Carl | last post by:
Hi, I am trying to figure out the best approach for this simple scenario. I have one C# Windows application Form that consumes few web services for all data related function. In this form I do have few fields bind to the dataset DS , return from the WEB service.
9
3490
by: Anders Borum | last post by:
Hello! I have a class that needs to validate the input value, when a programmer changes a specific property on a class. The input should only accept the following pattern {1,n} (alpha-numeric with atleast one entry). I'm a little resistant to implementing a regular expression validation, because of the overhead involved (not because I...
4
4079
by: Greg Linwood | last post by:
I am wondering what the best approach to binding XML data to an asp:Table from the Page_Load event in a code behind module? I'm using VB.Net and initially approached this by adding a table to the web page from the VS2003 ASP page designer, extracting an XML document from SQL Server during Page_Load, then adding asp:TableRows & asp:TableCells...
1
1580
by: milesm | last post by:
I've spent the last 3 hours reading various MSDN articles, other site articles and news group postings and was wondering what the best approach to my situation would be since I'm unable to come up with the best approach. What's Needed........ 1. Various background SQL inserts that don't interrupt the client request/response 2. Various...
4
1404
by: David Pinx | last post by:
Greetings, I will be developing an application that will have two versions, a web application to be deployed at the client side and a windows application. The question is, what would be the best approach for developing these two versions reusing code as much as possible?. Is there a best practice for this type of development? I have...
5
1387
by: gw7rib | last post by:
I'm writing a program which has "notes" - these can appear on the screen as windows with text in. It is possible to create an "index note" - at present, this will contain a list of the titles (or other data, you can choose) of some or all of the notes - you can choose the selection criteria. Thus you can create notes to store any text you...
0
7548
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7986
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7504
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6074
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5114
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3518
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1083
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.