Wednesday, 9 April 2014

security in java

Security
Watch for uninitialized variables
<?php
if($user=='rasmus') {
$ok = true;
}
if($ok) {
echo "$user logged in";
}
?>

 

Catch these by setting the error_reporting level to E_ALL. The above script would generate this
warning (assuming $user is set):
<b>Warning</b>: Undefined variable: ok in <b>script.php</b> on line <b>6</b>
You can of course also turn off register_globals, but that addresses the symptom rather than the
problem.


Never trust user data!
<?php
readfile($filename);
?>
Turning off register_globals doesn't make this any more secure. The script would instead look like
this:
<?php
readfile($HTTP_POST_VARS['filename']);
?>

The only way to secure something like this is to be really paranoid about cleaning user input. In this
case if you really want the user to be able to specify a filename that gets used in any of PHP's file
functions, do something like this:
<?php
$doc_root = $HTTP_SERVER_VARS['DOCUMENT_ROOT'];
$filename = realpath($filename);
readfile($doc_root.$filename);
?>
You may also want to strip out any path and only take the filename component. An easy way to do
that is to use the basename() function. Or perhaps check the extension of the file. You can get the
extension using this code:
<?php
$ext = substr($str,strrpos($str,'.'));
?>


Again, never trust user data!
<?php
system("ls $dir");
?>



Take this standard file upload form:
<FORM ENCTYPE="multipart/form-data" ACTION="upload.php" METHOD=POST>
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="100000">
Send this file: <INPUT NAME="myfile" TYPE="file">
<INPUT TYPE="submit" VALUE="Send File">
</FORM>
The correct way to put the uploaded file in the right place:
<?php
/* Not under DOCUMENT_ROOT */
$destination = "/some/path/$myfile_name";
move_uploaded_file($myfile, $destination);
?>
If you are uploading files to be placed somewhere under the DOCUMENT_ROOT then you need to
be very paranoid in checking what you are putting there. For example, you wouldn't want to let people
upload arbitrary PHP scripts that they can then browse to in order to execute them. Here we get
paranoid about checking that only image files can be uploaded. We even look at the contents of the
file and ensure that the file extension matches the content.

 

<?php
$type = $HTTP_POST_FILES['myfile']['type'];
$file = $HTTP_POST_FILES['myfile']['tmp_name'];
$name = $HTTP_POST_FILES['myfile']['name'];
$types = array(0,'.gif','.jpg','.png','.swf');
list(,,$type) = getimagesize($file);
if($type) {
$name = substr($name,0,strrpos($str,'.'));
$name .= $types[$type];
}
move_uploaded_file($myfile, "$DOCUMENT_ROOT/images/$name");
?>

                                         "News powered by"
                                 
                                                    
                                        



No comments:

Post a Comment

About Me

Popular Posts

Designed By Seo Blogger Templates