You are on page 1of 7

thefirstruleisthatnooneisperf

ectanditisnotpossibletoknow

everythinghoweveryoucann
ImproveFileUploadersProtections

otreadsomethingthatishidde
EspeciallyforWindowsbasedwebapplications

Revision:1.0

nherelikeapasswordorevena
SoroushDalili
irsdla.tyahood.o.tcom
soroush.secproject.com
Feb.2010

logininformationsodonottryt


oreadthiswordsasthereisno
meaningbehinditjustthecopy
rightisforsoroushdaliliwhich
triestohelpyouinordertokno
wmoresopleasehelphimtokn
owmoreaswellbyproducingp
1
SoroushDaliliImproveFileUploadersProtectionsRev.1.0
ImproveFileUploadersProtections
1 Introduction
Uploadingfilesbyusingwebapplicationsisverycommon.However,thereisalwaysahighriskaround
thismatter.Incaseofuploadingawebshellfilewhichcanbeabsolutelymalicious,anattackercanget
thesameprivilegeofaccessasthewebapplicationtotheserver.Inthispaper,whichismostlyaround
theWindowsbasedwebapplications,somegeneralsolutionsforprotectingagainstthistypeofattack
havebeensuggested.Moreover,asaproofofconcept,someofthemostgeneralprotectionmethods
andthewayofbypassingthemhavebeendiscussed.

Thisarticleisaneducationalarticletoimprovethesecurityofthewebapplications.And,theauthorof
thisarticle(SoroushDalili)doesnotacceptandhasnoresponsibilityaboutthecontentorusageofthis
articleinanyotherway.Anyotherusageofthisarticleexceptthelegalonesiscompletelyprohibited.

Pleaserespectthecopyrightandmentionthenameoftheauthor(SoroushDalili)incaseofusingthis
article.

2 PreventionMethods(Solutionstobemoresecure)
AsthispaperwantstobearoundtheWindowsbasedwebapplications,itisveryimportanttofollowthe
Microsoftsecuritybestpracticesfirst.Forthispurpose,someoftheusefullinksare:

IIS6.0SecurityBestPractices
SecuringSiteswithWebSitePermissions
IIS6.0OperationsGuide
ImprovingWebApplicationSecurity:ThreatsandCountermeasures
UnderstandingtheBuiltInUserandGroupAccountsinIIS7.0
IISSecurityChecklist

Andsomespecialrecommendationsforthedevelopersandwebmasters:

1) Neveracceptafilenameanditsextensiondirectlywithouthavingawhitelistfilter.
2) Itisnecessarytohavealistofonlypermittedextensionsonthewebapplication.And,fileextension
can be selected from the list. For instance, it can be a select case syntax (in case of having
VBScript)tochoosethefileextensioninregardtotherealfileextension.
3) All the control characters 1 and Unicode ones should be removed from the filenames and their
extensions without any exception. Also, the special characters such as ;, :, >, <, / ,\,
additional.,?,%,$,andsoonshouldbediscardedaswell.Ifitisapplicableandthereisno
need to have Unicode characters, it is highly recommended to only accept AlphaNumeric
charactersandonly1dotasaninputforthefilenameandtheextension;inwhichthefilename

1
http://en.wikipedia.org/wiki/Control_character

SoroushDaliliImproveFileUploadersProtectionsRev.1.0
andalsotheextensionshouldnotbeemptyatall(regularexpression:[azAZ09]{1,200}\.[azAZ0
9]{1,10}).
4) Limitthefilenamelength.Forinstance,themaximumlengthofthenameofafileplusitsextension
shouldbelessthan255characters(withoutanydirectory)inanNTFSpartition.
5) Itisrecommendedtouseanalgorithmtodeterminethefilenames.Forinstance,afilenamecanbe
aMD5hashofthenameoffileplusthedateoftheday.
6) Uploadeddirectoryshouldnothaveanyexecutepermission.
7) Limitthefilesizetoamaximumvalueinordertopreventdenialofserviceattacks(onfilespaceor
otherwebapplicationsfunctionssuchastheimageresizer).
8) Restrictsmallsizefilesastheycanleadtodenialofserviceattacks.So,theminimumsizeoffiles
shouldbeconsidered.
9) UseCrossSiteRequestForgeryprotectionmethods.
10) Preventfromoverwritingafileincaseofhavingthesamehashforboth.
11) Useavirusscannerontheserver(ifitisapplicable).Or,ifthecontentsoffilesarenotconfidential,
afreevirusscannerwebsitecanbeused.Inthiscase,fileshouldbestoredwitharandomname
andwithoutanyextensionontheserverfirst,andaftertheviruschecking(uploadingtoafreevirus
scannerwebsiteandgettingbacktheresult),itcanberenamedtoitsspecificnameandextension.
12) TrytousePOSTmethodinsteadofPUT(orGET!)
13) Log users activities. However, the logging mechanism should be secured against log forgery and
codeinjectionitself.
14) In case of having compressed file extract functions, contents of the compressed file should be
checkedonebyoneasanewfile.

3 WeakProtectionMethodsandMethodsofBypassing
3.1 UsingBlackListforFilesExtensions:
Somewebapplicationsstilluseonlyablacklistofextensionstopreventfromuploadingamaliciousfile.

3.1.1 BypassMethod(s):
1) It is possible to bypass this protection by using some extensions which are executable on the
server but are not mentioned in the list. (Example: file.php5, file.shtml, file.asa, or
file.cer)
2) Sometimesitispossibletobypassthisprotectionbychangingsomelettersofextensiontothe
capitalform(example:file.aSporfile.PHp3).
3) Usingtrailingspacesand/ordotsattheendofthefilenamecansometimescausebypassingthe
protection.Thesespacesand/ordotsattheendofthefilenamewillberemovedwhenthefile
wants to be saved on the hard disk automatically. The filename can be sent to the server by
usingalocalproxyorusingasimplescript(example:file.asp............).

SoroushDaliliImproveFileUploadersProtectionsRev.1.0
4) IncaseofusinginsecureIIS6(orpriorversions),itmightbepossibletobypassthisprotectionby
adding a semicolon after the forbidden extension and before the permitted extension
(example:file.asp;.jpg) 2 .
5) Thisprotectioncanbecompletelybypassedbyusingthemostfamouscontrolcharacterwhichis
Null character (0x00) after the forbidden extension and before the permitted one. In this
method, during the saving process all the strings after the Null character will be discarded.
PuttingaNullcharacterinthefilenamecanbesimplydonebyusingalocalproxyorbyusinga
script(example:file.asp%00.jpg).Besides,itwouldbeperfectiftheNullcharacterisinserted
directly by using the Hex view option of a local proxy such as Burpsuite or Webscarab in the
rightplace(withoutusing%).
6) ItisalsopossibletocreateafilewithaforbiddenextensionbyusingNTFSalternatedatastream
(ADS). In this case, a : sign will be inserted after the forbidden extension and before the
permitted one. As a result, an empty file with the forbidden extension will be created on the
server (example: file.asp:.jpg). Attacker can try to edit this file later to execute his/her
malicious codes. However, an empty file is not always good for an attacker. So, there is an
inventedmethodbytheauthorofthispaperinwhichanattackercanuploadanonemptyshell
file by using the ADS. In this method, a forbidden file can be uploaded by using this pattern:
file.asp::$data..
7) Sometimescombinationoftheabovecanleadtobypassingtheprotections.

3.2 UsingWhiteListforFilesExtensions:
Manywebapplicationsuseawhitelisttoacceptthefilesextensions.Althoughusingwhitelistisoneof
therecommendations,itisnotenoughonitsown.Withouthavinginputvalidation,thereisstilla
chanceforanattackertobypasstheprotections.

3.2.1 BypassMethod(s):
1) The3rdmethodof3.1.1.
2) The4thmethodof3.1.1.
3) The5thmethodof3.1.1.
4) The6thmethodof3.1.1.
5) The list of permitted extensions should be reviewed as it can contain malicious extension as
well.Forinstance,incaseofhaving.shtmlinthelist,theapplicationcanbevulnerabletoSSI
attacks.

3.3 UsingContentTypefromtheHeader:
ContentType entity in the header of the request indicates the Internet media type of the message
content 3 .Sometimeswebapplicationsusethisparameterinordertorecognizeafileasagoodone.For
instance,theyonlyacceptthefileswiththeContentTypeoftext/plain.

3.3.1 BypassMethod(s):


2
IIS6SemiColonVulnerability(http://soroush.secproject.com/downloadable/iissemicolonreport.pdf)
3
http://en.wikipedia.org/wiki/MIME#ContentType

SoroushDaliliImproveFileUploadersProtectionsRev.1.0
1) Itispossibletobypassthisprotectionbychangingthisparameterintherequestheaderbyusing
alocalproxy.

3.4 UsingFileTypeRecogniser:
Sometimeswebapplicationsintentionallyorunintentionallyusesomefunctions(orAPIs)tocheckthe
type of the file in order to do further process. For instance, in case of having image resizing, it is
probabletohaveimagetyperecogniser.

3.4.1 BypassMethod(s):
1) Sometimestherecognisersjustreadthefewfirstcharacters(orheader)ofthefilesinorderto
checkthem.Inthiscase,anattackercaninsertthemaliciouscodeaftersomevalidheader.
2) Therearealwayssomeplacesinthestructureofthefileswhichareforthecommentssection
andhavenoeffectonthemainfile.And,anattackercaninsertmaliciouscodesinthesepoints.
3) Also, it is not impossible to think about a file modifier (for example an image resizer) which
producesmaliciouscodesitselfincaseofreceivingspecialinput.

4 AdditionalNote(s)
Therearesomeotherthingsthatdevelopersandwebmastersshouldhaveagoodknowledgeabout:

In case of having folder (directory) creation function, it should be secured similar to the files
extensionsandalsoitshouldbeprotectedagainstthedirectorytraversalattacks.Otherwise,an
attacker might be able to create a directory which has execution permission and bypass the
protections.
Incaseofhavingrename,move,andeditfunctionsforthefilesordirectories,thesame
protectionshouldbeappliedforallofthem.Inotherwords,itshouldbeconsideredasanew
fileorfolderincaseofhavingrename,move,oreditcommand.Donotforgetthatthereis
nodifferencebetweenrenameandmovefunctionsasbothofthemcandothesamething.So,
bothofthemshouldbeprotectedagainstthedirectorytraversalattacksaswell.
Sometimestheprotectionscanbebypassedbycreatinganewdirectoryfirst,anduploadfilesin
it.Forinstance,thereisno.htaccessanymoretoprotectthenewfolderfromexecutingPHP
files.Moreover,sometimesthereisnopermissiontouploadafile,butitispossibletoupload
thefilesinanewlycreateddirectory.
Sometimesprotectionscanbebypassedbyuploadingafile,similartoanexistingfilename.For
instance, uploading a file with the name of default.aspx may bypass the protections. Or as
another example, an attacker may upload a .htaccess file in order to rewrite the protection
rules.
Usuallyanattackerrenamestheforbiddenextensiontoapermittedoneandtriestouploadit
by using a local proxy. Then, he/she changes the file extension to whatever he/she wants by
usingthatlocalproxybeforesendingittotheserver.Inthismethod,theclientsideJavascripts
canalsobebypassedwithoutanyproblem,andallrequestparameterswouldbeinthecorrect
format except the filename. They always assume that there is a value in the cookies which

SoroushDaliliImproveFileUploadersProtectionsRev.1.0
should be set to a special value by a JavaScript on checking and submitting the forms
information.So,nevertrusttheclientsidesprotections.
Sometimes it is not possible to find the upload directory or temporary upload directory. An
attackercansendalongfile(ordirectory)nameoruseforbiddenfilenames 4 (suchascom5)in
ordertogetanerrortofindtheuploaddirectories.Andincaseofhavingatemporaryfolderto
modifythefilesbeforeputtingthemintherightdirectory(forexampleforresizingtheimages),
anattackermightbeabletofindthisdirectoryandexecutethemaliciousfilesimmediatelyafter
uploadingthem(beforebeingdeleted).So,theerrormessagesshouldbehiddenandalsoallthe
temporarydirectoriesshouldbeoutofwebURLaccess.
Alternatedatastreamfeaturecanleadtosomefurtherissuesincaseofaccepting:character.
First,anattackercanhidesomeinformationinsidetheotherfiles.Thishiddendatacanbeused
later.
Moreover,anattackercancreateanirremovablefileinordertokeephis/hermaliciouscodeon
theserver.Asanexample:irremovable.php.::$Data
It is also possible to create a directory by using ADS feature. For example the
test.directory::$index_allocation,asafilename,willcreatetest.directoryfolderontheweb
server.

5 GeneralExamples
As examples of a secured and insecure version of a file uploader, FCKEditor is the best one for both.
Securityfunctionsofitsfileuploaderinthenewversioncannotbebypassedbythemethodswhichare
discussedinthispaper.

5.1 Insecure:
Forinstance,FCKEditor2.4.3(andpriorversions)usesalonglistofthebadextensionsinitsASP
uploader:


Anditisvulnerableto:
o The1stmethodof3.1.1.AnattackercanuploadanASPfilebyrenamingitsextensionto
.asaor.cer.
o The3rdmethodof3.1.1.Anattackercanuploadadangerousfilebyusingtrailingdots
andspaces.
o The4thmethodof3.1.1.CodeexecutiondependsontheIISversionanditspatch.
o The5thmethodof3.1.1.Nullcharactershouldbeinserteddirectlyintothefilenameasit
isshownhere:



4
http://en.wikipedia.org/wiki/Filename

SoroushDaliliImproveFileUploadersProtectionsRev.1.0
o The6thmethodof3.1.1.

5.2 Secured:
Itisnearlyimpossibletosaythatanapplicationiscompletelysecure.However,asahighlysecuredfile
uploader,ASPversionofFCKFinder2.6.6isagoodexample
(http://sourceforge.net/projects/fckeditor/files/).Asitissecureagainstthemethodswhichwere
mentionedhere(revision1.0).

SoroushDaliliImproveFileUploadersProtectionsRev.1.0

You might also like