Archive for May, 2007

551Chapter 29Security$key = get_user_key($username); $encr_hash = mcrypt_cbc(MCRYPT_BLOWFISH, $key, (Web site design and hosting)

Saturday, May 5th, 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
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

Space web hosting - 550Part IIIAdvanced Features and TechniquesWhat you need is

Saturday, May 5th, 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
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

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

Saturday, May 5th, 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
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision shared web hosting services

548Part IIIAdvanced Features (Free web hosting with ftp) and Techniquesyou wish to encrypt

Friday, May 4th, 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
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision best web hosting services

547Chapter 29SecurityThe Unix version of PHP provides a (Web host 4 life)

Friday, May 4th, 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
Note: If you are looking for cheap and reliable webhost to host and run your web application check Vision coldfusion web hosting services

Web design portfolio - 546Part IIIAdvanced Features and TechniquesWe shall call Alice s

Friday, May 4th, 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.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

Web design portfolio - 545Chapter 29Securitychmod($uploadfile, 0644); print( File upload was successful ); }

Friday, May 4th, 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.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision virtual web hosting services

544Part IIIAdvanced Features and TechniquesPHP defaults to a (Web hosting rating)

Thursday, May 3rd, 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
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision ftp web hosting services

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

Thursday, May 3rd, 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
Note: In case you are looking for affordable webhost to host and run your web application check Vision cheap hosting services

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

Thursday, May 3rd, 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.
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision mysql5 web hosting services