Distributed computation is about time and state. That is, in order for more than one component to communicate, state must be shared, and all that takes time.
Most programmers anthropomorphize their work. They think about one thread of control carrying out the entire program in the same way they would if they had to do the job themselves. Modern computers, however, switch between tasks very quickly, and in multi-core, multi-CPU, or distributed systems, two events may take place at exactly the same time. Defects rush to fill the gap between the programmer's model of how a program executes and what happens in reality. These defects are related to unexpected interactions between threads, processes, time, and information. These interactions happen through shared state: semaphores, variables, the file system, and, basically, anything that can store information.
HttpSessionState
attribute can damage application reliability.HttpSessionState
object, its attributes and any objects they reference in memory. This model limits active session state to what can be accommodated by the system memory of a single machine. In order to expand capacity beyond these limitations, servers are frequently configured to persistent session state information, which both expands capacity and permits the replication across multiple machines to improve overall performance. In order to persist its session state, the server must serialize the HttpSessionState
object, which requires that all objects stored in it be serializable.[Serializable]
attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable
interface.
public class DataGlob {
String GlobName;
String GlobValue;
public void AddToSession(HttpSessionState session) {
session["glob"] = this;
}
}
sleep()
while holding a lock can cause a loss of performance and might cause a deadlock.sleep()
while holding a lock can cause all of the other threads to wait for the resource to be released, which can result in degraded performance and deadlock.sleep()
while holding a lock.
ReentrantLock rl = new ReentrantLock();
...
rl.lock();
Thread.sleep(500);
...
rl.unlock();
if (fitz == null) {
synchronized (this) {
if (fitz == null) {
fitz = new Fitzer();
}
}
}
return fitz;
Fitzer()
object is ever allocated, but does not want to pay the cost of synchronization every time this code is called. This idiom is known as double-checked locking.Fitzer()
objects can be allocated. See The "Double-Checked Locking is Broken" Declaration for more details [1].pthread_mutex_unlock()
before another thread can begin running. If the signaling thread fails to unlock the mutex, the pthread_cond_wait()
call in the second thread will not return and the thread will not execute.pthread_cond_signal()
, but fails to unlock the mutex the other thread is waiting on.
...
pthread_mutex_lock(&count_mutex);
// Signal waiting thread
pthread_cond_signal(&count_threshold_cv);
...
...
if (tmpnam_r(filename)){
FILE* tmp = fopen(filename,"wb+");
while((recv(sock,recvbuf,DATA_SIZE, 0) > 0)&&(amt!=0))
amt = fwrite(recvbuf,1,DATA_SIZE,tmp);
}
...
tmpnam()
, tempnam()
, mktemp()
and their C++ equivalents prefaced with an _
(underscore) as well as the GetTempFileName()
function from the Windows API. This group of functions suffers from an underlying race condition on the filename chosen. Although the functions guarantee that the filename is unique at the time it is selected, there is no mechanism to prevent another process or an attacker from creating a file with the same name after it is selected but before the application attempts to open the file. Beyond the risk of a legitimate collision caused by another call to the same function, there is a high probability that an attacker will be able to create a malicious collision because the filenames generated by these functions are not sufficiently randomized to make them difficult to guess.open()
using the O_CREAT
and O_EXCL
flags or to CreateFile()
using the CREATE_NEW
attribute, which will fail if the file already exists and therefore prevent the types of attacks described previously. However, if an attacker is able to accurately predict a sequence of temporary file names, then the application may be prevented from opening necessary temporary storage causing a denial of service (DoS) attack. This type of attack would not be difficult to mount given the small amount of randomness used in the selection of the filenames generated by these functions.tmpfile()
and its C++ equivalents prefaced with an _
(underscore), as well as the slightly better-behaved C Library function mkstemp()
.tmpfile()
style functions construct a unique filename and open it in the same way that fopen()
would if passed the flags "wb+"
, that is, as a binary file in read/write mode. If the file already exists, tmpfile()
will truncate it to size zero, possibly in an attempt to assuage the security concerns mentioned earlier regarding the race condition that exists between the selection of a supposedly unique filename and the subsequent opening of the selected file. However, this behavior clearly does not solve the function's security problems. First, an attacker may pre-create the file with relaxed access-permissions that will likely be retained by the file opened by tmpfile()
. Furthermore, on Unix based systems if the attacker pre-creates the file as a link to another important file, the application may use its possibly elevated permissions to truncate that file, thereby doing damage on behalf of the attacker. Finally, if tmpfile()
does create a new file, the access permissions applied to that file will vary from one operating system to another, which can leave application data vulnerable even if an attacker is unable to predict the filename to be used in advance.mkstemp()
is a reasonably safe way to create temporary files. It will attempt to create and open a unique file based on a filename template provided by the user combined with a series of randomly generated characters. If it is unable to create such a file, it will fail and return -1
. On modern systems the file is opened using mode 0600
, which means the file will be secure from tampering unless the user explicitly changes its access permissions. However, mkstemp()
still suffers from the use of predictable file names and can leave an application vulnerable to denial of service attacks if an attacker causes mkstemp()
to fail by predicting and pre-creating the filenames to be used.
...
try:
tmp_filename = os.tempnam()
tmp_file = open(tmp_filename, 'w')
data = s.recv(4096)
while True:
more = s.recv(4096)
tmp_file.write(more)
if not more:
break
except socket.timeout:
errMsg = "Connection timed-out while connecting"
self.logger.exception(errMsg)
raise Exception
...
open()
using the os.O_CREAT
and os.O_EXCL
flags, which will fail if the file already exists and therefore prevent the types of attacks described previously. However, if an attacker is able to accurately predict a sequence of temporary file names, then the application may be prevented from opening necessary temporary storage causing a denial of service (DoS) attack. This type of attack would not be difficult to mount given the small amount of randomness used in the selection of the filenames generated by these functions.tmpfile()
.tmpfile()
style functions construct a unique filename and open it in the same way that open()
would if passed the flags "wb+"
, that is, as a binary file in read/write mode. If the file already exists, tmpfile()
will truncate it to size zero, possibly in an attempt to assuage the security concerns mentioned earlier regarding the race condition that exists between the selection of a supposedly unique filename and the subsequent opening of the selected file. However, this behavior clearly does not solve the function's security problems. First, an attacker may pre-create the file with relaxed access-permissions that will likely be retained by the file opened by tmpfile()
. Furthermore, on Unix based systems if the attacker pre-creates the file as a link to another important file, the application may use its possibly elevated permissions to truncate that file, thereby doing damage on behalf of the attacker. Finally, if tmpfile()
does create a new file, the access permissions applied to that file will vary from one operating system to another, which can leave application data vulnerable even if an attacker is unable to predict the filename to be used in advance.
...
HttpSession sesssion = request.getSession(true);
sesssion.setMaxInactiveInterval(-1);
...
HttpSession
attribute can damage application reliability.HttpSession
object across multiple JVMs so that if one JVM becomes unavailable another can step in and take its place without disrupting the flow of the application.Serializable
interface.
public class DataGlob {
String globName;
String globValue;
public void addToSession(HttpSession session) {
session.setAttribute("glob", this);
}
}
jti
claim provides a unique identifier for the JWT. It can be used to prevent the JWT from being replayed. The application "signs out" the user from all devices by deleting all JWTs in the backend store associated with that user. In addition, the developer should use exp
(expiration time) to expire the JWT.refresh_tokens
to web application clients and native application clients without verifying client_id
and client_secret
might be susceptible to impersonation attacks.client_id
and client_secret
when refreshing the access_token
are susceptible to impersonation and unauthorized access attacks. Authorization servers might issue refresh tokens to web application clients and native application clients. The authorization server must verify the binding between the refresh token and client identity whenever the client identity can be authenticated. When client authentication is not possible, the authorization server should deploy other means to detect refresh token abuse such as redirecting the user to repeat the authorization process after an expiration date is reached.state
parameter value with sufficient entropy are susceptible to a CSRF vulnerability.state
parameter value with sufficient entropy are susceptible to a CSRF vulnerability that might give an attacker the ability to login to the victim's current application account using a third-party account without any restrictions.state
parameter value is predictable. An attacker can perform a normal OAuth2 process and get the redirection URL that contains the authorization code for the third-party. The attacker can bind their own account to the victim's account for the vulnerable application by enticing a victim to access this URL. If the state
parameter is set in the redirection URL but without sufficient entropy, then an attacker can predict the user's state
parameter and forge a reliable redirection URL to persuade the victim to access and then implement a CSRF attack. block.timestamp
or block.number
as a proxy for time.block.timestamp
or block.number
are often used by developers to trigger time-dependent events, however, these values often give a sense of time that is generally not safe to use.block.timestamp
is unreliable at best, and at worst, malicious miners can alter the timestamp of their blocks if they see an advantage to do so.block.number
, even though it is possible to predict the time between blocks (approximately 14 seconds), block times are not constant and can vary depending on network activity. This makes block.number
unreliable for time-related calculations.block.number
to unlock funds after a certain period of time.
function withdraw() public {
require(users[msg.sender].amount > 0, 'no amount locked');
require(block.number >= users[msg.sender].unlockBlock, 'lock period not over');
uint amount = users[msg.sender].amount;
users[msg.sender].amount = 0;
(bool success, ) = msg.sender.call.value(amount)("");
require(success, 'transfer failed');
}
...
var authenticated = true;
...
database_connect.query('SELECT * FROM users WHERE name == ? AND password = ? LIMIT 1', userNameFromUser, passwordFromUser, function(err, results){
if (!err && results.length > 0){
authenticated = true;
}else{
authenticated = false;
}
});
if (authenticated){
//do something privileged stuff
authenticatedActions();
}else{
sendUnathenticatedMessage();
}
true
, otherwise false
. Unfortunately, since the callback is blocked by IO, it will run asynchronously and may be run after the check to if (authenticated)
, and since the default was true, it will go into the if-statement whether the user is actually authenticated or not.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
setuid root
. The program performs certain file operations on behalf of non-privileged users, and uses access checks to ensure that it does not use its root privileges to perform operations that should not be available to the current user. The program uses the access()
system call to check if the person running the program has permission to access the specified file before it opens the file and performs the necessary operations.
if (!access(file,W_OK)) {
f = fopen(file,"w+");
operate(f);
...
}
else {
fprintf(stderr,"Unable to open file %s.\n",file);
}
access()
behaves as expected, and returns 0
if the user running the program has the necessary permissions to write to the file, and -1 otherwise. However, because both access()
and fopen()
operate on filenames rather than on file handles, there is no guarantee that the file
variable still refers to the same file on disk when it is passed to fopen()
that it did when it was passed to access()
. If an attacker replaces file
after the call to access()
with a symbolic link to a different file, the program will use its root privileges to operate on the file even if it is a file that the attacker would otherwise be unable to modify. By tricking the program into performing an operation that would otherwise be impermissible, the attacker has gained elevated privileges.root
privileges. If the application is capable of performing any operation that the attacker would not otherwise be allowed perform, then it is a possible target.
fd = creat(FILE, 0644); /* Create file */
if (fd == -1)
return;
if (chown(FILE, UID, -1) < 0) { /* Change file owner */
...
}
chown()
is the same as the file created by the call to creat()
, but that is not necessarily the case. Since chown()
operates on a file name and not on a file handle, an attacker may be able to replace the file with a link to file the attacker does not own. The call to chown()
would then give the attacker ownership of the linked file.CBL_CHECK_FILE_EXIST
routine to check if the file exists before it creates one and performs the necessary operations.
CALL "CBL_CHECK_FILE_EXIST" USING
filename
file-details
RETURNING status-code
END-CALL
IF status-code NOT = 0
MOVE 3 to access-mode
MOVE 0 to deny-mode
MOVE 0 to device
CALL "CBL_CREATE_FILE" USING
filename
access-mode
deny-mode
device
file-handle
RETURNING status-code
END-CALL
END-IF
CBL_CHECK_FILE_EXIST
behaves as expected and returns a non-zero value, indicating that the file does not exist. However, because both CBL_CHECK_FILE_EXIST
and CBL_CREATE_FILE
operate on filenames rather than on file handles, there is no guarantee that the filename
variable still refers to the same file on disk when it is passed to CBL_CREATE_FILE
that it did when it was passed to CBL_CHECK_FILE_EXIST
. If an attacker creates filename
after the call to CBL_CHECK_FILE_EXIST
, the call to CBL_CREATE_FILE
will fail, leading the program to believe that the file is empty, when in fact it contains data controlled by the attacker.root
privileges that performs certain file operations on behalf of non-privileged users, and uses access checks to ensure that it does not use its root privileges to perform operations that should not be available to the current user. By tricking the program into performing an operation that would otherwise be impermissible, the attacker might gain elevated privileges.parse()
and format()
in java.text.Format
contain a design flaw that can cause one user to see another user's data.parse()
and format()
in java.text.Format
contains a race condition that can cause one user to see another user's data.
public class Common {
private static SimpleDateFormat dateFormat;
...
public String format(Date date) {
return dateFormat.format(date);
}
...
final OtherClass dateFormatAccess=new OtherClass();
...
public void function_running_in_thread1(){
System.out.println("Time in thread 1 should be 12/31/69 4:00 PM, found: "+ dateFormatAccess.format(new Date(0)));
}
public void function_running_in_thread2(){
System.out.println("Time in thread 2 should be around 12/29/09 6:26 AM, found: "+ dateFormatAccess.format(new Date(System.currentTimeMillis())));
}
}
format()
.RoamingFolder
or RoamingSettings
property of the Windows.Storage.ApplicationData
class.RoamingFolder
and RoamingSettings
properties get a container in the roaming app data store, which can then be used to share data between two more devices. By writing and reading objects stored in the roaming app data store, the developer increases the risk of compromise. This includes the confidentiality, integrity, and availability of the data, applications, and systems which share those objects through the roaming app data store.free()
twice on the same value can lead to a buffer overflow. When a program calls free()
twice with the same argument, the program's memory management data structures become corrupted. This corruption can cause the program to crash or, in some circumstances, cause two later calls to malloc()
to return the same pointer. If malloc()
returns the same value twice and the program later gives the attacker control over the data that is written into this doubly-allocated memory, the program becomes vulnerable to a buffer overflow attack.
void sh(int dummy) {
...
free(global2);
free(global1);
...
}
int main(int argc,char* argv[]) {
...
signal(SIGHUP,sh);
signal(SIGTERM,sh);
...
}