my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
function checkFile($nomeFile, $myExt = false){ if($myExt != false){ $goodExt = '_$myExt'.'_'; }else{ $goodExt = '_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_'; } $punto = strrpos($nomeFile, '.'); $ext = '_'.substr($nomeFile, $punto, 8).'_'; if(stristr($goodExt, $ext)){ return 1; }else{ return 0; } }
here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.
There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?
I’ve tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-
You’re going to need to validate that the uploaded file is actually the type that the extension indicates it is. You can do that through various methods, probably the easiest is via the
filecommand. I don’t know if it has an API. You can try it out yourself in the shell. For your example of file.exe that was renamed to file.jpg before being uploaded, runfile file.jpgand it will print out something telling you it’s an executable. It can be fooled, however.I’m guessing you don’t know much about Linux file permissions if you think .exe means it will be executed. On linux, only the execute bit in the file permissions determine that — you can execute any file, regardless of extension, if that bit is turned on. Don’t set it on any uploaded files and you should be safe from executing them. You may still be serving them back up to your site’s visitors, so it could still be a vector for XSS attacks, so watch out for that.