Archive for July, 2007

543Chapter 29SecurityFirst, we need to decide what we (Web design company)

Friday, July 27th, 2007

543Chapter 29SecurityFirst, we need to decide what we are going to do with the uploaded file. In this case, let s planon writing it back out to disk somewhere in our Web tree, so that visitors can access it: cd mkdir uploadschmod 766 uploadsThe first thing we ve done is to make sure we are in the root of our Web document directory. Next, we ve created a directory to hold uploaded files. There s nothing magical about thename we ve chosen for this directory you can name it free_beerif you like, although thatmight be slightly less meaningful in your finished implementation. The last bit is the scarypart. With permissions defined above, we ve made the directory world writeable. In somecases, the directory may also need to be executable, but you should try to get away withthese more minimal permissions first. (Of course, these are Unix-specific commands. Windowsusers will typically have an easier time of it using the graphical tools that OS provides.) Next, we need a proper form. A form that handles file uploads is not much different from aregular form, but the requirements of its design are somewhat more stringent:

Select a file:

The first thing you ll notice here is the enctypeattribute to the form tag. Other values forenctypeare available, but the default browser interpretation, application/x-www-form- urlencoded, will generally serve for most purposes. Not so with file uploads, however. Youmust specify the enctypeexactly as shown above or the browser will not send the data in a format that PHP understands. Skip down to line 3, to the input type of file. This may be anew item to you. It creates in the form field that looks much like a text input box, but with theaddition of a Browsebutton that ideally launches the default file browsing implementation forthe client system. Finally, we ve added a hidden field with the reserved name MAX_FILE_SIZE. This is a cue to the browser that it should check the file size against a maximum of 50000bytes and advise the user accordingly. This is primarily done as a convenience to the user. Itis not universally supported and is easily circumvented, so don t rely on it to enforce your filesize limits. You can, however, rely on PHP to enforce your limits in this regard. PHP provides bothphp.inifile settings and some coding techniques to do this. You should avail yourself ofboth. As the php.inifile settings provide a reasonable fallback, let s start by reviewingthose. The first setting should be obvious: file_uploads = OnThe next relevant setting is: upload_tmp_dir = This is typically left unassigned, which results in a default appropriate for your system. Thisis not where the final uploaded file will resideThis isgenerally the best choice, so unless youhave a really compelling reason to set this to something else, leave it alone. The next setting is where we enforce a maximum file size. upload_max_filesize = 2M33

Web server logs - 542Part IIIAdvanced Features and Techniques&& ($_POST[pass] == $password_we_expected))

Thursday, July 26th, 2007

542Part IIIAdvanced Features and Techniques&& ($_POST[pass] == $password_we_expected)) $registered user = 1; } } if ($registered_user) { // Here are those names and addresses the cracker is after} Now our script expects the referring url to a very specific page on our site, which we accom- plish by comparing the information supplied by the browser with the source form we knowwe created. All by itself, this doesn t constitute a solution to our problem. HTTP_REFERERisn t always sent by the browser or registered by the server; and like the other componentsof an http request header, can be forged in some cases. But remember, while our idealizedgoal here is to make the cracker s work impossible, we can never really fully achieve that. TheInternet is littered with the bodies of those who thought they could. We can, however, addlayers to our armor, making the malicious user s job more and more difficult, and hopefullysend him off in search of an easier mark. Our final change doesn t involve a modification to the script at all. We ll simply change thesetting of register_globals(and restart the Web server). We ve already made it difficult forthe user to send bad values for the information we expect to be user data. Now we ve pro- tected the values of the other four variables in our script. The variables $registered_user, $user_we_expected, $pass_we_expectedand $our_addressare all protected from outsidemanipulation by this one simple action. Imagine how much easier the cracker s job would beif she could simply alter the expected value rather than trying to guess it. File UploadsAs Web designers and application developers, we tend to think of the ability to upload filesvia the Web as a really cool and useful feature. However, with our system administrator hatson, the notion of file uploads is a fairly scary one. Historically, almost all of the major PHPsecurity warnings to date have involved file upload. Witness the fact that this feature is dis- abled by default in the standard php.inifile, and many of the major PHP projects such asPhorum and phpGroupWare, while they support file uploads in some manner, advise extremecaution in its use and allow this feature to be disabled. The fears of the sysadmins are wellgrounded: There is little you can do to put your system at greater risk than employing a poorfile upload implementation. Still, the keyword here is poor. Intuitively, we know the risks associated with file uploading: .Liberal permissions are required on the upload directory. .Executable or other unauthorized files can potentially be uploaded. .Excessively large files can tie up resources and even be used to create a DOS (denial ofservice) condition on your server. .If your Web application sends mails containing the file, your server can easily run into avirus distribution, a most unpleasant mantle you will not enjoy wearing. The good news is, PHP provides several means to address these concerns. Indeed, a fair num- ber of updates to PHP have been released specifically in answer to the problem of secure fileuploads. We ll get to the security issues in a moment; but first, let s get the rudiments of fileuploads out of the way.

Web site domain - 541Chapter 29SecurityIt s important to remember that setting register_globalsto

Thursday, July 26th, 2007

541Chapter 29SecurityIt s important to remember that setting register_globalsto offdoes not prevent an ill- intentioned Web site user from setting variables for himself. It does, however, add anotherlayer of complexity to the cracker s job. It s no longer enough to simply send a variable to theserver; he or she must also know from which environment you expect that variable to come. And with register_globalsset to off, variables evaluated and set exclusively within thereceiving script are not in danger from any suspect request variables. Coupled with some wellthought out code, a potentially hazardous situation can be easily averted. Let s look at aquick example: // Bad example, don t do thisfunction check_user() { if (($user == $user_we_expected) && ($pass == $password_we_expected)) $registered user = 1; } if ($registered_user) { // Here are those names and addresses the cracker is after} The preceding example, written as if register_globalswere turned on, may at least look rea- sonable at first glance. Don t worry about where $user_we_expectedand $pass_we_expectedcome from right now. We ll just assume, for the time being, that these come from some otherfunction such as a database lookup. The first problem is the relatively open use of $userand$pass. These variables can come from anywhere and our script won t ask any questions; itjust dutifully processes these variables regardless of the source. Let s look again at a versionmodified to address this. We still haven t changed the value of register_globals. // Better example, but still needs workfunction check_user() { if (($_POST[user] == $user_we_expected) && ($_POST[pass] == $password_we_expected)) $registered user = 1; } if ($registered_user) { // Here are those names and addresses the cracker is after} So, for the low, low price of just 10 keystrokes, we ve narrowed the sources we will accept fora username and password. A cracker can no longer submit these through a GETargument likehttp://website/script?user=meat&pass=potatoes. These variables will simply expireineffectually at the end of the script execution. Our cracker can still send these variables, buthe is restricted to using a POSTmethod form. That brings us to a couple more issues concern- ing variable origin. A script kiddie could still use a simple form-posting script to rapidly submituser and password combinations in succession. This sort of brute force attack is successfulmore often that you might think, especially where usernames and passwords are poorly chosen. // We re almost therefunction check_user() { if($_SERVER[HTTP_REFERER] == $our address) { if (($_POST[user] == $user_we_expected)

Web site optimization - 540Part IIIAdvanced Features and TechniquesRegister GlobalsThe PHP master

Wednesday, July 25th, 2007

540Part IIIAdvanced Features and TechniquesRegister GlobalsThe PHP master configuration file, php.ini, offers a configuration directive, register_ globals,which controls how PHP recognizes and uses variables passed to it. With the valueof register_globalsset to on, external variables from sources such as forms, cookies, ses- sions, and urls are passed directly to, and used without extra manipulation by, a receivingPHP script. Prior to PHP4.2.0, this was the default setting. While this presents a certain levelof coding convenience and simplicity, it s not such a good idea. The PHP team benevolentlyoffers you the choice of registering globals or not, but they have clearly announced theirintention to remove the option sooner rather than later. What does it mean to register globals exactly? In a larger sense, a global is any variable orconstant that persists outside of the scope in which it is initialized. For example, passing avariable value of socks from a form field named clothes in one script results in the vari- able $clotheswith the value socks being directly available in the processing script. Thisdirect availability is dependent on the registration of these variables as they become available. There are, however, some potential drawbacks, some of them security related, in registeringglobal variables in this way. The first and perhaps most significant possibility is that variables from one source may over- write variables from some other source. Consider, by way of example, the following form:

You can probably see the problem here almost immediately in that $clotheshas been definedtwice, and since it is not an array, the value of clothesdefined in the GET-style ACTIONattribute will be overwritten by the user-entered value POSTed by the form. Potentially moreseriously, if a cookie with that name has been defined, it will overwrite the POSTvariable. Youcan instruct PHP, again via the php.inifile, to evaluate variables in a different order; but thenet effect of that is to simply reorder the problem; not to solve it. It doesn t, for example, allowyou to have two variables of the same name. This issue provides a couple of different avenuesthrough which Web site visitors of malicious intent could set variables for themselves andpossibly slip undesirable data into your applications. However, with the value of register_globalsset to off, a different situation emerges. Insteadof being immediately imported into the global scope, variables are stored in one of a numberof arrays, each named for the environment that supplies it. These associative arrays are: $_GET$_POST$_SESSION$_FILES$_COOKIETheir respective variables are accessed as indices in the array; for example, a POSTform vari- able from the preceding example would be $_POST[clothes]. But because we aren t register- ing globals, we would also have $_GET[clothes]and possibly $_COOKIE[ clothes ], eachwith its own intact values. Whether or not you would actually need to, or even should, namevariables in this way is debatable, but there are other advantages to insuring register_globalsis set to off.

539Chapter 29Securityin such seemingly harmless files as word (Best web design)

Wednesday, July 25th, 2007

539Chapter 29Securityin such seemingly harmless files as word processor documents. Indeed, Microsoft was caughtin this very bind when it inadvertently released a CD-ROM with a Word document containingthe Melissa virus. See the section Site defacement at the beginning of this chapter for other ways that yourvisitor may inadvertently receive malicious code. E-mail safetyE-mail is the least secure of any of the Internet protocols. As it travels to its destination, itmay be spooled on several intermediary servers. If security is weak on a server, it is not diffi- cult for a cracker to read e-mail passing through that server. Send as little critical informationas possible via e-mail. That is, nevere-mail credit card numbers, and try to avoid sendingpasswords via e-mail unless absolutely necessary. It is interesting that most existing sites donot adhere to the latter point. Whenever your site asks for your visitor s e-mail address, it should explain exactly how theaddress is to be used and to whom it is to be released. Whenever an e-mail address is pre- sented on a Web page, it should be modified so as not to be easily identified by automatedsearch engines picking up e-mail addresses to produce spam. The easiest and most elegantway to do this is to replace the @symbol by the word at. Unless absolutely necessary, avoid creating mailto:links. These links are excellent sourcesof spam addresses and are inconvenient for visitors who do not use their Web browser forsending e-mail. Cross- ReferenceSystem administratorsSystem administrators, also called sysadmins, are the folks who make sure the computers we alluse keep on computing and that the Internet keeps on networking. Their jobs are shrouded inmystery: They hold the keys to the mysterious machine room where all the critical servers arestored. It s not unusual to see them hurrying into the office at midnight, surely to avert some cri- sis that could bring the company to its knees. Sysadmins are also a very cautious lot. They tend to program their servers to report any unusualactivity immediately (often to the large-screen alphanumeric pager they carry at all times) and totake swift, decisive action against anything they deem improper or unsafe. A professor in a Computer Science department once asked his students, as homework, to breakinto his Linux desktop. To make things a little easier, he gave the encrypted text of his password(see the description of crypt()in the section Reading arbitrary files ). In a testament to thesecurity of the Unix crypt()function, none of the students cracked his desktop. Several of hisstudents were denied access to their campus accounts, however, and questioned by universityofficials because they were running computationally expensive programs named crack! If you aren t your own system administrator, but you are concerned about the security of yoursite, it is probably a good idea to befriend your local sysadmin. He or she can sometimes suggestways to make your site more secure and can also be an enormous help in recovering from anincident.

538Part IIIAdvanced Features and (Web design) TechniquesPHP has several program

Tuesday, July 24th, 2007

538Part IIIAdvanced Features and TechniquesPHP has several program execution functions: system(), exec(), popen(), passthru(), andthe back-tick (`) operator. As an example of the use of one of these functions, the followingpage returns the Unix fingerinformation for a visitor specified through an HTML form:

Get information on ,

Results for

The program, as given, takes a user name from the HTML form and executes the Unix programfingerto look up information about that user. You should hear Don t trust the networkrepeat- ing loudly in your head. Unix commands are separated by a semicolon, so anything followinga semicolon in the string passed to system()is treated as a new command. This new commandis executed with all the permissions of the user under which the Web server is running. Under Unix, the command rm-rf / will delete all files on the server. Imagine the damage ifan ill-intentioned visitor typed ;rm-rf / into the form and clicked Please. The best solution to this problem is to filter out everything but valid user names beforeinvoking finger. This requires specific knowledge about user name formats on your server, so we do not present an example here. PHP presents a solution that is almost as good. Thefunction escapeshellcmd()will sanitize a string for use in a program execution command, rendering harmless any special characters such as the semicolon. We replace the line invok- ing system()in the preceding code snippet with:

Magically, no value the visitor may enter can result in arbitrary programs being executed. This does not, however, prevent the visitor from providing unexpected input to finger. Although fingerdoes no harm if given incorrect input, other programs may not be so forgiv- ing. If in doubt, err on the side of caution! To minimize the damageof a compromise of this sort, most modern Web servers run as adummy user (often called nobodyon Unix systems). This user has only the permissionsrequired to run the Web server (and any PHP scripts) and read and write the necessary files. But remember, any databases or files that your scripts can modify are modifiable by this user, and thus they are vulnerable if an attacker can run arbitrary programs. Viruses and other e-crittersVisitors trust software coming from a trusted site. If your site allows visitors to download filesuploaded by other visitors, you should warn your visitors to check files for viruses before run- ning them, and you should consider periodically scanning the files on your server for virusesas well. This is a hard problem to solve, particularly with the possibility of embedding viruses33

537Chapter 29SecurityAnd this function (Web hosting directory) will compare a password

Tuesday, July 24th, 2007

537Chapter 29SecurityAnd this function will compare a password given by a visitor with a stored, encrypted password: function verify_pw($given, $stored) { $salt = substr($stored, 0, CRYPT_SALT_LENGTH); $given_encrypted = crypt($given, $salt); return ($stored == $given_encrypted); } See Chapter 44 for a complete example of a user management system that uses the basic prin- ciple of storing and comparing encrypted passwords. Running arbitrary programsIt s every system administrator s worst nightmare. The server s running more slowly thanusual. A look at the running programs on the server reveals that a program entitled crackisburning 98 percent of the processor s time. Most likely, this program has been placed here bya cracker who is using it to decrypt (crack) passwords. The administrator logs in to kill theoffending program but finds that his password is incorrect. His server has been root compro- mised, and there is no telling how much damage has been done. In a compromise such as this, an intruder gains interactive access to the server, usually via aUnix shell or MS-DOS command line. Clearly, this is the most difficult type of heist to pull off, but it also bears the greatest reward. Once insidea server, the cracker has virtually unlimitedpower to bring down the server, steal or modify information, or make use of the server s com- putational power for further wrongdoing. Worse yet, a truly skilled cracker can conceal his orher steps by editing log files and erasing any temporary files he or she has created. Social engineeringSocial engineeringis an often overlooked part of cracking. Sometimes it s easier for crackers toextract information (particularly passwords) from human beings than from computers: Cracker:Hi, John, this is Gary in the IT department. When was the last time you usedyour company account? John:Well, I entered a few new purchase orders about an hour ago. Cracker:Well, John, I m afraid your account has been compromised. Some of the infor- mation in it may have been lost. This could cost the company millions if we don t catchthe intruder quickly. We need to open your account and assess the damage immediately. Can you give me your password? John:Sure, it s . . . Worse yet, sometimes forgetful visitors note their passwords on scraps of paper in their desks! Adetermined cracker can easily find a job as a night janitor and look for such notes. Many famouscrackers were more notable for their social engineering and research skills than their ability towrite code to compromise systems.

Adult web hosting - 536Part IIIAdvanced Features and TechniquesThis is nota good

Tuesday, July 24th, 2007

536Part IIIAdvanced Features and TechniquesThis is nota good solution: The second conditional in this code segment checks for pathname separators in the givenfilename. This program explicitly describes a set of unacceptable inputs and considers anythingelse acceptable. It depends on the programmer imagining and checking for every possibleundesired input. In this case, the programmer has missed something by making the implicitassumption that no sensitive files are stored in the same directory as the script. What if a file that should be private escapes your server anyway? There is a chance that somemisconfiguration (perhaps by someone else) or an unnoticed security hole will render someor all of your server s files publicly accessible. PHP allows you to explicitly specify the set of directories in which files can be opened withthe configuration value open_basedir. See Chapter 30 for more information on the PHP con- figuration file. This configuration value can be useful to prevent access to entire directoriesand is a good way to minimize the damage. Many sensitive files, however, must be opened from PHP programs as visitors access the site. A common example is a password file. Access to such a file cannot be blocked withopen_basedir, but the sensitive information it contains can be encrypted to render it use- less to anyone who may steal it. A password-protected site must verify the password given by a visitor wishing to gain access. One way to do this would be to store a password for safekeeping in encrypted form and thendecrypt it when we need to compare it to the user-supplied password. The problem is that ifwe can decrypt the password, others may be able to decrypt it too. Also, we would have tomake sure that no one could see the password after we decrypted it for comparison. Instead, we can use an encryption function that only goes one way and is easy to use for encryption, but that can t be decrypted. Rather than decrypt a stored password and compare thedecrypted versions, we encrypt the given password and compare the encrypted passwords. Unix uses this strategy with its own password file, /etc/passwd, and PHP allows program- mers to use the same encryption function for their own password files. The function crypt(password, salt)encrypts the given password. The salt adds an extrabit of chance and should be chosen randomly when the password is first recorded. (PHPchooses a random salt if this parameter is omitted.) The function returns the concatenationof the salt value and the encrypted version of the password. The following function will cre- ate a new password for a visitor: function new_pw($given) { return crypt($given) }

Web design careers - 535Chapter 29SecurityReading arbitrary filesA few common PHP programming

Monday, July 23rd, 2007

535Chapter 29SecurityReading arbitrary filesA few common PHP programming mistakes can make it easy for a hacker to read almost anyfile on the server. Study the following page:


Pick a poem:
This simple program displays a number of poems, selectable from a pop-up menu given in the form near the end. Invoke the security mantra: Don t trust the network. Clicking ShowMeonthis page results in URLs such as poetry.php?poem=graves.html. A cracker may substitutethe filename of some more sensitive file, such as poetry.php?poem=/etc/passwd. The pro- gram, as given, would dutifully serve up the Unix password file, possibly enabling the crackerto break into a visitor account and do further damage. The following is an appropriate solution to this problem: The advantage of this method is that it explicitly lists the acceptable inputs and gracefullyhandles unacceptable inputs. If there were more poems to be processed, the switchstate- ment could be replaced with a database query, where failure of the query indicates invalidinput.

534Part IIIAdvanced Features and TechniquesWhen PHP is used (Msn web hosting)

Monday, July 23rd, 2007

534Part IIIAdvanced Features and TechniquesWhen PHP is used as a Web server module, there is little risk of source code being releasedby the Web server, as any file with the proper extension is parsed by the PHP module. If PHPis installed as a CGI program, however, things are not so simple. If you cannot run PHP as a server module, the next most secure setup is to run it as an inter- preter for CGI scripts, just as you would Perl or Python. Place all your PHP programs in the cgi-bindirectory for your server or your account andarrange for the PHP interpreter to be invoked when they are executed. On Unix, this is doneby adding a line similar to the following as the first line of every script: #! /usr/local/bin/phpTo use this setup, you must compile PHP with the –enable-discard-pathconfigurationoption. This setup has the disadvantage that the URLs for most of your pages contain /cgi-bin/. The next most secure setup is a bit more complicated and is actually counter to the recom- mendations of CERT, a respected authority on computer security: We place the PHP inter- preter itself in the cgi-bindirectory. It is usually inadvisable to put an interpreter in thecgi-bindirectory, because the rules for invoking CGI programs would allow any file on theserver to be parsed as a program. PHP is written to operate safely from the cgi-bindirectory, however, if configured correctly. If you intend to use this setup, first carefully read the security and configuration sections ofthe PHP manual, as they may contain important information not available as this book wentto press. This setup relies upon the Web server to redirect URLs of the form: http://your.server/program.phpto URLs of the form: http://your.server/cgi-bin/php/program.phpThe precise directives that will cause your Web server to do this vary. For Apache they are: Action php-script /cgi-bin/phpAddType php-script .phpIf you are using Apache, be sure to compile PHP with the –enable-force-cgi-redirectconfiguration option. This option utilizes a feature specific to Apache to prevent PHP fromexecuting when invoked by URLs of the second form. Your setup is complete. If you are using any other server software, you must compile PHP with the –disable- force-cgi-redirectconfiguration option. PHP cannot distinguish the two types of URLsand serves a document of either type. This allows a visitor to view files without regard forWeb-server based access restrictions. Assume, for example, that the URL www.secrets.com/ top/secret/hush.phphas access restrictions placed on it. A cracker could use the URLwww.secrets.com/cgi-bin/php/top/secret/hush.phpto read the file anyway. In this case, the Web server is giving PHP the path name /top/secret/hush.php. PHP deter- mines the location of the program file by prepending the configuration value doc_rootto thegiven path name. By default, this value is the same as the Web server s document root (thedirectory corresponding to www.secrets.com/). Setting doc_rootto another directory willlimit PHP to programs in that directory and its subdirectories instead of the entire collectionof Web-server documents. Any visitor may access any of the PHP programs by the methodjust described, however, without regard for Web-server-based access controls. Be careful!