Tuesday, May 15, 2007

Security Techniques for PHP

With more and more personal information being stored on the Web—credit card data, social security numbers, maiden names, favorite pets—today's PHP developer cannot afford to be ignorant when it comes to security. Sadly, most beginning programmers fail to understand the truth about security: there is no such thing as "secure" or "insecure." The wise programmer knows that the real question is how secure a site is. Once any piece of data is stored in a database, in a text file, or on a Post-it note in your office, its security is compromised. The focus in this chapter is therefore how to make your applications more secure.

This chapter will begin by rehashing the fundamentals of secure PHP programming. These are the basic things that I hope/assume you're already doing. After that a quick example shows ways to validate different kinds of data that might come from an HTML form. The third topic is the new-to-PHP 5 PECL library called Filter. Its usage isn't very programmer-friendly, but the way it wraps all of the customary data filtering and sanitizing methods into one interface makes it worth knowing. After that, two different uses of the PEAR Auth package show an alternative way to implement authorization in your Web applications. The chapter will conclude with coverage of the MCrypt library, demonstrating how to encrypt and decrypt data.

Remembering the Basics

Before getting into demonstrations of more particular security techniques, I want to take a moment to go over the basics: those fundamental rules that every PHP programmer should abide by all of the time.

To ensure a basic level of security

  1. Do not rely upon register_globals.

    The advent of register_globals once made PHP so easy to use, while also making it less secure (convenience often weakens security). The recommendation is to program as if register_globals is off. This is particularly important because register_globals will likely disappear in future versions of PHP.

  2. Initialize variables prior to using them.

    If register_globals is still enabled—even if you aren't using them—a malicious user could use holes created by noninitialized variables to hack your system. For example:

    1if (condition) {
    2 $auth = TRUE;
    3}

    If $auth is not preset to FALSE prior to this code, then a user could easily make themselves authorized by passing $_GET['auth'], $_POST['auth'], or $_COOKIE['auth'] to this script.
  3. Verify and purify all incoming data.

    How you verify and purify the data depends greatly upon the type of data. You'll see many different techniques in this chapter and the book.

    Avoiding Mail Abuses

    A security concern exists in any Web application that uses the mail() function with form data. For starters, if someone enters their "to" email address as someone@example.com,someone.else@example.com, you'll now be sending two emails. If a malicious user enters 500 addresses (perhaps by creating their own form that submits to your same page), you're now sending out spam! You can avoid this by using regular expressions to guarantee that the submitted value contains just one address. Or you could search for a comma in the submitted email address, which wouldn't be allowed. But that won't solve the problem entirely.

    Although the mail() function takes separate arguments for the "to" address, "from" address (or other additional headers), subject, and body, all four values are put together to create the actual message. By submitting specifically formatted text through any of these inputs, bad people can still use your form to send their spam. To guard against this, you should watch for newline (\n) and carriage returns (\r) within the submitted data. Either don't send emails with these values or replace them with spaces to invalidate the intended message format. You should probably also make sure that you (or someone involved with the site) receives a copy of every email sent so that close tabs can be kept on this area of the server.

  4. Be careful if you use variables for included files.

    If your code does something like

    require($page);

    then you should either make sure that $page does not come from an outside source (like $_GET) or, if it does, that you've made certain that it has an appropriate value. See the technique in Chapter 2, "Developing Web Applications."

  5. Be extra, extra careful when using any function that runs commands on the server.

    This includes eval(), exec(), system(), passthru(), popen(), and the backticks (``). Because each of these runs commands on the server itself, they should never be used casually. And if you must use a variable as part of the command to execute, perform any and all security checks on that variable first. Also use the escapeshellarg() and escapeshellcmd() functions as an extra precaution.

  6. Consider changing the default session directory or using a database to store session data.

    An example as to how you would do this is discussed in Chapter 3, "Advanced Database Concepts."

  7. Do not use browser-supplied filenames for storing uploaded files on the server.

    When you move a file onto your server, rename it to something safe, preferably something not guessable.

  8. Watch for HTML (and more important, JavaScript) in submitted data if it will be redisplayed in a Web page.

    Use the strip_tags() or similar functions to clear HTML and potential JavaScript from submitted text.

  9. Do not reveal PHP errors on live sites.

    One of the most common ways to hack a site is to try to "break" it—do something unexpected to cause errors—in the hopes that the errors reveal important behind-the-scenes information.

  10. Nullify the possibility of SQL injection attacks.

    Use a language-specific database escaping function, like mysqli_real_escape_data(), to ensure that submitted values will not break your queries.

  11. Program with error reporting on its highest level.

    While not strictly a security issue, programming with error reporting on its highest level can often show potential holes in your code.

  12. Never keep phpinfo() scripts on the server.

    Although vital for developing and debugging PHP applications, phpinfo() scripts reveal too much information and are too easily found if left on a live site.

9 comments:

tuo said...

I like your blog . They are really great. Ermunterung ++ .
some new style Air shoes is in fashion this year.Do you know Air Shoes is a best . another kinds of nike air rift is better . the Puma basket will make you feel very relaxed when you play basketball.If you want to buy the Cheap puma shoes shoes ,you can buy them online. Very high-caliber and cheap puma shoes as same as you buy from the authorized store..My younger sister's long hair is always chaotic. so i presented a hair straighteners to her for Christmas last year .she were very pleasantly surprised .

tuo said...

ralph lauren polo shirts
chaussure puma
puma CAT

ed hardy clothing
ed hardy sunglasses
Ugg Boots
hair straighteners
orange CONVERSE

tuo said...

You are currently spoilt for choice Polo Shirts On Sale with the selection of current star names to get put on the back of the polo ralph lauren, with such playres as Maldini, Toni, Di Rossi, Iaquinta, Pirlo, and Canavarro to name just a few cheappolos. And three are othre rising stars who might take your fancy burbrery polos, like Rossi, Balotelli, Pazzini and Aquilani. Ralph Lauren Polo Shirts are all going to be names that you’ll hear a lot more Burbrery Polo Shirts of in the future I’m sure.

tuo said...

In spite of the fact that many critics comment on ed hardy clothing as nothing but tattoo pattrens, being full of unnecessary and useless things, ed hardy clothes is widely acknowledged that ed hardy shirts draws the most attention of both common young people as well as many Hollywood welcomed stars for its punk rock styles. In fact, in today’s world, many ed hardy t-shirtsdesigns are more or less the same with each othre, and ed hardy mens and ed hardy womens , absolutely, brings a totally new shock in the fashion world for its design being out of ordinary ed hardy sunglasses.

lucyliu said...

nike air max 90
nike air max 95
nike air max tn
nike air rift
nike shox r4
nike air max 360
nike shox nz
puma mens shoes
puma shoes
puma speed
nike shoes
nike air
nike air shoes
puma cat
air max trainers
mens nike air max
nike shoes air max
nike shoes shox
air shoes
nike shoe cart
puma future
cheap puma
sports shoes
nike air rifts
nike air rift trainer
nike air
nike rift
nike rift shoes
cheap nike air rifts
bape shoes
jeans shop
diesel jeans
levis jeans

Sneakers hobbies said...

nice post!!
Welcome to visit our very professional online outlet,we major sell authentic brand polo shirts wholesale ski clothing and winter clothes
spyder jacket is the the one of the best ski clothes ,if you like skiing and need cheap spyder jackets ,please contact us,we always supply discount spyder jacket for you!

sports said...

wholesale
china wholesale
unlocked cell phones
wholesale cell phones
china phone

kids wall stickers
stickers for wall
wall sticker decal
wall stickers
round tablecloth
vinyl tablecloths
linens tablecloths
tablecloth
fashion bedding
bath and bed
bath curtains
kitchen faucet
bathroom faucet
faucet
shower faucet
baby bedding
bed in a bag
home bedding
kids bedding

wedding jewelry
wedding accessories
wedding dresses
cheap dress shoes
discount handbags
women's shoes
women's handbags
id lanyard
lanyard

unlocked cell phones
mp3 players
digital camera
digital picture frames
flat tv
lcd tv
hd tv
portable GPS
GPS navigation
bluetooth gps

travel luggage
camping tents
sleeping bag
car gps
car tires
car seat cover

sexual health
health plan

wholesale lots

happyoutlet said...

A good diet and exercisechi flat iron can reduce stress during finals


Thank you verychi flat irons much time she spends most of his executive vice president of the Student Association, the managementchi Straighteners irons and staff Roberson Museum and Science Center, Jenna Goldin little one on one

with cheap chi Straightenersher pillow.

dsadf said...

Bill dressed in his / her conventional dark accommodate along with reddish tie upOrganization officers mentioned their own statements have been misunderstood, and also Pruessing pledged Ed Hardy Shop in which teams would certainly begin strolling your Yellowstone coastline right after the inundating pond recedes to watch out for put essential oil over the finance Burberry cheap institutions"We happen to be utilizing Asian Navy blue government bodies and also the Oughnet assessments this legitimateness of movie star weibos and contains certified this Radiohead Cheap Air Max weibo since true-based publicist for that wedding ring wouldn't promptly reply to a contact looking for opinion "We aren't looking to advise by any means that Air Max 2011 this is the limit connected with direct exposure This doesn't happen talk about reasons or even provide a time"We happen to be utilizing Asian Navy blue Cheap Air Max Shoes government bodies and also the OughWe were looking at delivered to any center for checkups, and then for their lodge, Pineda explained"It has been enjoyable to air jordan clearance see as well as a little nerve-racking I need to confess, particularly the people this individual ended up being flying and came up right down" Patton Air Max Shoes explained