Professional Documents
Culture Documents
CommandInjectionOWASP
CommandInjection
FromOWASP
ThisisanAttack.Toviewallattacks,pleaseseetheAttackCategorypage.
Lastrevision(mm/dd/yy):08/7/2016
Description
Commandinjectionisanattackinwhichthegoalisexecutionofarbitrarycommandsonthehostoperatingsystem
viaavulnerableapplication.Commandinjectionattacksarepossiblewhenanapplicationpassesunsafeuser
supplieddata(forms,cookies,HTTPheadersetc.)toasystemshell.Inthisattack,theattackersuppliedoperating
systemcommandsareusuallyexecutedwiththeprivilegesofthevulnerableapplication.Commandinjection
attacksarepossiblelargelyduetoinsufficientinputvalidation.
ThisattackdiffersfromCodeInjection,inthatcodeinjectionallowstheattackertoaddhisowncodethatisthen
executedbytheapplication.InCodeInjection,theattackerextendsthedefaultfunctionalityoftheapplication
withoutthenecessityofexecutingsystemcommands.
Examples
Example1
ThefollowingcodeisawrapperaroundtheUNIXcommandcatwhichprintsthecontentsofafiletostandard
output.Itisalsoinjectable:
#include<stdio.h>
#include<unistd.h>
intmain(intargc,char**argv){
charcat[]="cat";
char*command;
size_tcommandLength;
commandLength=strlen(cat)+strlen(argv[1])+1;
command=(char*)malloc(commandLength);
strncpy(command,cat,commandLength);
strncat(command,argv[1],(commandLengthstrlen(cat)));
system(command);
return(0);
}
Usednormally,theoutputissimplythecontentsofthefilerequested:
$./catWrapperStory.txt
Whenlastweleftourheroes...
https://www.owasp.org/index.php?title=Command_Injection&printable=yes
1/5
1/9/2017
CommandInjectionOWASP
However,ifweaddasemicolonandanothercommandtotheendofthisline,thecommandisexecutedby
catWrapperwithnocomplaint:
$./catWrapper"Story.txt;ls"
Whenlastweleftourheroes...
Story.txtdoubFree.cnullpointer.c
unstosig.cwww*a.out*
format.cstrlen.cuseFree*
catWrapper*misnull.cstrlength.cuseFree.c
commandinjection.cnodefault.ctrunc.cwriteWhatWhere.c
IfcatWrapperhadbeensettohaveahigherprivilegelevelthanthestandarduser,arbitrarycommandscouldbe
executedwiththathigherprivilege.
Example2
Thefollowingsimpleprogramacceptsafilenameasacommandlineargument,anddisplaysthecontentsofthe
filebacktotheuser.Theprogramisinstalledsetuidrootbecauseitisintendedforuseasalearningtooltoallow
systemadministratorsintrainingtoinspectprivilegedsystemfileswithoutgivingthemtheabilitytomodifythem
ordamagethesystem.
intmain(char*argc,char**argv){
charcmd[CMD_MAX]="/usr/bin/cat";
strcat(cmd,argv[1]);
system(cmd);
}
Becausetheprogramrunswithrootprivileges,thecalltosystem()alsoexecuteswithrootprivileges.Ifauser
specifiesastandardfilename,thecallworksasexpected.However,ifanattackerpassesastringoftheform"rm
rf/",thenthecalltosystem()failstoexecutecatduetoalackofargumentsandthenplowsontorecursivelydelete
thecontentsoftherootpartition.
Example3
Thefollowingcodefromaprivilegedprogramusestheenvironmentvariable$APPHOMEtodeterminethe
application'sinstallationdirectory,andthenexecutesaninitializationscriptinthatdirectory.
...
char*home=getenv("APPHOME");
char*cmd=(char*)malloc(strlen(home)+strlen(INITCMD));
if(cmd){
strcpy(cmd,home);
strcat(cmd,INITCMD);
execl(cmd,NULL);
}
...
AsinExample2,thecodeinthisexampleallowsanattackertoexecutearbitrarycommandswiththeelevated
privilegeoftheapplication.Inthisexample,theattackercanmodifytheenvironmentvariable$APPHOMEto
specifyadifferentpathcontainingamaliciousversionofINITCMD.Becausetheprogramdoesnotvalidatethe
valuereadfromtheenvironment,bycontrollingtheenvironmentvariable,theattackercanfooltheapplicationinto
runningmaliciouscode.
https://www.owasp.org/index.php?title=Command_Injection&printable=yes
2/5
1/9/2017
CommandInjectionOWASP
Theattackerisusingtheenvironmentvariabletocontrolthecommandthattheprograminvokes,sotheeffectof
theenvironmentisexplicitinthisexample.Wewillnowturnourattentiontowhatcanhappenwhentheattacker
changesthewaythecommandisinterpreted.
Example4
ThecodebelowisfromawebbasedCGIutilitythatallowsuserstochangetheirpasswords.Thepasswordupdate
processunderNISincludesrunningmakeinthe/var/ypdirectory.Notethatsincetheprogramupdatespassword
records,ithasbeeninstalledsetuidroot.
Theprograminvokesmakeasfollows:
system("cd/var/yp&&make&>/dev/null");
Unlikethepreviousexamples,thecommandinthisexampleishardcoded,soanattackercannotcontrolthe
argumentpassedtosystem().However,sincetheprogramdoesnotspecifyanabsolutepathformake,anddoesnot
scrubanyenvironmentvariablespriortoinvokingthecommand,theattackercanmodifytheir$PATHvariableto
pointtoamaliciousbinarynamedmakeandexecutetheCGIscriptfromashellprompt.Andsincetheprogram
hasbeeninstalledsetuidroot,theattacker'sversionofmakenowrunswithrootprivileges.
Theenvironmentplaysapowerfulroleintheexecutionofsystemcommandswithinprograms.Functionslike
system()andexec()usetheenvironmentoftheprogramthatcallsthem,andthereforeattackershaveapotential
opportunitytoinfluencethebehaviorofthesecalls.
TherearemanysitesthatwilltellyouthatJava'sRuntime.execisexactlythesameasC'ssystemfunction.Thisis
nottrue.Bothallowyoutoinvokeanewprogram/process.However,C'ssystemfunctionpassesitsargumentsto
theshell(/bin/sh)tobeparsed,whereasRuntime.exectriestosplitthestringintoanarrayofwords,thenexecutes
thefirstwordinthearraywiththerestofthewordsasparameters.Runtime.execdoesNOTtrytoinvoketheshell
atanypoint.Thekeydifferenceisthatmuchofthefunctionalityprovidedbytheshellthatcouldbeusedfor
mischief(chainingcommandsusing"&","&&","|","||",etc,redirectinginputandoutput)wouldsimplyendupas
aparameterbeingpassedtothefirstcommand,andlikelycausingasyntaxerror,orbeingthrownoutasaninvalid
parameter.
Example5
ThefollowingtrivialcodesnippetsarevulnerabletoOScommandinjectionontheUnix/Linuxplatform:
C:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
intmain(intargc,char**argv)
{
charcommand[256];
if(argc!=2){
printf("Error:Pleaseenteraprogramtotime!\n");
return1;
}
memset(&command,0,sizeof(command));
strcat(command,"time./");
strcat(command,argv[1]);
https://www.owasp.org/index.php?title=Command_Injection&printable=yes
3/5
1/9/2017
CommandInjectionOWASP
system(command);
return0;
}
Ifthiswereasuidbinary,considerthecasewhenanattackerentersthefollowing:'lscat/etc/shadow'.
IntheUnixenvironment,shellcommandsareseparatedbyasemicolon.Wenowcanexecutesystem
commandsatwill!
Java:
TherearemanysitesthatwilltellyouthatJava'sRuntime.execisexactlythesameasC'ssystemfunction.
Thisisnottrue.Bothallowyoutoinvokeanewprogram/process.However,C'ssystemfunctionpassesits
argumentstotheshell(/bin/sh)tobeparsed,whereasRuntime.exectriestosplitthestringintoanarrayof
words,thenexecutesthefirstwordinthearraywiththerestofthewordsasparameters.Runtime.execdoes
NOTtrytoinvoketheshellatanypoint.Thekeydifferenceisthatmuchofthefunctionalityprovidedby
theshellthatcouldbeusedformischief(chainingcommandsusing"&","&&","|","||",etc,redirecting
inputandoutput)wouldsimplyendupasaparameterbeingpassedtothefirstcommand,andlikely
causingasyntaxerror,orbeingthrownoutasaninvalidparameter.
Example6
ThefollowingPHPcodesnippetisvulnerabletoacommandinjectionattack:
<?php
print("Pleasespecifythenameofthefiletodelete");
print("<p>");
$file=$_GET['filename'];
system("rm$file");
?>
Thefollowingrequestandresponseisanexampleofasuccessfulattack:
Request
http://127.0.0.1/delete.php?filename=bob.txt;id
Response
Pleasespecifythenameofthefiletodelete
uid=33(wwwdata)gid=33(wwwdata)groups=33(wwwdata)
SanitizingInput
ReplaceorBanargumentswith;
Othershellescapesavailable
Example:
&&
|
...
https://www.owasp.org/index.php?title=Command_Injection&printable=yes
4/5
1/9/2017
CommandInjectionOWASP
RelatedAttacks
CodeInjection
BlindSQLInjection
BlindXPathInjection
LDAPinjection
RelativePathTraversal
RelatedControls
Category:InputValidation
Ideally,adevelopershoulduseexistingAPIfortheirlanguage.Forexample(Java):Ratherthanuse
Runtime.exec()toissuea'mail'command,usetheavailableJavaAPIlocatedatjavax.mail.*
IfnosuchavailableAPIexists,thedevelopershouldscruballinputformaliciouscharacters.Implementinga
positivesecuritymodelwouldbemostefficient.Typically,itismucheasiertodefinethelegalcharactersthanthe
illegalcharacters.
References
CWE77:CommandInjection(http://cwe.mitre.org/data/definitions/77.html)
CWE78:OSCommandInjection(http://cwe.mitre.org/data/definitions/78.html)
http://blog.phpsecurity.org/archives/76Holesinmostpreg_matchfilters.html
Retrievedfrom"http://www.owasp.org/index.php?title=Command_Injection&oldid=220078"
Categories: OWASPASDRProject InjectionAttack Injection Attack
Thispagewaslastmodifiedon7August2016,at12:11.
Thispagehasbeenaccessed407,373times.
ContentisavailableunderaCreativeCommons3.0Licenseunlessotherwisenoted.
https://www.owasp.org/index.php?title=Command_Injection&printable=yes
5/5