permissions := strconv.Atoi(os.Getenv("filePermissions"));
fMode := os.FileMode(permissions)
os.chmod(filePath, fMode);
...
String permissionMask = System.getProperty("defaultFileMask");
Path filePath = userFile.toPath();
...
Set<PosixFilePermission> perms = PosixFilePermissions.fromString(permissionMask);
Files.setPosixFilePermissions(filePath, perms);
...
$rName = $_GET['publicReport'];
chmod("/home/". authenticateUser . "/public_html/" . rName,"0755");
...
publicReport
, such as "../../localuser/public_html/.htpasswd
", the application will make the specified file readable to the attacker.
...
$mask = $CONFIG_TXT['perms'];
chmod($filename,$mask);
...
permissions = os.getenv("filePermissions");
os.chmod(filePath, permissions);
...
...
rName = req['publicReport']
File.chmod("/home/#{authenticatedUser}/public_html/#{rName}", "0755")
...
publicReport
, such as "../../localuser/public_html/.htpasswd
", the application will make the specified file readable to the attacker.
...
mask = config_params['perms']
File.chmod(filename, mask)
...
sprintf()
, FormatMessageW()
, or syslog()
.snprintf()
.
int main(int argc, char **argv){
char buf[128];
...
snprintf(buf,128,argv[1]);
}
%x
, than the function takes as arguments to be formatted. (In this example, the function takes no arguments to be formatted.) By using the %n
formatting directive, the attacker may write to the stack, causing snprintf()
to write the number of bytes output thus far to the specified argument (rather than reading a value from the argument, which is the intended behavior). A sophisticated version of this attack will use four staggered writes to completely control the value of a pointer on the stack.
printf("%d %d %1$d %1$d\n", 5, 9);
5 9 5 5
Example 1
.syslog()
function is sometimes used as follows:
...
syslog(LOG_ERR, cmdBuf);
...
syslog()
is a format string, any formatting directives included in cmdBuf
are interpreted as described in Example 1
.syslog()
:
...
syslog(LOG_ERR, "%s", cmdBuf);
...
sprintf()
, FormatMessageW()
, syslog()
, NSLog
, or NSString.stringWithFormat
Example 1: The following code utilizes a command line argument as a format string in NSString.stringWithFormat:
.
int main(int argc, char **argv){
char buf[128];
...
[NSString stringWithFormat:argv[1], argv[2] ];
}
%x
, than the function takes as arguments to be formatted. (In this example, the function takes no arguments to be formatted.)
printf("%d %d %1$d %1$d\n", 5, 9);
5 9 5 5
Example 1
.syslog()
function is sometimes used as follows:
...
syslog(LOG_ERR, cmdBuf);
...
syslog()
is a format string, any formatting directives included in cmdBuf
are interpreted as described in Example 1
.syslog()
:Example 4: Apple core classes provide interesting avenues for exploiting format string vulnerabilities.
...
syslog(LOG_ERR, "%s", cmdBuf);
...
String.stringByAppendingFormat()
function is sometimes used as follows:
...
NSString test = @"Sample Text.";
test = [test stringByAppendingFormat:[MyClass
formatInput:inputControl.text]];
...
stringByAppendingFormat()
:
...
NSString test = @"Sample Text.";
test = [test stringByAppendingFormat:@"%@", [MyClass
formatInput:inputControl.text]];
...
strncpy()
, can cause vulnerabilities when used incorrectly. The combination of memory manipulation and mistaken assumptions about the size or makeup of a piece of data is the root cause of most buffer overflows.
void wrongNumberArgs(char *s, float f, int d) {
char buf[1024];
sprintf(buf, "Wrong number of %.512s");
}
strncpy()
, can cause vulnerabilities when used incorrectly. The combination of memory manipulation and mistaken assumptions about the size or makeup of a piece of data is the root cause of most buffer overflows.f
from a float using a %d
format specifier.
void ArgTypeMismatch(float f, int d, char *s, wchar *ws) {
char buf[1024];
sprintf(buf, "Wrong type of %d", f);
...
}
script
tag.
<script src="http://www.example.com/js/fancyWidget.js"></script>
www.example.com
, then the site is dependent upon www.example.com
to serve up correct and non-malicious code. If attackers can compromise www.example.com
, then they can alter the contents of fancyWidget.js
to subvert the security of the site. They could, for example, add code to fancyWidget.js
to steal a user's confidential data.
...
String lang = Request.Form["lang"];
WebClient client = new WebClient();
client.BaseAddress = url;
NameValueCollection myQueryStringCollection = new NameValueCollection();
myQueryStringCollection.Add("q", lang);
client.QueryString = myQueryStringCollection;
Stream data = client.OpenRead(url);
...
lang
such as en&poll_id=1
, and then the attacker may be able to change the poll_id
at will.
...
String lang = request.getParameter("lang");
GetMethod get = new GetMethod("http://www.example.com");
get.setQueryString("lang=" + lang + "&poll_id=" + poll_id);
get.execute();
...
lang
such as en&poll_id=1
, and then the attacker will be able to change the poll_id
at will.
<%
...
$id = $_GET["id"];
header("Location: http://www.host.com/election.php?poll_id=" . $id);
...
%>
name=alice
specified, but they've added an additional name=alice&
, and if this is being used on a server that takes the first occurrence, then this may impersonate alice
in order to get further information regarding her account.
String arg = request.getParameter("arg");
...
Intent intent = new Intent();
...
intent.setClassName(arg);
ctx.startActivity(intent);
...
Intent
has been detected. Implicit internal intents might expose the system to man-in-the-middle style attacks on internal components.Intent
uses a custom action as defined by an internal component. Implicit intents can facilitate the calling of intents from any given external component without knowledge of the specific component. Combining the two allows for an application to access intents specified for a specific internal use from outside of the desired application context.Intent
from an external application can enable for a wide variety of man-in-the-middle exploits ranging in severity from information leakage and denial of service to remote code execution, depending on the capacity of the internal action specified by the Intent
.Intent
.
...
val imp_internal_intent_action = Intent("INTERNAL_ACTION_HERE")
startActivity(imp_internal_intent_action)
...
PendingIntent
has been detected. Implicit pending intents might result in security vulnerabilities such as denial of service, private and system information leakage, and privilege escalation.Intent
at a later time. Implicit intents facilitate the calling of intents from any given external component, using a general name and filter to determine execution.Intent
is created as a PendingIntent
, this might allow for the Intent
to be sent to an unintended component that runs outside of the intended temporal context, leaving the system vulnerable to exploit vectors such as denial of service, private and system information leakage, and privilege escalation.PendingIntent
.
...
val imp_intent = Intent()
val flag_mut = PendingIntent.FLAG_MUTABLE
val pi_flagmutable_impintintent = PendingIntent.getService(
this,
0,
imp_intent,
flag_mut
)
...
PendingIntent
has been detected that has its flag value set to FLAG_MUTABLE
. Pending intents created with the flag value of FLAG_MUTABLE
are susceptible to having unspecified Intent
fields set downstream, which can modify the capacity of the Intent
and leave the system open to vulnerability.Intent
of a PendingIntent
after its creation can leave a system open to attack. This mostly depends on the overall capability of the underlying Intent
. In most cases, it is best practice to prevent potential issues by setting the PendingIntent
flag to FLAG_IMMUTABLE
.PendingIntent
created with a flag value of FLAG_MUTABLE
.
...
val intent_flag_mut = Intent(Intent.ACTION_GTALK_SERVICE_DISCONNECTED, Uri.EMPTY, this, DownloadService::class.java)
val flag_mut = PendingIntent.FLAG_MUTABLE
val pi_flagmutable = PendingIntent.getService(
this,
0,
intent_flag_mut,
flag_mut
)
...
Intent
from external input to start an activity, start a service, or deliver a broadcast can enable an attacker to arbitrarily launch internal application components, control the behavior of an internal component, or indirectly access protected data from a content provider through temporary permission grants.Intent
nested in the extras bundle of an externally provided Intent
.Intent
to launch a component by calling startActivity
, startService
, or sendBroadcast
.Intent
from an external source and uses that Intent
to start an activity.
...
Intent nextIntent = (Intent) getIntent().getParcelableExtra("next-intent");
startActivity(nextIntent);
...
returningObjectFlag
to true
on the javax.naming.directory.SearchControls
instance passed to the search
method or by using a library function that sets this flag on its behalf.
<beans ... >
<authentication-manager>
<ldap-authentication-provider
user-search-filter="(uid={0})"
user-search-base="ou=users,dc=example,dc=org"
group-search-filter="(uniqueMember={0})"
group-search-base="ou=groups,dc=example,dc=org"
group-role-attribute="cn"
role-prefix="ROLE_">
</ldap-authentication-provider>
</authentication-manager>
</beans>
chroot()
should be dropped immediately after the operation is performed.chroot()
, it must first acquire root
privilege. As soon as the privileged operation has completed, the program should drop root
privilege and return to the privilege level of the invoking user.chroot()
to restrict the application to a subset of the file system below APP_HOME
in order to prevent an attacker from using the program to gain unauthorized access to files located elsewhere. The code then opens a file specified by the user and processes the contents of the file.
...
chroot(APP_HOME);
chdir("/");
FILE* data = fopen(argv[1], "r+");
...
setuid()
with some non-zero value means the application is continuing to operate with unnecessary root
privileges. Any successful exploit carried out by an attacker against the application can now result in a privilege escalation attack because any malicious operations will be performed with the privileges of the superuser. If the application drops to the privilege level of a non-root
user, the potential for damage is substantially reduced.CREATE
command that is sent to the IMAP server. An attacker may use this parameter to modify the command sent to the server and inject new commands using CRLF characters.
...
final String foldername = request.getParameter("folder");
IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
...
folder.doCommand(new IMAPFolder.ProtocolCommand() {
@Override
public Object doCommand(IMAPProtocol imapProtocol) throws ProtocolException {
try {
imapProtocol.simpleCommand("CREATE " + foldername, null);
} catch (Exception e) {
// Handle Exception
}
return null;
}
});
...
USER
and PASS
command that is sent to the POP3 server. An attacker may use this parameter to modify the command sent to the server and inject new commands using CRLF characters.
...
String username = request.getParameter("username");
String password = request.getParameter("password");
...
POP3SClient pop3 = new POP3SClient(proto, false);
pop3.login(username, password)
...
VRFY
command that is sent to the SMTP server. An attacker might use this parameter to modify the command sent to the server and inject new commands using CRLF characters.
...
c, err := smtp.Dial(x)
if err != nil {
log.Fatal(err)
}
user := request.FormValue("USER")
c.Verify(user)
...
VRFY
command that is sent to the SMTP server. An attacker may use this parameter to modify the command sent to the server and inject new commands using CRLF characters.
...
String user = request.getParameter("user");
SMTPSSLTransport transport = new SMTPSSLTransport(session,new URLName(Utilities.getProperty("smtp.server")));
transport.connect(Utilities.getProperty("smtp.server"), username, password);
transport.simpleCommand("VRFY " + user);
...
VRFY
command that is sent to the SMTP server. An attacker may use this parameter to modify the command sent to the server and inject new commands using CRLF characters.
...
user = request.GET['user']
session = smtplib.SMTP(smtp_server, smtp_tls_port)
session.ehlo()
session.starttls()
session.login(username, password)
session.docmd("VRFY", user)
...
null
.Item
property is null
before calling the member function Equals()
, potentially causing a null
dereference.
string itemName = request.Item(ITEM_NAME);
if (itemName.Equals(IMPORTANT_ITEM)) {
...
}
...
null
value."null
.malloc()
.
buf = (char*) malloc(req_size);
strncpy(buf, xfer, req_size);
malloc()
fail because req_size
was too large or because there were too many requests being handled at the same time? Or was it caused by a memory leak that has built up over time? Without handling the error, there is no way to know.null
.getParameter()
is null
before calling the member function compareTo()
, potentially causing a null
dereference.Example 2:. The following code shows a system property that is set to
String itemName = request.getParameter(ITEM_NAME);
if (itemName.compareTo(IMPORTANT_ITEM)) {
...
}
...
null
and later dereferenced by a programmer who mistakenly assumes it will always be defined.
System.clearProperty("os.name");
...
String os = System.getProperty("os.name");
if (os.equalsIgnoreCase("Windows 95") )
System.out.println("Not supported");
null
value."NullException
.cmd
" defined. If an attacker can control the program's environment so that "cmd
" is not defined, the program throws a null-pointer exception when it attempts to call the Trim()
method.
string cmd = null;
...
cmd = Environment.GetEnvironmentVariable("cmd");
cmd = cmd.Trim();
null
before checking if the pointer is null
. Dereference-after-check errors occur when a program makes an explicit check for null
, but proceeds to dereference the pointer when it is known to be null
. Errors of this type are often the result of a typo or programmer oversight. A dereference-after-store error occurs when a program explicitly sets a pointer to null
and dereferences it later. This error is often the result of a programmer initializing a variable to null
when it is declared.ptr
is not NULL
. That assumption is made explicit when the programmer dereferences the pointer. This assumption is later contradicted when the programmer checks ptr
against NULL
. If ptr
can be NULL
when it is checked in the if
statement then it can also be NULL
when it dereferenced and may cause a segmentation fault.Example 2: In the following code, the programmer confirms that the variable
ptr->field = val;
...
if (ptr != NULL) {
...
}
ptr
is NULL
and subsequently dereferences it erroneously. If ptr
is NULL
when it is checked in the if
statement, then a null
dereference will occur, thereby causing a segmentation fault.Example 3: In the following code, the programmer forgets that the string
if (ptr == null) {
ptr->field = val;
...
}
'\0'
is actually 0 or NULL
, thereby dereferencing a null-pointer and causing a segmentation fault.Example 4: In the following code, the programmer explicitly sets the variable
if (ptr == '\0') {
*ptr = val;
...
}
ptr
to NULL
. Later, the programmer dereferences ptr
before checking the object for a null
value.
*ptr = NULL;
...
ptr->field = val;
...
}
NullPointerException
.cmd
" defined. If an attacker can control the program's environment so that "cmd
" is not defined, the program throws a null-pointer exception when it attempts to call the trim()
method.
String val = null;
...
cmd = System.getProperty("cmd");
if (cmd)
val = util.translateCommand(cmd);
...
cmd = val.trim();
unserialize()
function. Attackers could pass specially crafted serialized strings to a vulnerable unserialize()
call, resulting in an arbitrary PHP object(s) injection into the application scope. The severity of this vulnerability depends on the classes available in the application scope. Classes implementing PHP magic method such as __wakeup
or __destruct
will be interesting for the attackers since they will be able to execute the code within these methods.__destruct()
magic method and executing a system command defined as a class property. There is also an insecure call to unserialize()
with user-supplied data.
...
class SomeAvailableClass {
public $command=null;
public function __destruct() {
system($this->command);
}
}
...
$user = unserialize($_GET['user']);
...
Example 1
, the application may be expecting a serialized User
object but an attacker may actually provide a serialized version of SomeAvailableClass
with a predefined value for its command
property:
GET REQUEST: http://server/page.php?user=O:18:"SomeAvailableClass":1:{s:7:"command";s:8:"uname -a";}
$user
object and then it will execute the command provided by the attacker.unserialize()
is being called using a technique known as "Property Oriented Programming", which was introduced by Stefan Esser during BlackHat 2010 conference. This technique allows an attacker to reuse existing code to craft its own payload.YAML.load()
. Attackers could pass specially crafted serialized strings to a vulnerable YAML.load()
call, resulting in arbitrary Ruby objects being injected into the program, as long as the class is loaded into the application at the time of deserialization. This may open up a whole heap of various attack opportunities, such as bypassing validation logic to find cross-site scripting vulnerabilities, allow SQL injection through what appear to be hardcoded values, or even full code execution.YAML.load()
with user-supplied data.
...
class Transaction
attr_accessor :id
def initialize(num=nil)
@id = num.is_a?(Numeric) ? num : nil
end
def print_details
unless @id.nil?
print $conn.query("SELECT * FROM transactions WHERE id=#{@id}")
end
end
end
...
user = YAML.load(params[:user]);
user.print_details
...
Example 1
, the application may be expecting a serialized User
object, which also happens to have a function called print_details
, but an attacker may actually provide a serialized version of a Transaction
object with a predefined value for its @id
attribute. A request such as the following can thus allow bypassing of the validation check that attempts to make sure @id
is a numeric value
GET REQUEST: http://server/page?user=!ruby%2Fobject%3ATransaction%0Aid%3A4%20or%205%3D5%0A
user
parameter is assigned !ruby/object:Transaction\nid:4 or 5=5\n
.Transaction
, setting @id
to "4 or 5=5"
. When the developer believes they will be calling User#print_details()
, they will now be calling Transaction#print_details()
, and Ruby's string interpolation will mean the SQL query will be changed to execute the query: SELECT * FROM transactions WHERE id=4 or 5=5
. Due to the extra clause that was added, the query evaluates to true
and will return everything within the transactions
table instead of the single row that was intended from the developer.YAML.load()
is being called using a technique known as "Property Oriented Programming", which was introduced by Stefan Esser during BlackHat 2010 conference. This technique allows an attacker to reuse existing code to craft its own payload.