Archive for July, 2007

My web site - 553Chapter 29Security .Minimize the damage.Where possible, make sure

Tuesday, July 31st, 2007

553Chapter 29Security .Minimize the damage.Where possible, make sure that the damage possible from a par- ticular type of security breach is minimal. Encrypt sensitive data. If you run your ownWeb server, make sure it is running as a dummy user. .Finally, if you run your own server, spend some time breaking into it. If you re successful, then you ve identified a vulnerability that you can patch before an intruder finds it. Ifyou re unsuccessful, you ve learned something about your server, and your securityprecautions have weathered a good test. If you don t run your server, find out whodoes, and see what he or she can tell you about your site s security. …

Web and email hosting - 552Part IIIAdvanced Features and TechniquesFYI: Security Web SitesIf

Tuesday, July 31st, 2007

552Part IIIAdvanced Features and TechniquesFYI: Security Web SitesIf you are losing sleep after reading this chapter, fear not. Every administrator and site designeraround the world is grappling with the same issues, and there is a strong feeling of solidarityamong computer security professionals. Many Web sites are devoted to computer security, and almost all of them contain full descriptions of recent security incidents and ways to pro- tect your system from duplicate attacks. Some are designed for security professionals, whereasothers have the cracker in mind. Either way, the information they provide is useful and oftenvery interesting. Begin your explorations by checking out these sites: .Computer Emergency Response Team(CERT)(www.cert.org/):CERT is one of themost popular repositories of official descriptions of security incidents. It publishesadvisories on all sorts of security issues, including very clear descriptions of the prob- lem, vulnerable systems, and possible solutions. .Security-focus.com(www.securityfocus.com/):Security-focus.com provides a greatdeal of information on all aspects of computer security, from the legal and political tothe technical. It also hosts the well-known security mailing list, BugTraq (which can befound under Forums). .Rootshell(http://rootshell.com/): Rootshell is a well-respected site that containsfairly technical descriptions of many, many security vulnerabilities, including detaileddescriptions of how to exploit the vulnerability, as well as instructions on removing thevulnerability. .Insecure.Org(http://insecure.org/):Insecure.Org is a fairly well-established sitethat is not afraid to make cracking tools available and to discuss the nitty-gritty detailsof many exploits. This site can be extremely useful if you want to try to break intoyour own site. .L0pht Heavy Industries(http://www.l0pht.com/index.html):L0pht is another on-the-edge site, run by people who crack into machines for a living. They are paid todo this in the hopes that they can find a vulnerability before someone with maliciousintent does, and they report what they ve done on this site and others. The site alsocontains lots of interesting opinions on its soapbox. SummaryFor any significant Web site, security is a crucial part of the site s implementation. You shouldtake extreme care to secure your server from attack and also be sure to protect your visitors private information from prying eyes. In a time of enormous growth for online businesses, publication of a story about a major security breach can destroy visitors confidence in yoursite, driving them to the competition and possibly leaving your site to evaporate as quickly asit appeared. In this chapter, we ve driven home three basic lessons: .Don t trust the network.Every byte of data that comes from the Internet should betreated as potentially hazardous. Be as restrictive as possible in defining the inputs youallow. Prefer the solution that lists the acceptable inputs to the one that lists the unac- ceptable inputs. Be sure that your Web server configuration does not allow clients toview your source code or to work around your access restrictions.

Remote web server - 551Chapter 29Security$key = get_user_key($username); $encr_hash = mcrypt_cbc(MCRYPT_BLOWFISH, $key,

Tuesday, July 31st, 2007

551Chapter 29Security$key = get_user_key($username); $encr_hash = mcrypt_cbc(MCRYPT_BLOWFISH, $key, $hash, MCRYPT_ENCRYPT); $sfp = fopen($sig); $sig_data = fread($sig, $sig_size); fclose($sfp); if ($encr_hash != $sig_data) echo

Rejected — signature did not match

; else { echo

Accepted

; // Continue handling the uploaded file} } ?> This program parallels the uploader s steps, first hashing the uploaded file and then encrypt- ing the result with the user s key. If the results are the same, the uploader must have used thesame key, and we can assume they are genuine. If the results differ, the upload is a forgery. Secure Sockets LayerThe uses of cryptography presented so far protect the server s data. The single-key encryptionexample protects information the server stores on clients (cookies) from unwanted modifica- tion. The hashing example enables the server to detect forged files and refuse to accept them. We now turn our attention to the security of your site s visitor. The visitor often transmits private information to your site. The visitor s password and credit card information mustsomehow travel from his or her machine to the server, across the untrustworthy network. The Secure Sockets Layer(SSL) protocol provides a way to do this, making it impossible for aneavesdropper to listen in. It also provides a way for the site to prove its identity to the visitorand, optionally, for the visitor to prove its identity to the site. Although we won t delve intothe cryptographic details, SSL does its work by using public-key encryption to prove the iden- tity of the server and to exchange a new key to be used to encrypt the conversation. It thenswitches over to single-key encryption, which is much faster, using this new key. Regardless of how you acquire and license the SSL software, you must purchase a certificatefor your site from a well-known certificate authority.These authorities are the trusted thirdparties in the conversation between your server and a browser, but they do not give awaytheir services for free. It is beyond the scope of this book to make comparisons of competing SSL servers. In the tradition of open source, the authors believe that the free implementations are the best andmost reliable; indeed, many of the commercial SSL servers are based on the open sourceimplementations! If you buy a commercial implementation, however, you receive supportfrom that company, and you satisfy management s desire to pay for something. SSL is outside the scope of the book, since it really is an issue for Web server managementrather than Web scripting. For more information on how to implement SSL on your site, seea good Apache or IIS book such as Apache Server 2 Bible, Second Edition, by Mohammed J. Kabir (Wiley, 2002). Tip33

Personal web server - 550Part IIIAdvanced Features and TechniquesWhat you need is

Monday, July 30th, 2007

550Part IIIAdvanced Features and TechniquesWhat you need is a digital fingerprint for a large file. What if we treat the binary data of thefile as a list of integers, add them all together, then chop off all but 128 bits of the sum? Wecall the final 128-bit number the checksum.The author of the file then encrypts the checksumwith his or her secret key and attaches the result to the file as a signature. Assume a cracker makes modifications to the file. He or she can then calculate the sum Cofthe changes and put the number Cat the end of the file, creating a file that he or she knowsto have the same checksum as the original. The cracker then appends the same encryptedchecksum to the file as its signature. When some unsuspecting user downloads the modified file, the user calculates the new check- sum, decrypts the signature to find the original author s checksum, and sees that they match. The user proceeds to use the modified file, incorrectly assuming that it was written by thestated author. Of course, the cryptographers are right on the spot with a solution. It should be very difficultto make changes to a file to produce a certain fingerprint. To ensure this, many hashingalgo- rithms have been developed. Hashing algorithms are generally modifications of single-keyencryption algorithms to make them create a ciphertext of a specific length, from which it isnot possible to reconstruct the original message. As you would expect, PHP provides a set of functions for hashing. These functions depend on the publicly available mhashlibrary. You can find the latest version of the mhashlibrarythrough a link in the PHP manual. The function mhash(type, input)computes the hash value of input,using the methodspecified by type.Common values for this argument are MCRYPT_MD5and MCRYPT_SHA1. For a complete list of possibilities, see the PHP manual. Digitally signing filesNow let us present a PHP program to accept uploaded files only when they are correctly signed. We assume that our site is equipped with a list of usernames and Blowfish keys, where eachuser has a key known only to that user and our site. The function get_user_key(username) retrieves these keys for us. The uploader generates the signature for an upload by first hash- ing the upload file with the MD5 hashalgorithm and then encrypting the resulting hash valuewith her Blowfishkey.

Upload a file

Upload the file:
With this signature:
For user

Web site design - 549Chapter 29SecurityBut with some help from mcryptand a

Monday, July 30th, 2007

549Chapter 29SecurityBut with some help from mcryptand a few friends, we can make this impossible: mcryptdeals with strings full of binary data, so we can t easily type them or send them tobrowsers without modification. In this case, we have chosen to use the PHP base64functionsto turn them into well-behaved strings. Before writing this program, we invented a DESkeywith the following code: We copied and pasted the resulting key (in base 64 encoding) into our cookie program s firstline. We store the number of visits in the cookie named visits, encrypted and in base 64encoding. So if the visits variable is set, we first base64_decodeit, then decrypt it. We thenincrement the counter, encrypt it, base64_encodeit, and store it in a new cookie. The visitorsees cookie values such as IQ109yQCEgw%3D, which are not editable. The program is not completely secure! The cookie value just given will alwayscorrespond tovisit number 7. A cracker wishing to make your site believe he had visited only seven timescould simply substitute this value for the visitscookie. If you know it would not benefit avisitor to return to a prior cookie (in this case, if the visitor wants a large visit count), how- ever, this method is adequate: There is no way to easily invent a cookie for a state that hasnot been seen yet. To maintain a more useful visitor state, you should use sessions, which are described fully inChapter 24. This example should bring home the need to keep your source code private: If a crackercould view this program from his or her browser, he or she would have your site s encryptionkey and could decrypt your cookie values with ease. HashingSigning a document with your private key produces a signature that is as large as the originaldocument. This becomes a problem when we want to sign long documents such as files. Forinstance, most security software (including mcrypt) is digitally signed so that downloadersknow that the latest version really was written by the author. Otherwise, sysadmins worry, an eager cracker could circulate a version of a security program into which he or she hasinstalled a back door and then walk into the systems running that version with no difficulty. Cross- Reference33

548Part IIIAdvanced Features and Techniquesyou wish to encrypt (Web design online)

Sunday, July 29th, 2007

548Part IIIAdvanced Features and Techniquesyou wish to encrypt or decrypt in the keyand dataarguments, respectively. To encrypt, passMCRYPT_ENCRYPTin the directionargument; to decrypt, pass MCRYPT_DECRYPT. Finally, forcipher modes that support initialization vectors, pass your own IV in the ivargument. Your key must be of the correct size for your cipher. To find out what this size is, use: mcrypt_get_key_size(cipher) Again, cipheris the cipher you have chosen. To generate a random IV or key, use: mcrypt_create_iv(size, source) Here, sizeis the size of the desired object and sourceis one of MCRYPT_RAND, MCRYPT_DEV_ RANDOM, or MCRYPT_DEV_URANDOM, specifying the random number generator to use: rand(), /dev/random, or /dev/urandom, respectively. If you use rand(), be sure to call srand()toseed the random number generator first. (See Chapter 10 for more information on randomnumbers.) The proper sizes for IVs and keys are obtained by calling mcrypt_get_block_ size(cipher)and mcrypt_get_key_size(cipher), respectively. Note that all data handled by mcryptis in the form of PHP strings of binary data. If you wishto display the data in some human-readable format or store it as a text string, you must applysome translation to it. PHP provides the functions base64_encode()and base64_decode() for just this purpose. Check the PHP manual for more information on these functions. Encrypting cookiesCookies your site sends to a visitor s browser contain information about that visitor. Whenthe browser sends the cookie back, your site uses the information it contains to generate anew page. Don t trust the network sound familiar? A cookie could be modified or forged by amalicious user, perhaps fooling your site somehow. This extremely simple program will serveas an example:

You have been here times

See Chapter 24 for more information on cookies. Here, a count of our visitors visits to this site is kept in the cookie visits. A visitor couldmodify his or her cookie, however, to make the visit count 10,000. Our program would haveno idea that this visitor has not been to the page 10,000 times and would blindly display Youhavebeenhere10000times. Cross- Reference33

Web hosting comparison - 547Chapter 29SecurityThe Unix version of PHP provides a

Sunday, July 29th, 2007

547Chapter 29SecurityThe Unix version of PHP provides a set of functions that implement single-key encryption, using a publicly available library called mcrypt.To use these functions, you must downloadand install mcrypt(there is a link to the library s source available in the PHP manual) andrecompile PHP with the –enable-mcryptconfiguration option. When compiling this version of mcrypt, you must specify the configuration option –disable-posix-threadsduring the mcryptconfiguration. Missing this step causesApache to crash. mcryptoffers a choice between a number of ciphers different single-key algorithms. Eachhas its relative pros and cons in terms of speed and strength. In general, DES and Blowfish are fairly well-known algorithms with a good balance of speed and strength, but if you needextreme speed or great strength, you should research the algorithms available in your imple- mentation (listed in mcrypt.h) and choose the one most suited to your needs. mcryptalso allows you to choose among four cipher modes. These are summarized in Table 29-1. Table 29-1: Cipher Modes Provided by mcryptModeDescriptionInitialization vector (IV) ECB (electronic code book)Just translate the block of data given. noSuitable for small blocks of data that aren t very predictable, such as other keys. Do not use for text: The high frequency of letters and punctuation may be used to break the encryption. CBC (cipher block chaining)This stronger mode is far better optsuited for use with textual data. CFB (cipher feedback)Like ECB, CFB is well suited for short yesblocks of data. OFB (output feedback)OFB is very similar to CFB but designed yesto be better behaved when it encounters errors in its input. The last two modes require an initialization vector (abbreviated IV), which functions as astarting state for the encryption algorithm. The differences between these modes are relevantto interactive use, where individual keystrokes are encrypted one at a time. In that case, it iscrucial that the algorithm not encrypt athe same way each time. The PHP interface to mcryptonly allows us to encrypt strings, however, so any of the modes except ECB are perfectlyacceptable. Depending on the cipher mode you want to use, call mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb(), or mcrypt_ofb()like this: mcrypt_cbc(cipher, key, data, direction, [iv]) where cipheris MCRYPT_DES, MCRYPT_BLOWFISH, or whichever cipher you have chosen. (Seethe PHP documentation for an updated list of supported ciphers.) Pass your key and the dataCaution33

Web hosting bandwidth - 546Part IIIAdvanced Features and TechniquesWe shall call Alice s

Saturday, July 28th, 2007

546Part IIIAdvanced Features and TechniquesWe shall call Alice s keys Paliceand Salice,respectively and, likewise, Bob s keys Pboband Sbob. They publish their public keys in the newspaper but hide their secret keys under their mattresses. Alice has a sensitive message Mfor Bob. With her keys, Alice received a set of instructions fortranslating a message with a key. We write the translation like this: Pbob(M).She translates hermessage with Bob s public key and hands the result to a shady-looking character on a pony. Our friends keys were not chosen arbitrarily. They have the special property that if theytranslate a message with one key, then translate the result with the other, they get the originalmessage back. That is, Salice(Palice(M)) = Palice(Salice(M)) = M.There s no other way to resurrectthe original message. In this case, Bob translates the message he receives, which he knows tobe Pbob(M)with his secret key. Sbob(Pbob(M)) = M,so he can read Alice s original message. Bob knows that nobody else could have read that message, because nobody else has hissecret key. But he does not know that it came from Alice: Anyone who reads the newspapermay have sent that message, signing the name Aliceat the bottom. Now Alice wants to send another message to Bob, and this time she wants no doubt that itwas from her. First, she translates the message with her secret key and writes the result afterher message as a signature:M + Salice(M).She sends this off to Bob, who reads Alice s message, which instructs him to translate the signature with her public key: Palice(Salice(M)) = M,and hesees her message again. Because nobody else has Alice s secret key, she is the only one who could have created thissignature, so this message must have come from her. But note that this time Alice sent hermessage Mto Bob directly. Any rogue could have waylaid the Pony Express and read it. If shehad so desired, she could have first signed the message, then encrypted the message and thesignature using the first method, resulting in a signed, encrypted message. There is a hitch in this scheme. Without meeting Alice, Bob can t be sure that the public key he found in the newspaper is really Alice s key. What if someone else had his or her keyprinted under her name? This could become a real problem if Bob communicates with lots of people he simply doesn t have the time to check keys with each of them face-to-face. Assume that there is at least one person everyone trusts; call him Tom. Tom picks a set ofkeys and offers to sign documents with his secret key, if the owner of the document showsproof of his or her identity. Alice has her public key signed by Tom, and then publishes thesigned key, called a certificate,in the newspaper. Bob checks the signature on the key he seesin the newspaper, using Tom s public key. He knows that Tom signed that message, and Tommust have checked Alice s identification, so the key in the newspaper must really belong toAlice. Single-key encryptionIn single-key encryption, the same key can encrypt and decrypt a message. In general, it runsmuch more quickly than other forms of encryption, but it is more difficult to use for commu- nication because the key must somehow be transmitted from one end to the other without anyeavesdroppers picking it up. This is precisely where public-key encryption can lend a hand. Returning briefly to our characterization, imagine Alice and Bob want to have a private con- versation using single-key encryption. Alice asks Bob for his certificate, which contains hispublic key. She then picks a new single key and encrypts that key with Bob s public key, send- ing the result to Bob. Using his secret key, he decrypts the message to reveal Alice s singlekey and then uses it to begin a single-key encryption conversation.

Ftp web hosting - 545Chapter 29Securitychmod($uploadfile, 0644); print( File upload was successful ); }

Saturday, July 28th, 2007

545Chapter 29Securitychmod($uploadfile, 0644); print( File upload was successful ); } else { print( File upload failed ); } } else { print( Only images are allowed, upload failed ); } What s different about this version, and why is it better? We ve started by working a littlestring and regex magic on our filename. The value of $_FILES[ upfile ][ name ]containsthe literal name of the file as it was on the user s system; but for reasons which should alreadybe apparent, this cannot be trusted. The second line removes any trailing and leading white- space characters. The third line ensures that we have a filename with a manageable length by taking only the last twenty characters. We take these characters from the end because weneed to capture the file extension; but this is an important step because excessively long file- names can create a host of potential problems. The fourth line pulls out any spaces in the filename, as different platforms handle long filenames in different ways, potentially posingadditional problems. The last thing we do before writing out the file is to make sure it s animage. You may wish to allow other types and can adjust the regular expression accordingly. Finally, we change permissions on the written-out file to a minimal set, reducing the risk fromviruses or unwanted executables. There are safer and less safe ways to handle file uploads; but uploading is historically one ofthe most insecure things that PHP allows you to do. Many good Web developers and sysad- mins think that anyone who s willing to let unknown users upload unknown binaries to theirfilesystem is asking for trouble. So before implementation, you need to ask if this is reallywhat you need or want to do, and if you re prepared for all the possible consequences. Onceyou ve made that decision, follow the hints in this section to make things as safe as possible. EncryptionEncryption is the process of encryptingsome message, referred to as plaintext,into unrecog- nizable ciphertext.Without certain information (a keyof some sort), it is extremely hard toreconstruct the plaintext from the ciphertext. Someone equipped with the proper key, how- ever, can easily decryptthe ciphertext, revealing the original plaintext at least, if the chosenencryption function is not one-way. We have already seen one use of encryption in this chapter: Passwords are stored inencrypted form. Password encryption, however, is usually one-way. There is no key todecrypt an encrypted password. Such a key is not needed, and the encryption can be madestronger if it doesn t need to be reversible. Encryption has many other uses in online busi- ness, both for storing data on the server and transmitting it across the network. Public-key encryptionMeet Alice and Bob, professional cryptographic examples. They were chosen by the mathe- matical community, not for their acting talent, but because their names begin with A and B. Alice and Bob want to communicate securely, but their only method of communication is viaPony Express not particularly secure. Each of them selects a public key and a secret key.

544Part IIIAdvanced Features and TechniquesPHP defaults to a (Zeus web server)

Friday, July 27th, 2007

544Part IIIAdvanced Features and TechniquesPHP defaults to a size of 2MB for this parameter, which is probably larger than you will needunder ordinary circumstances. You can set this value as large as you like, but you will have tostrike a balance with the value of max_execution_timewhich will require a duration largeenough to accommodate your largest possible upload from your least well equipped user. For example, a modem user may take six minutes or more to upload a 1MB file. If any of these values seem out of line with the needs of the rest of your PHP installation, they probably are. Greatly increasing the value of max_execution_timeto allow for largeruploads, for example, can make debugging infinite loops and other scripting mishaps diffi- cult. It can also pose a security risk based on scripts that are placed elsewhere on your site. This would be an appropriate place to set these values on a per directory basis using phpflags and .htaccess files as discussed in Chapter 30. The next setting controls the size of HTTP form submissions, which includes file uploads. post_max_size = 8MAgain, the PHP default here is pretty high, but it needs to be big enough to hold the value ofupload_max_filesizeplus a few bytes for any form data that may accompany the upload. Once you ve got these values all set, you re ready to write a script that handles the uploadedfile. At its most basic, this script would look something like the following: $uploaddir = uploads/ ; $uploadfile = $uploaddir . $_FILES[ upfile ][ name ]; if (move_uploaded_file($_FILES[ upfile ][ tmp_name ], $uploadfile)) { print( File upload was successful ); } else { print( File upload failed ); } This script creates a couple of simple variables to create an easily readable path and filename. The global $_FILESis a multidimensional array in order to handle concurrent file uploadsfrom the same form. In the first level, we identify the file by the name assigned to that field inthe form. In the second level, we use the predefined variable name to assign our file a name. Next we capture the actual file data, which is referenced by the value of tmp_name , the loca- tion where the bits are stored until you do something with them. Finally, we move it to its per- manent resting place. You probably didn t expect it to be that simple, and you won t be disappointed. Sure, if youcover all your bases ahead of time, this script will get the job done, but it s pretty insecure aswe have placed the vaguest and most general restrictions on what users can send us. The fol- lowing script offers some checks and modifications added for security and robustness: $uploaddir = uploads/ ; $filename = trim($_FILES[ upfile ][ name ]; $filename = substr($filename, -20); $filename = ereg_replace( , , $filename); if((ereg( .jpg , $filename)) || (ereg( .gif , $filename))) { $uploadfile = $uploaddir . $filename; if (move_uploaded_file($_FILES[ upfile ][ tmp_name ], $uploadfile)) { Caution33