Filesystem Security

דוגמה 4-1 .

 
?php

 
/

 
/

 
remove

 
a

 
file

 
from

 
the

 
user'

 
s

 
home

 
directory

 
$username

 
=

 
$HTTP_POST_VARS['user_submitted_name']

 
;

 
$homedir

 
=

 
"

 
/

 
home

 
/

 
$username"

 
;

 
$file_to_delete

 
=

 
"$userfile"

 
;

 
unlink

 
($homedir

 
/

 
$userfile)

 
;

 
echo

 
"$file_to_delete

 
has

 
been

 
deleted

 
!"

 
;

 
?



Since the username is postable from a user form, they can submit a username and file belonging to someone else, and delete files. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

דוגמה 4-2 . .. .








There are two important measures you should take to prevent these issues. Here is an improved script:

דוגמה 4-3 .

 
?php

 
/

 
/

 
removes

 
a

 
file

 
from

 
the

 
hard

 
drive

 
that

 
/

 
/

 
the

 
PHP

 
user

 
has

 
access

 
to

 
.

 
$username

 
=

 
$HTTP_SERVER_VARS[

 
'REMOTE_USER']

 
;

 
/

 
/

 
using

 
an

 
authentication

 
mechanisim

 
$homedir

 
=

 
"

 
/

 
home

 
/

 
$username"

 
;

 
$file_to_delete

 
=

 
basename("$userfile")

 
;

 
/

 
/

 
strip

 
paths

 
unlink

 
($homedir

 
/

 
$file_to_delete)

 
;

 
$fp

 
=

 
fopen("

 
/

 
home

 
/

 
logging

 
/

 
filedelete.log"

 
,"+a")

 
;

 
/

 
/log

 
the

 
deletion

 
$logstring

 
=

 
"$username

 
$homedir

 
$file_to_delete"

 
;

 
fputs

 
($fp

 
,

 
$logstring)

 
;

 
fclose($fp)

 
;

 
echo

 
"$file_to_delete

 
has

 
been

 
deleted

 
!"

 
;

 
?



However, even this is not without it's flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

דוגמה 4-4 .

 
?php

 
$username

 
=

 
$HTTP_SERVER_VARS[

 
'REMOTE_USER']

 
;

 
/

 
/

 
using

 
an

 
authentication

 
mechanisim

 
$homedir

 
=

 
"

 
/

 
home

 
/

 
$username"

 
;

 
if

 
(!ereg('^[^

 
.

 
/

 
][^

 
/

 
]*$'

 
,

 
$userfile)

 
)

 
die('bad

 
filename')

 
;

 
/

 
/die

 
,

 
do

 
not

 
process

 
if

 
(!ereg('^[^

 
.

 
/

 
][^

 
/

 
]*$'

 
,

 
$username)

 
)

 
die('bad

 
username')

 
;

 
/

 
/die

 
,

 
do

 
not

 
process

 
/

 
/etc..

 
.

 
?