473,386 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

PHP Security

I am developing an online application and the last thing I need to get
a handle on is security.
This app is very heavy with forms. Business critical data will be
entered via forms and inserted in to a database (mysql).

I've google "php security" and from what I've read, I should:

1) Filter all form data by stripping all non-alpha/numeric characters
out,

2) Have the database on a different server,

3) Use "POST" not "GET",

4) Turn global variables off.

5) Use sessions for logins

Should this do it? Or do I need more precautions?
Even with all this can I still get hacked?

Thanks

bob

Nov 3 '05 #1
29 2952
rj***********@gmail.com wrote:
I am developing an online application and the last thing I need to get
a handle on is security.
Not that I'm an expert, but you have this backwards. Security should be
the FIRST, not last, thing you thing about.

Your application's security is already doomed to be on the defensive: it's
**much** harder to plug holes than it is to bulid walls. The only way to
correct this is to re-write the whole thing from scratch.

This is a truism: it's true of any language, not just PHP.

This app is very heavy with forms. Business critical data will be
entered via forms and inserted in to a database (mysql).

I've google "php security" and from what I've read, I should:

1) Filter all form data by stripping all non-alpha/numeric characters
out,

2) Have the database on a different server,

3) Use "POST" not "GET",

4) Turn global variables off.

5) Use sessions for logins

Should this do it? Or do I need more precautions?
Oh, god yes.

You need to validate any user input that's destined to the DB for starters.
That alone, when done well, should make your timecard shake in its shoes.

How solid is your application against changes in the database? Do you check
the return of every query? There's *hundreds* of precautions you can take.

Any web scripting language is convenient (although some are more convenient
than others). But they give you a LOT of rope to hang yourself with.
Even with all this can I still get hacked?


Bob, no offense, but it sounds like you really need to learn a lot more about
PHP *and* security in general if you want to write applications that claim to
be secure. No question is a bad question, but some questions signal that the
asker needs to go back to the books.

Yes. Absolutely, you can get hacked. Even if you do everything correct, and
it sounds like you already have an insecure application on your hands, you
can get hacked.

Hackers can be *very* smart folk.
Nov 3 '05 #2
Security is the last thing I need to get a handle on BEFORE I start.

I have not started yet, and I won't until I am confident the app is
reasonably secure and that I have tried and true methods to recover
after I am hacked.

I won't do this if I can't, I will be handling crictical busines data.

I understand it's a never ending battle, and that no app will ever be
100% secure, and that I will have to monitor it constantly.

But having said that, I have to take reasonable measures, waiting for
perfection is not well, reasonable. Question is what is reasonable?
From the research I've done, mostly via google, the steps I have

outlined appear to be the least that should be done.

To that I will add validation of user input and checking the results on
queries.
(I always check the results on queries, I just didn't mention it).

Without about getting in to specifics there is not much validation of
user input I can do besides stripping out special characters, I won't
be saving zip codes or phone numbers or email address or data that is
highly characterisable.

The books I have seen on the subject appear lacking. Any suggestions
on books?

Nov 3 '05 #3
rj***********@gmail.com wrote:
Security is the last thing I need to get a handle on BEFORE I start.

I have not started yet, and I won't until I am confident the app is
reasonably secure and that I have tried and true methods to recover
after I am hacked.
Ahh, then I apologize. I was under the impression that you had already
written a mission critical app and then wanted to tack on security. Sorry
for the misunderstanding!

I'm sure you can see why I was horrified. ;*)
Without about getting in to specifics there is not much validation of
user input I can do besides stripping out special characters, I won't
be saving zip codes or phone numbers or email address or data that is
highly characterisable.

The books I have seen on the subject appear lacking. Any suggestions
on books?


Everything I know about PHP security and defensive programming I brought with
me from other languages, lurking in this newsgroup, spending a lot of time
reading other peoples' code. I find pouring through well written code,
especially when the programmer is gracious enough to reply to email, is the
best teacher. I'm self taught, unfortunately.

However, there seems to be books a few books specifically on PHP security:

http://www.nerdbooks.com/search.php?...%20security%5D

It's hard to go wrong with ORA, but they've been slipping in quality lately.
I think all that Microsoft technology is rotting their brain. Nevertheless,
the book is published 2005 which is encouraging.

I've thumbed through the "best practices" chapter in the Wiley book. Seems
like a lot of obvious suggestions (like making a big deal about things like
"naming variables correctly".) The little bit I read was well written, but
the book was published 2003

Good luck with your app. I find that input validation requires a lot of
thought. Some people are fast at it. Being excellent at composing regexes
will certainly help!

Pete
Nov 3 '05 #4
rj***********@gmail.com wrote:
I am developing an online application and the last thing I need to get
a handle on is security.
This app is very heavy with forms. Business critical data will be
entered via forms and inserted in to a database (mysql).

I've google "php security" and from what I've read, I should:

1) Filter all form data by stripping all non-alpha/numeric characters
out,

2) Have the database on a different server,

3) Use "POST" not "GET",

4) Turn global variables off.

5) Use sessions for logins

Should this do it? Or do I need more precautions?
Even with all this can I still get hacked?


You should be filtering all input from external sources: user input,
from databases, etc.

You should escape all output before sending it: echo or print
statements, sql queries, etc.

You should be practicing defense in depth which means you have redundant
safegards in place just in case something gets through.

I'd suggest reading "Essential PHP Security" by Chris Shiflett (O'Reilly
ISBN 0-596-00656-X) as well as reading articles on his blog
(shiflett.org) and probably read through the articles on the PHP
Security consortium website (phpsec.org)

If you're application is already written, you have a large job ahead of
you. My suggestion is to do some reading as outlined above and start the
application from scratch. It's really the best way - and in many cases
the least time-consuming way as well.

--
Justin Koivisto, ZCE - ju****@koivi.com
http://koivi.com
Nov 3 '05 #5
Following on from 's message. . .
rj***********@gmail.com wrote:
I am developing an online application and the last thing I need to get
a handle on is security.


Not that I'm an expert, but you have this backwards. Security should be
the FIRST, not last, thing you thing about.

OK so "If I was you I wouldn't start from here!" is the correct answer
but not all that helpful.

Get the following security issues clear
- Threat
- Protection
- Detection
- Damage limitation
for all the system components
- Physical environment
- OS
- Apache(etc)
- PHP
- SQL - general
- mySql - particular
- other tools

Nobody (except perhaps GLB) knows all the answers. Each component has
spawned many books, articles, much mis-information and confusion.

As far as PHP and mySql are concerned you are looking at the right sort
of thing but need to review how a click on a submit gets to a database
update in the light of common attack modes for SQL and all the possible
ways you can think of of subverting your program logic (Obviously
userid=44 is an open invitation to try userid=45) When you've done it
get somebody else to review it. Your list of items is step 1 out of 5.

You can keep your data on the same machine as the scripts. You need to
understand your OS and Apache security configuration. For many
situations this is simple enough.

Beware when sharing a host.

As I understand it, the really really difficult bit is keeping the
access password to the database secure. There are some articles on the
web about that issue and when you understand those you should have
covered a lot of muddy ground.

--
PETER FOX Not the same since the borehole business dried up
pe******@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.co.uk>
Nov 3 '05 #6
In article <11**********************@g44g2000cwa.googlegroups .com>,
rj***********@gmail.com says...

I am developing an online application and the last thing I need to get
a handle on is security.
This app is very heavy with forms. Business critical data will be
entered via forms and inserted in to a database (mysql).

I've google "php security" and from what I've read, I should:

1) Filter all form data by stripping all non-alpha/numeric characters
out,

2) Have the database on a different server,

3) Use "POST" not "GET",

4) Turn global variables off.

5) Use sessions for logins

Should this do it? Or do I need more precautions?
Even with all this can I still get hacked?

Thanks

bob


Some folks use a web form to have it email them results a visitor submitted.
Always check all the fields being submitted for tricks lie "\nBcc: the world" in
case some one tries to hijack your web page as a vehicle for spam. My two cents.

Marty
--
Basic Newsguy - 3 GB / month - $39.95 / year
http://newsguy.com/overview.htm

Nov 3 '05 #7
rj***********@gmail.com wrote:
: I am developing an online application and the last thing I need to get
: a handle on is security.
: This app is very heavy with forms. Business critical data will be
: entered via forms and inserted in to a database (mysql).

: I've google "php security" and from what I've read, I should:

: 1) Filter all form data by stripping all non-alpha/numeric characters
: out,

Not exactly. You should "validate" every input. That means confirm it
has the data you expect it to have.

You should also make sure the data is correctly "escaped" before being
used. The correct way to do that depends on the situation. Before you
use any input in an SQL query then that database's string escape routine
should be used. Before using the data in an html page then a mysql html
escape function should be used. I mentioned SQL - if possible use bind
variables so the data is not used directly in the query at all (then you
don't have to escape it - the database software does it all for you).

: 2) Have the database on a different server,

It also means that the database is accessible via the network, which may
itself be a security risk itself if you're that concerned about security.

But probably a good idea.

: 3) Use "POST" not "GET",

Things like passwords should be POSTed, so yes.

: 4) Turn global variables off.

Yes.

: 5) Use sessions for logins

Sure.
And what about 6) HTTPS ?
: Should this do it? Or do I need more precautions?
: Even with all this can I still get hacked?

Doing the above is a good idea, but only careful coding and review of all
the things involved in the application can prevent being hacked.
--

This programmer available for rent.
Nov 3 '05 #8
In article <Tf********************@onvoy.com>,
Justin Koivisto <ju****@koivi.com> wrote:
rj***********@gmail.com wrote:
I am developing an online application and the last thing I need to get
a handle on is security.
This app is very heavy with forms. Business critical data will be
entered via forms and inserted in to a database (mysql).

I've google "php security" and from what I've read, I should:

1) Filter all form data by stripping all non-alpha/numeric characters
out,

2) Have the database on a different server,

3) Use "POST" not "GET",

4) Turn global variables off.

5) Use sessions for logins

Should this do it? Or do I need more precautions?
Even with all this can I still get hacked?


You should be filtering all input from external sources: user input,
from databases, etc.

You should escape all output before sending it: echo or print
statements, sql queries, etc.

You should be practicing defense in depth which means you have redundant
safegards in place just in case something gets through.

I'd suggest reading "Essential PHP Security" by Chris Shiflett (O'Reilly
ISBN 0-596-00656-X) as well as reading articles on his blog
(shiflett.org) and probably read through the articles on the PHP
Security consortium website (phpsec.org)

If you're application is already written, you have a large job ahead of
you. My suggestion is to do some reading as outlined above and start the
application from scratch. It's really the best way - and in many cases
the least time-consuming way as well.


Great. He wrote a book. I was going to recommend Chris's web site:

http://shiflett.org/articles

There are articles on each of the items the OP mentioned and full
discussions. If this is a sample of his writing and breadth of
knowledge, I think I'll toddle down to B&N and get his book...

--
DeeDee, don't press that button! DeeDee! NO! Dee...

Nov 3 '05 #9
Michael Vilain wrote:
In article <Tf********************@onvoy.com>,
Justin Koivisto <ju****@koivi.com> wrote:
I'd suggest reading "Essential PHP Security" by Chris Shiflett (O'Reilly
ISBN 0-596-00656-X) as well as reading articles on his blog
(shiflett.org) and probably read through the articles on the PHP
Security consortium website (phpsec.org)


Great. He wrote a book. I was going to recommend Chris's web site:

http://shiflett.org/articles

There are articles on each of the items the OP mentioned and full
discussions. If this is a sample of his writing and breadth of
knowledge, I think I'll toddle down to B&N and get his book...


I'm half way through it now, and so far I like how it's written. To the
point and no clutter or fluff.

--
Justin Koivisto, ZCE - ju****@koivi.com
http://koivi.com
Nov 3 '05 #10
Malcolm Dew-Jones wrote:
rj***********@gmail.com wrote:
Not exactly. You should "validate" every input. That means confirm it
has the data you expect it to have.
I always feel uncomfortable when people mention input validation in
security discussion, as smacks of perimeter defense. Given that the
question of what constitute valid user input is usually dictacted by
the requirements of your application, it's not a good idea to rely on
validation for security purpose. For example, while you might think
that the single quote is unacceptable in a name, the O'Reillys and
O'Conners of this world all say otherwise.

The approach I favor is "security by assertion." Instead of looking for
dangerous data, make the data safe. If the code is expecting a number,
then force it into a number with intval. If a text string will be
inserted into a SQL statement, then escape it--always. The idea is to
be proactive and not reactive. It's easy to know that you're something
right than to know that things cannot go wrong.
: 2) Have the database on a different server,

It also means that the database is accessible via the network, which may
itself be a security risk itself if you're that concerned about security.

But probably a good idea.
It also allows you to keep the database server fully shielded behind a
firewall. The main benefit though I would say is having a second server
as backup, in case one catches on fire or something.
: 4) Turn global variables off.

Yes.


Avoid using global variables in general. It's a bad programming
practice. For configuration info, use either constants or a function.

Nov 4 '05 #11
>> Not exactly. You should "validate" every input. That means confirm it
has the data you expect it to have.
I always feel uncomfortable when people mention input validation in
security discussion, as smacks of perimeter defense.


Sometimes the application is *SUPPOSED* to enforce its own security
requirements, such as not allowing a user to delete posts that aren't
his own. This can be just as important a requirement as avoiding
SQL injection attacks.
Given that the
question of what constitute valid user input is usually dictacted by
the requirements of your application, it's not a good idea to rely on
validation for security purpose. For example, while you might think
that the single quote is unacceptable in a name, the O'Reillys and
O'Conners of this world all say otherwise.

The approach I favor is "security by assertion." Instead of looking for
dangerous data, make the data safe. If the code is expecting a number,
then force it into a number with intval.
I'll strongly disagree with this one. If an input should be a
number, and it's not, you should generate an error message (and
possibly log a tampering attempt), not process the input as though
it were zero or something else. Fixing an over-long string by
chopping it has potential for causing more (security and other)
problems than it fixes. Chances are a numeric input should be
checked against an application-specific range of allowable values
also.

"security by assertion" could be done by insisting that the input
match a given regular expression, and possibly a length check. That
doesn't rule out application-specific checks, such as if it's
supposed to be one of 7 different values, check that it matches one
of them.

Names should be validated for acceptable characters also.
There may be plenty of room for being too restrictive here, but you
should still check against a list of known acceptable characters,
not against a list of known unacceptable ones (backspace, carriage
return, newline, and most non-printing control characters would be
included here).
If a text string will be
inserted into a SQL statement, then escape it--always.
Ok, I'll go along with that, but it shouldn't eliminate application-specific
checks.

The idea is to
be proactive and not reactive. It's easy to know that you're something
right than to know that things cannot go wrong.


Gordon L. Burditt
Nov 4 '05 #12
Chung Leong (ch***********@hotmail.com) wrote:
: Malcolm Dew-Jones wrote:
: > rj***********@gmail.com wrote:
: > Not exactly. You should "validate" every input. That means confirm it
: > has the data you expect it to have.

: I always feel uncomfortable when people mention input validation in
: security discussion,

Your right. Input validation is not for security. I mentioned it so that
it would be clear I was talking about two different steps for input data,
i.e. validating (one step, quoted above) and making the data safe by
escaping it (another step, not quoted above).
:as smacks of perimeter defense. Given that the
: question of what constitute valid user input is usually dictacted by
: the requirements of your application, it's not a good idea to rely on
: validation for security purpose. For example, while you might think
: that the single quote is unacceptable in a name, the O'Reillys and
: O'Conners of this world all say otherwise.

: The approach I favor is "security by assertion." Instead of looking for
: dangerous data, make the data safe. If the code is expecting a number,
: then force it into a number with intval.

I don't like to modify the data. What goes in should be exactly what the
user input - if it's valid, or not at all otherwise. Nothing to do with
security.

:If a text string will be
: inserted into a SQL statement, then escape it--always.

Definitely correct, but escaping is not the same as using intval to force
something into a number. Escaping is the mechanism to ensure that the
database (or whatever) sees and stores the original data in its original
format.
:The idea is to
: be proactive and not reactive. It's easy to know that you're something
: right than to know that things cannot go wrong.

: > : 2) Have the database on a different server,
: >
: > It also means that the database is accessible via the network, which may
: > itself be a security risk itself if you're that concerned about security.
: >
: > But probably a good idea.

: It also allows you to keep the database server fully shielded behind a
: firewall. The main benefit though I would say is having a second server
: as backup, in case one catches on fire or something.

: > : 4) Turn global variables off.
: >
: > Yes.

: Avoid using global variables in general. It's a bad programming
: practice. For configuration info, use either constants or a function.

Sure, though I assumed he was actually talking about "register_globals."

--

This programmer available for rent.
Nov 4 '05 #13
Gordon Burditt wrote:
I'll strongly disagree with this one. If an input should be a
number, and it's not, you should generate an error message (and
possibly log a tampering attempt), not process the input as though
it were zero or something else. Fixing an over-long string by
chopping it has potential for causing more (security and other)
problems than it fixes. Chances are a numeric input should be
checked against an application-specific range of allowable values
also.


You misunderstood me. I said you shouldn't rely on validation for
security purpose. I didn't say don't do validation. My point is that
input validation is a functional requirement and not a security
measure. You do it so that you can, as you said, tell the user he did
something wrong. You don't want to rely on it, at the same time, to
protect your code downstream.

Nov 4 '05 #14
Malcolm Dew-Jones wrote:
Definitely correct, but escaping is not the same as using intval to force
something into a number. Escaping is the mechanism to ensure that the
database (or whatever) sees and stores the original data in its original
format.


Well, how else do you safely insert an integer into a SQL statement?
You could escape and put quotes around it, but then you're just asking
the database to cast the number into integer for you. If you leave it
as is then you're placing the burden on your validation and error
handling code to avert SQL injection. I could easily imagine someone
writing something like this: if(preg_match('/[0-9]+/', $pkTable)) { ...
}. Calling intval or floatval is easy enough.

Nov 4 '05 #15
Following on from Chung Leong's message. . .
Gordon Burditt wrote:
I'll strongly disagree with this one. If an input should be a
number, and it's not, you should generate an error message (and
possibly log a tampering attempt), not process the input as though
it were zero or something else. Fixing an over-long string by
chopping it has potential for causing more (security and other)
problems than it fixes. Chances are a numeric input should be
checked against an application-specific range of allowable values
also.


You misunderstood me. I said you shouldn't rely on validation for
security purpose. I didn't say don't do validation. My point is that
input validation is a functional requirement and not a security
measure. You do it so that you can, as you said, tell the user he did
something wrong. You don't want to rely on it, at the same time, to
protect your code downstream.

Input validation is a great asset to security because it simplifies the
inputs that the security has to field. Any typed input is going to have
typing errors or the user has misunderstood what goes where so when
unexpected input arrives it is best _in the first instance_ to deal with
these as an interface matter not as a security issue.

But /then/ there are two matters (One for the programmer one for the
designer) which are 'Is this a bit of bent wire being used to pick the
lock?' and 'Is this key in the right hands?' Neither should be assumed.
I like to weed out ununderstood data as soon as possible and protect
(say) the database as close to the database as possible. In the first
case it is the meaning and structure I'm interested in, in the second
its is the particular threats to (say) sql injection that I'm addressing
and I couldn't care if the (say) string is 1 or 1000 characters long -
just so as it can't do naughty things by accident or design.

Below the raw input validation is logic such as they say they want 5
starters, 5 main courses and 50 sweets - odd! (So how did that happen -
could be a bug or misunderstanding problem rather than malicious.

--
PETER FOX Not the same since the poster business went to the wall
pe******@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.co.uk>
Nov 4 '05 #16
Chung Leong wrote:
Malcolm Dew-Jones wrote:
Definitely correct, but escaping is not the same as using intval to force
something into a number. Escaping is the mechanism to ensure that the
database (or whatever) sees and stores the original data in its original
format.

Well, how else do you safely insert an integer into a SQL statement?
You could escape and put quotes around it, but then you're just asking
the database to cast the number into integer for you. If you leave it
as is then you're placing the burden on your validation and error
handling code to avert SQL injection. I could easily imagine someone
writing something like this: if(preg_match('/[0-9]+/', $pkTable)) { ...
}. Calling intval or floatval is easy enough.


If the incoming value isn't an integer, you don't.

For instance - let's say I want to order 100 widgets. However, in the
quantity column I mistype "1q00", because of my fat fingers. :-)

Your way of forcing it to an int with intval would give me 1 item. The
correct response is to call is_int to determine if it is an integer or
not, and if it isn't, tell me about it.

Calling intval or floatval is incorrect - NEVER change the user's data;
it's either valid or invalid. If the former, process it. If the
latter, return an error message to the user!

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Nov 4 '05 #17
Chung Leong (ch***********@hotmail.com) wrote:
: Malcolm Dew-Jones wrote:
: > Definitely correct, but escaping is not the same as using intval to force
: > something into a number. Escaping is the mechanism to ensure that the
: > database (or whatever) sees and stores the original data in its original
: > format.

: Well, how else do you safely insert an integer into a SQL statement?

insert into Tbl (my_col) values (?)

and then bind the statement to the value.


--

This programmer available for rent.
Nov 4 '05 #18
What is "bind the statement to the value". What is bind?

Nov 4 '05 #19
Jerry Stuckle wrote:

<snip>
Your way of forcing it to an int with intval would give me 1 item. The
correct response is to call is_int to determine if it is an integer or
not, and if it isn't, tell me about it.
No, calling is_int is not the correct response. That is because all data
that is collected from the user is of type string. is_int checks to see
if it of type integer. What you'd really want to do is something like
the following:

if(is_numeric($_POST['num'])){
if (intval($_POST['num']) == $_POST['num']){
$clean['num']=intval($_POST['num']);
}else if (floatval($_POST['num']) == $_POST['num']) {
$clean['num']=floatval($_POST['num']);
}
}else{
// not a number...
}

Calling intval or floatval is incorrect - NEVER change the user's data;
it's either valid or invalid. If the former, process it. If the
latter, return an error message to the user!


Correct, never change the submitted data, but in the case of numbers,
converting the variable type is acceptable if you don't change the
meaning of the submitted data.

--
Justin Koivisto, ZCE - ju****@koivi.com
http://koivi.com
Nov 4 '05 #20
Malcolm Dew-Jones wrote:
Chung Leong (ch***********@hotmail.com) wrote:
: Malcolm Dew-Jones wrote:
: > Definitely correct, but escaping is not the same as using intval to force
: > something into a number. Escaping is the mechanism to ensure that the
: > database (or whatever) sees and stores the original data in its original
: > format.

: Well, how else do you safely insert an integer into a SQL statement?

insert into Tbl (my_col) values (?)

and then bind the statement to the value.


This looks like something specific to a db abstraction layer like
PEAR::DB - I don't believe that RDBMS databases support this on their
own. (At least I haven't come across it yet.)

--
Justin Koivisto, ZCE - ju****@koivi.com
http://koivi.com
Nov 4 '05 #21
rj***********@gmail.com wrote:
: What is "bind the statement to the value". What is bind?

bind variables

oracle examples

http://www.oracle.com/ technology/ pub/ articles/
oracle_php_cookbook/ ullman_bindings.html

mysql via mysqli (look for "bind")

http://ca.php.net/mysqli
mysql without mysqli

<quote>
Andy Hassall
Sep 6, 2:28 pm show options
...
I recommend using the ADOdb library
(http://adodb.sourceforge.net/).
</quote>

Haven't used that myself yet, and I plan on trying it the next time I have
a reason sicne it sounds like a thin wrapper to add this very useful
functionality.

OT: the mysql escape should make anything _safe_, including things that
you hope to be number, so I still don't quite see the need for intval.

# ESCAPE == the mysql function the name of which I may have wrong

$maybe_a_number = ESCAPE($the_input_data);

$sql = "select * from T1 where the_number = $maybe_a_number";

# that should be _safe_, but should also generate an sql error if
# the number is not valid. It will also accept whatever syntax and
# automatic conversions are supported by the database, so if your
# database can handle human readable input like "1,234,456.9", or
# 99,9 (where comma is the decimal point) then
# so can your application.

I'm not sure why it would be bad to allow the database to validate your
input anyway. You will be expecting it to to other validations, such as
"duplicate key", and in something like Oracle, any number of other
database enforced constraints.
--

This programmer available for rent.
Nov 4 '05 #22
Justin Koivisto (ju****@koivi.com) wrote:
: Malcolm Dew-Jones wrote:
: > Chung Leong (ch***********@hotmail.com) wrote:
: > : Malcolm Dew-Jones wrote:
: > : > Definitely correct, but escaping is not the same as using intval to force
: > : > something into a number. Escaping is the mechanism to ensure that the
: > : > database (or whatever) sees and stores the original data in its original
: > : > format.
: >
: > : Well, how else do you safely insert an integer into a SQL statement?
: >
: > insert into Tbl (my_col) values (?)
: >
: > and then bind the statement to the value.

: This looks like something specific to a db abstraction layer like
: PEAR::DB - I don't believe that RDBMS databases support this on their
: own. (At least I haven't come across it yet.)

Some do support this natively. The cut of point appears to be the cost -
as they say, you sometimes get what you pay for.

According to a google search, a few example databases

Oracle DB2 Interbase Sybase MS-SQL

have bind variables built in (I am familiar with Oracle, it has "always"
had them).
mSQL, MySQL, PostgreSSQL

do not have them built in, but I wonder if the page was old because I
thought that PostgreSSQL did have them (but I don't use it so what do I
know).

Even things like MS Access have built in support for expressions in
statements that could be called bind variables.
--

This programmer available for rent.
Nov 4 '05 #23
Justin Koivisto wrote:
Jerry Stuckle wrote:

<snip>
Your way of forcing it to an int with intval would give me 1 item.
The correct response is to call is_int to determine if it is an
integer or not, and if it isn't, tell me about it.

No, calling is_int is not the correct response. That is because all data
that is collected from the user is of type string. is_int checks to see
if it of type integer. What you'd really want to do is something like
the following:

if(is_numeric($_POST['num'])){
if (intval($_POST['num']) == $_POST['num']){
$clean['num']=intval($_POST['num']);
}else if (floatval($_POST['num']) == $_POST['num']) {
$clean['num']=floatval($_POST['num']);
}
}else{
// not a number...
}

Calling intval or floatval is incorrect - NEVER change the user's
data; it's either valid or invalid. If the former, process it. If
the latter, return an error message to the user!

Correct, never change the submitted data, but in the case of numbers,
converting the variable type is acceptable if you don't change the
meaning of the submitted data.


Justin,

You're right - it should have been is_numeric. And the rest of your
code is great, as well (of course).

Thanks for the correction.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Nov 4 '05 #24
Jerry Stuckle wrote:
If the incoming value isn't an integer, you don't.

For instance - let's say I want to order 100 widgets. However, in the
quantity column I mistype "1q00", because of my fat fingers. :-)


Geez. Either I failed to express myself clearly or people have never
heard of defense in-depth. The existence of a mechanism to stop one
type of SQL injection does not imply that data will necessarily reach
it. You put it there so that the code that interacts with the database
isn't dependent on your validation code for safety. That code should,
of course, keep the user from encountering the odd behavior.

Nov 4 '05 #25
Justin Koivisto wrote:

if(is_numeric($_POST['num'])){
if (intval($_POST['num']) == $_POST['num']){
$clean['num']=intval($_POST['num']);
}else if (floatval($_POST['num']) == $_POST['num']) {
$clean['num']=floatval($_POST['num']);
}
}else{
// not a number...
}


Some things I should have pointed out is that this does not cover all
the different ways of representing numbers...

For instance, if the submitted value was an octal number like "010",
$clean['num'] is 10 rather than 8 as it should.

If "0x10" was submitted, $clean['num'] == NULL rather than 16...

If "1e4" is submitted, $clean['num'] == float(10000)...

--
Justin Koivisto, ZCE - ju****@koivi.com
http://koivi.com
Nov 4 '05 #26
Chung Leong wrote:
Malcolm Dew-Jones wrote:
Definitely correct, but escaping is not the same as using intval to force
something into a number. Escaping is the mechanism to ensure that the
database (or whatever) sees and stores the original data in its original
format.


Well, how else do you safely insert an integer into a SQL statement?
You could escape and put quotes around it, but then you're just asking
the database to cast the number into integer for you. If you leave it
as is then you're placing the burden on your validation and error
handling code to avert SQL injection. I could easily imagine someone
writing something like this: if(preg_match('/[0-9]+/', $pkTable)) { ...
}. Calling intval or floatval is easy enough.


IIRC, MySQL will actually give an error if you to quote a value for an
integer field...

--
Justin Koivisto, ZCE - ju****@koivi.com
http://koivi.com
Nov 4 '05 #27
On Fri, 04 Nov 2005 14:21:21 -0600, Justin Koivisto <ju****@koivi.com> wrote:
IIRC, MySQL will actually give an error if you to quote a value for an
integer field...


mysql> create table t (c int);
Query OK, 0 rows affected (0.05 sec)

mysql> insert into t values ('1');
Query OK, 1 row affected (0.03 sec)

mysql> select * from t;
+------+
| c |
+------+
| 1 |
+------+
1 row in set (0.00 sec)

MySQL still has a nasty habit of mangling data to fit, rather than raising
errors.

mysql> create table t (c varchar(1));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into t values ('clearly too long');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from t;
+------+
| c |
+------+
| c |
+------+
1 row in set (0.00 sec)

OK, it's come up with a "warning" but that's a bit more than a warning. I
believe MySQL 5.0 has an option at last to turn these into errors.
--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Nov 4 '05 #28
Chung Leong wrote:
<snip>
: 4) Turn global variables off.

Yes.


Avoid using global variables in general. It's a bad programming
practice. For configuration info, use either constants or a function.


It is true that constants cannot be tampered. But, I don't get
the idea, how it is a right choice for global scope thing. I also tried
the function, but in my tests, it severely affects the memory.

FWIW, OP may refer Chung's thread on security
<news:iP********************@comcast.com> (
http://groups.google.com/group/comp....a18bc51f0448fc )

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

Nov 7 '05 #29
R. Rajesh Jeba Anbiah wrote:
Chung Leong wrote:
Avoid using global variables in general. It's a bad programming
practice. For configuration info, use either constants or a function.


It is true that constants cannot be tampered. But, I don't get
the idea, how it is a right choice for global scope thing. I also tried
the function, but in my tests, it severely affects the memory.


A lot of vulnerabilities in PHP programs are caused by people using
global variables to store configuration info. If parameter is constant
value, then it should be a constant.

I don't quite understand what you mean by the use of functions
affecting memory. The idea is to use a function to return a parameter
as opposed to storing it in a global variable. What that does is
changing the assumption made by your code. When you use a global
variable to store a configurable parameter, your code assume that the
it was assigned to the proper value at an earlier point in time. When
you call a function, it is assuming the function exists. This latter
assumption is enforced by PHP (or else the script dies) hence it's
safer. In contrast, it's far harder to prove that the former assumption
would hold under all circumstances.

Nov 8 '05 #30

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

Similar topics

2
by: robert | last post by:
well, talk about timely. i'm tasked to implement a security feature, and would rather do so in the database than the application code. the application is generally Oracle, but sometimes DB2. ...
116
by: Mike MacSween | last post by:
S**t for brains strikes again! Why did I do that? When I met the clients and at some point they vaguely asked whether eventually would it be possible to have some people who could read the data...
4
by: Ashish | last post by:
Hi Guys I am getting the following error while implementing authentication using WS-security. "Microsoft.Web.Services2.Security.SecurityFault: The security token could not be authenticated...
0
by: prithvi g via .NET 247 | last post by:
Hi I am a newbie to .NET remoting, I am trying to implementauthorization using SSPI example provided by Michael Barnett. Ihave included the required dll(Microsoft.Samples.Security.SSPI.dll...
1
by: Earl Teigrob | last post by:
Background: When I create a ASP.NET control (User or custom), it often requires security to be set for certain functionality with the control. For example, a news release user control that is...
7
by: Magdelin | last post by:
Hi, My security team thinks allowing communication between the two IIS instances leads to severe security risks. Basically, we want to put our presentation tier on the perimeter network and the...
0
by: Jay C. | last post by:
Jay 3 Jan. 11:38 Optionen anzeigen Newsgroups: microsoft.public.dotnet.framework.webservices.enhancements Von: "Jay" <p.brunm...@nusurf.at> - Nachrichten dieses Autors suchen Datum: 3 Jan...
3
by: Velvet | last post by:
I ran FxCop on one of the components for my web site and the security rules what me to add " tags like the ones listed below: This breaks my ASP.NET application. So my question is,...
1
by: Jeremy S. | last post by:
..NET's code Access Security enables administrators to restrict the types of things that a .NET application can do on a local computer. For example, a ..NET Windows Forms application can be...
2
by: Budhi Saputra Prasetya | last post by:
Hi, I managed to create a Windows Form Control and put it on my ASP .NET page. I have done the suggestion that is provided by modifying the security settings. From the stack trace, I would...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.