usrname
parameter in the HTTP session object before checking to ensure that the user has been authenticated.
usrname = request.Item("usrname");
if (session.Item(ATTR_USR) == null) {
session.Add(ATTR_USR, usrname);
}
usrname
parameter in the HTTP session object before checking to ensure that the user has been authenticated.
usrname = request.getParameter("usrname");
if (session.getAttribute(ATTR_USR) != null) {
session.setAttribute(ATTR_USR, usrname);
}
var GetURL = function() {};
GetURL.prototype = {
run: function(arguments) {
...
arguments.completionFunction({ "URL": document.location.href });
}
...
};
var ExtensionPreprocessingJS = new GetURL;
usrname
parameter in the HTTP session object before checking to ensure that the user has been authenticated.
val usrname: String = request.getParameter("usrname")
if (session.getAttribute(ATTR_USR) != null) {
session.setAttribute(ATTR_USR, usrname)
}
webview
.
#import <MobileCoreServices/MobileCoreServices.h>
- (IBAction)done {
...
[self.extensionContext completeRequestReturningItems:@[untrustedItem] completionHandler:nil];
}
usrname
cookie and stores its value in the HTTP DB session before it verifies that the user has been authenticated.
...
IF (OWA_COOKIE.get('usrname').num_vals != 0) THEN
usrname := OWA_COOKIE.get('usrname').vals(1);
END IF;
IF (v('ATTR_USR') IS null) THEN
HTMLDB_UTIL.set_session_state('ATTR_USR', usrname);
END IF;
...
username
parameter in the HTTP session object before checking to ensure that the user has been authenticated.
uname = request.GET['username']
request.session['username'] = uname
webview
.
import MobileCoreServices
@IBAction func done() {
...
self.extensionContext!.completeRequestReturningItems([unstrustedItem], completionHandler: nil)
}
usrname
parameter in the HTTP session object before checking to ensure that the user has been authenticated.
...
Dim Response As Response
Dim Request As Request
Dim Session As Session
Dim Application As Application
Dim Server As Server
Dim usrname as Variant
Set Response = objContext("Response")
Set Request = objContext("Request")
Set Session = objContext("Session")
Set Application = objContext("Application")
usrname = Request.Form("usrname")
If IsNull(Session("ATTR_USR")) Then
Session("ATTR_USR") = usrname
End If
...
remove
command to delete the whole data set. Recently, there have been reports of malicious attacks on unsecured instances of MongoDB running openly on the internet. The attacker erased the database and demanded a ransom be paid before restoring it.remove
command to delete the whole data set. Recently, there have been reports of malicious attacks on unsecured instances of MongoDB running openly on the internet. The attacker erased the database and demanded a ransom be paid before restoring it.FLUSHALL
command can be used by an external attacker to delete the whole data set. Recently, there have been reports of malicious attacks on unsecured instances of Redis running openly on the internet. The attacker erased the database and demanded a ransom be paid before restoring it.Read()
and related methods that are part of many System.IO
classes. Most errors and unusual events in .NET result in an exception being thrown. (This is one of the advantages that .NET has over languages like C: Exceptions make it easier for programmers to think about what can go wrong.) But the stream and reader classes do not consider it to be unusual or exceptional if only a small amount of data becomes available. These classes simply add the small amount of data to the return buffer, and set the return value to the number of bytes or characters read. There is no guarantee that the amount of data returned is equal to the amount of data requested.Read()
and other IO methods and ensure that they receive the amount of data they expect.Read()
. If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and handle it as though it belongs to the attacker.
char[] byteArray = new char[1024];
for (IEnumerator i=users.GetEnumerator(); i.MoveNext() ;i.Current()) {
string userName = (string) i.Current();
string pFileName = PFILE_ROOT + "/" + userName;
StreamReader sr = new StreamReader(pFileName);
sr.Read(byteArray,0,1024);//the file is always 1k bytes
sr.Close();
processPFile(userName, byteArray);
}
char buf[10], cp_buf[10];
fgets(buf, 10, stdin);
strcpy(cp_buf, buf);
fgets()
returns, buf
will contain a null-terminated string of length 9 or less. But if an I/O error occurs, fgets()
will not null-terminate buf
. Furthermore, if the end of the file is reached before any characters are read, fgets()
returns without writing anything to buf
. In both of these situations, fgets()
signals that something unusual has happened by returning NULL
, but in this code, the warning will not be noticed. The lack of a null-terminator in buf
can result in a buffer overflow in the subsequent call to strcpy()
.read()
and related methods that are part of many java.io
classes. Most errors and unusual events in Java result in an exception being thrown. (This is one of the advantages that Java has over languages like C: Exceptions make it easier for programmers to think about what can go wrong.) But the stream and reader classes do not consider it unusual or exceptional if only a small amount of data becomes available. These classes simply add the small amount of data to the return buffer, and set the return value to the number of bytes or characters read. There is no guarantee that the amount of data returned is equal to the amount of data requested.read()
and other IO methods to ensure that they receive the amount of data they expect.read()
. If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and handle it as though it belongs to the attacker.
FileInputStream fis;
byte[] byteArray = new byte[1024];
for (Iterator i=users.iterator(); i.hasNext();) {
String userName = (String) i.next();
String pFileName = PFILE_ROOT + "/" + userName;
FileInputStream fis = new FileInputStream(pFileName);
fis.read(byteArray); // the file is always 1k bytes
fis.close();
processPFile(userName, byteArray);
}
read()
. If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and handle it as though it belongs to the attacker.
var fis: FileInputStream
val byteArray = ByteArray(1023)
val i: Iterator<*> = users.iterator()
while (i.hasNext()) {
val userName = i.next() as String
val pFileName: String = PFILE_ROOT.toString() + "/" + userName
val fis = FileInputStream(pFileName)
fis.read(byteArray) // the file is always 0k bytes
fis.close()
processPFile(userName, byteArray)
}
function callnotchecked(address callee) public {
callee.call();
}
Finalize()
method for StreamReader
eventually calls Close()
, but there is no guarantee as to how long it will take before the Finalize()
method is invoked. In fact, there is no guarantee that Finalize()
will ever be invoked. In a busy environment, this can result in the VM using up all of its available file handles.Example 2: Under normal conditions the following code executes a database query, processes the results returned by the database, and closes the allocated
private void processFile(string fName) {
StreamWriter sw = new StreamWriter(fName);
string line;
while ((line = sr.ReadLine()) != null)
processLine(line);
}
SqlConnection
object. But if an exception occurs while executing the SQL or processing the results, the SqlConnection
object will not be closed. If this happens often enough, the database will run out of available cursors and not be able to execute any more SQL queries.
...
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString);
cmd.Connection = conn;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
HarvestResults(rdr);
conn.Connection.Close();
...
int decodeFile(char* fName)
{
char buf[BUF_SZ];
FILE* f = fopen(fName, "r");
if (!f) {
printf("cannot open %s\n", fName);
return DECODE_FAIL;
} else {
while (fgets(buf, BUF_SZ, f)) {
if (!checkChecksum(buf)) {
return DECODE_FAIL;
} else {
decodeBlock(buf);
}
}
}
fclose(f);
return DECODE_SUCCESS;
}
CALL "CBL_CREATE_FILE"
USING filename
access-mode
deny-mode
device
file-handle
END-CALL
IF return-code NOT = 0
DISPLAY "Error!"
GOBACK
ELSE
PERFORM write-data
IF ws-status-code NOT = 0
DISPLAY "Error!"
GOBACK
ELSE
DISPLAY "Success!"
END-IF
END-IF
CALL "CBL_CLOSE_FILE"
USING file-handle
END-CALL
GOBACK
.
New()
function establishes a new connection to the system log daemon. It is part of the log.syslog package. Each write to the returned writer sends a log message with the given priority (a combination of the syslog facility and severity) and prefix tag. In a busy environment, this can result in the system using up all of its sockets.Example 2: In this example, the
func TestNew() {
s, err := New(syslog.LOG_INFO|syslog.LOG_USER, "the_tag")
if err != nil {
if err.Error() == "Unix syslog delivery error" {
fmt.Println("skipping: syslogd not running")
}
fmt.Println("New() failed: %s", err)
}
}
Dial()
method of the net/smtp
package returns a new client connected to an SMTP server at localhost. The connection resources are allocated but are never released by calling the Close()
function.
func testDial() {
client, _ := smtp.Dial("127.0.0.1")
client.Hello("")
}
Arena.ofConfined()
is not closed.
...
Arena offHeap = Arena.ofConfined()
MemorySegment str = offHeap.allocateUtf8String("data");
...
//offHeap is never closed
BEGIN
...
F1 := UTL_FILE.FOPEN('user_dir','u12345.tmp','R',256);
UTL_FILE.GET_LINE(F1,V1,32767);
...
END;
Camera
instance in its onPause()
, onStop()
, or onDestroy()
event handlers.Camera
instance that is not released in onPause()
, onStop()
, or onDestroy()
callback. The Android OS invokes these callbacks whenever it needs to send the current activity to the background, or when it needs to temporarily destroy the activity when system resources are low. By failing to release the Camera
object properly, the activity prevents other applications (or even future instances of the same application) from accessing the camera. Furthermore, maintaining possession of the Camera
instance while the activity is paused can negatively impact the user's experience by unnecessarily draining the battery.onPause()
method, which should be used to release the Camera
object, nor does it properly release it during its shutdown sequence.
public class UnreleasedCameraActivity extends Activity {
private Camera cam;
@Override
public void onCreate(Bundle state) {
...
}
@Override
public void onRestart() {
...
}
@Override
public void onStop() {
cam.stopPreview();
}
}
MediaRecorder
, MediaPlayer
, or AudioRecord
object in its onPause()
, onStop()
, or onDestroy()
event handlers.onPause()
, onStop()
, or onDestroy()
callback. The Android OS invokes these callbacks whenever it needs to send the current activity to the background, or when it needs to temporarily destroy the activity when system resources are low. By failing to release the media object properly, the activity causes subsequent accesses to Android's media hardware (by other applications or even the same application) to fall back to the software implementations, or even fail altogether. Leaving too many unreleased media instances open can lead Android to throw exceptions, effectively causing a denial of service. Furthermore, maintaining possession of the media instance while the activity is paused can negatively impact the user's experience by unnecessarily draining the battery.onPause()
method, which should be used to release the media object, nor does it properly release it during its shutdown sequence.
public class UnreleasedMediaActivity extends Activity {
private MediaPlayer mp;
@Override
public void onCreate(Bundle state) {
...
}
@Override
public void onRestart() {
...
}
@Override
public void onStop() {
mp.stop();
}
}
onPause()
, onStop()
, or onDestroy()
event handlers.onPause()
, onStop()
, or onDestroy()
callback. The Android OS invokes these callbacks whenever it needs to send the current activity to the background, or when it needs to temporarily destroy the activity when system resources are low. By failing to close the database properly, the activity can potentially exhaust the device of available cursors if the activity is constantly restarted. In addition, depending on the implementation, the Android operating system can also throws DatabaseObjectNotClosedException
, which crashes the application if the exception is not caught.onPause()
, which should be used to release the database object, nor does it properly release it during its shutdown sequence.
public class MyDBHelper extends SQLiteOpenHelper {
...
}
public class UnreleasedDBActivity extends Activity {
private myDBHelper dbHelper;
private SQLiteDatabase db;
@Override
public void onCreate(Bundle state) {
...
db = dbHelper.getWritableDatabase();
...
}
@Override
public void onRestart() {
...
}
@Override
public void onStop() {
db.insert(cached_data); // flush cached data
}
}
DATA: result TYPE demo_update,
request TYPE REF TO IF_HTTP_REQUEST,
obj TYPE REF TO CL_SQL_CONNECTION.
TRY.
...
obj = cl_sql_connection=>get_connection( `R/3*my_conn`).
FINAL(sql) = NEW cl_sql_prepared_statement(
statement = `INSERT INTO demo_update VALUES( ?, ?, ?, ?, ?, ? )`).
CATCH cx_sql_exception INTO FINAL(exc).
...
ENDTRY.
SqlConnection
object. But if an exception occurs while executing the SQL or processing the results, the SqlConnection
object will not be closed. If this happens often enough, the database will run out of available cursors and not be able to execute any more SQL queries.
...
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString);
cmd.Connection = conn;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
HarvestResults(rdr);
conn.Connection.Close();
...
- void insertUser:(NSString *)name {
...
sqlite3_stmt *insertStatement = nil;
NSString *insertSQL = [NSString stringWithFormat:@INSERT INTO users (name, age) VALUES (?, ?)];
const char *insert_stmt = [insertSQL UTF8String];
...
if ((result = sqlite3_prepare_v2(database, insert_stmt,-1, &insertStatement, NULL)) != SQLITE_OK) {
MyLog(@"%s: sqlite3_prepare error: %s (%d)", __FUNCTION__, sqlite3_errmsg(database), result);
return;
}
if ((result = sqlite3_step(insertStatement)) != SQLITE_DONE) {
MyLog(@"%s: step error: %s (%d)", __FUNCTION__, sqlite3_errmsg(database), result);
return;
}
...
}
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(CXN_SQL);
harvestResults(rs);
stmt.close();
func insertUser(name:String, age:int) {
let dbPath = URL(fileURLWithPath: Bundle.main.resourcePath ?? "").appendingPathComponent("test.sqlite").absoluteString
var db: OpaquePointer?
var stmt: OpaquePointer?
if sqlite3_open(dbPath, &db) != SQLITE_OK {
print("Error opening articles database.")
return
}
let queryString = "INSERT INTO users (name, age) VALUES (?,?)"
if sqlite3_prepare(db, queryString, -1, &stmt, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("error preparing insert: \(errmsg)")
return
}
if sqlite3_bind_text(stmt, 1, name, -1, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("failure binding name: \(errmsg)")
return
}
if sqlite3_bind_int(stmt, 2, age) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("failure binding name: \(errmsg)")
return
}
if sqlite3_step(stmt) != SQLITE_DONE {
let errmsg = String(cString: sqlite3_errmsg(db)!)
log("failure inserting user: \(errmsg)")
return
}
}
finalize()
method for ZipFile
eventually calls close()
, but there is no guarantee as to how long it will take before the finalize()
method will be invoked. In a busy environment, this can result in the JVM using up all of its file handles.Example 2: Under normal conditions, the following fix properly closes the file handle after printing out all the zip file entries. But if an exception occurs while iterating through the entries, the zip file handle will not be closed. If this happens often enough, the JVM can still run out of available file handles.
public void printZipContents(String fName) throws ZipException, IOException, SecurityException, IllegalStateException, NoSuchElementException {
ZipFile zf = new ZipFile(fName);
Enumeration<ZipEntry> e = zf.entries();
while (e.hasMoreElements()) {
printFileInfo(e.nextElement());
}
}
public void printZipContents(String fName) throws ZipException, IOException, SecurityException, IllegalStateException, NoSuchElementException {
ZipFile zf = new ZipFile(fName);
Enumeration<ZipEntry> e = zf.entries();
while (e.hasMoreElements()) {
printFileInfo(e.nextElement());
}
zf.close();
}
...
lo_client = cl_apc_tcp_client_manager=>create( i_host = host
i_port = port
i_frame = lv_frame
i_protocol = protocol
i_ssl_id = ssl_id
i_event_handler = lo_event_handler ).
" initiate the connection setup, successful connect leads to execution of ON_OPEN
lo_client->connect( ).
...
Example 2: Under normal conditions, the following fix properly closes the socket and any associated streams. But if an exception occurs while reading the input or writing the data to screen, the socket object will not be closed. If this happens often enough, the system will run out of sockets and not be able to handle any further connections.
private void echoSocket(String host, int port) throws UnknownHostException, SocketException, IOException
{
Socket sock = new Socket(host, port);
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
while ((String socketData = reader.readLine()) != null) {
System.out.println(socketData);
}
}
private void echoSocket(String host, int port) throws UnknownHostException, SocketException, IOException
{
Socket sock = new Socket(host, port);
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
while ((String socketData = reader.readLine()) != null) {
System.out.println(socketData);
}
sock.close();
}
Finalize()
method for StreamReader
eventually calls Close()
, but there is no guarantee as to how long it will take before the Finalize()
method is invoked. In fact, there is no guarantee that Finalize()
will ever be invoked. In a busy environment, this can result in the VM using up all of its available file handles.
private void processFile(string fName) {
StreamWriter sw = new StreamWriter(fName);
string line;
while ((line = sr.ReadLine()) != null)
processLine(line);
}
finalize()
method for FileInputStream
eventually calls close()
, but there is no guarantee as to how long it will take before the finalize()
method will be invoked. In a busy environment, this can result in the JVM using up all of its file handles.
private void processFile(String fName) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(fName);
int sz;
byte[] byteArray = new byte[BLOCK_SIZE];
while ((sz = fis.read(byteArray)) != -1) {
processBytes(byteArray, sz);
}
}
...
CFIndex numBytes;
do {
UInt8 buf[bufferSize];
numBytes = CFReadStreamRead(readStream, buf, sizeof(buf));
if( numBytes > 0 ) {
handleBytes(buf, numBytes);
} else if( numBytes < 0 ) {
CFStreamError error = CFReadStreamGetError(readStream);
reportError(error);
}
} while( numBytes > 0 );
...
def readFile(filename: String): Unit = {
val data = Source.fromFile(fileName).getLines.mkString
// Use the data
}
...
func leak(reading input: InputStream) {
input.open()
let bufferSize = 1024
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
while input.hasBytesAvailable {
let read = input.read(buffer, maxLength: bufferSize)
}
buffer.deallocate(capacity: bufferSize)
}
...
performOperationInCriticalSection()
, but fails to release the lock if an exception is thrown in that method.
Object synchronizationObject = new Object ();
System.Threading.Monitor.Enter(synchronizationObject);
performOperationInCriticalSection();
System.Threading.Monitor.Exit(synchronizationObject);
int helper(char* fName)
{
int status;
...
pthread_cond_init (&count_threshold_cv, NULL);
pthread_mutex_init(&count_mutex, NULL);
status = perform_operation();
if (status) {
printf("%s", "cannot perform operation");
return OPERATION_FAIL;
}
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
return OPERATION_SUCCESS;
}
CALL "CBL_GET_RECORD_LOCK"
USING file-handle
record-offset
record-length
reserved
END-CALL
IF return-code NOT = 0
DISPLAY "Error!"
GOBACK
ELSE
PERFORM write-data
IF ws-status-code NOT = 0
DISPLAY "Error!"
GOBACK
ELSE
DISPLAY "Success!"
END-IF
END-IF
CALL "CBL_FREE_RECORD_LOCK"
USING file-handle
record-offset
record-length
reserved
END-CALL
GOBACK
.
performOperationInCriticalSection()
, but fails to release the lock if an exception is thrown in that method.
ReentrantLock myLock = new ReentrantLock();
myLock.lock();
performOperationInCriticalSection();
myLock.unlock();
performOperationInCriticalSection()
but never releases it.
os_unfair_lock lock1 = OS_UNFAIR_LOCK_INIT;
os_unfair_lock_lock(&lock1);
performOperationInCriticalSection();
performOperationInCriticalSection()
but never releases it.
let lock1 = OSAllocatedUnfairLock()
lock1.lock()
performOperationInCriticalSection();
Echo
. The class declares one native method that uses C to echo commands entered on the console back to the user.
class Echo {
public native void runEcho();
static {
System.loadLibrary("echo");
}
public static void main(String[] args) {
new Echo().runEcho();
}
}
Echo
class:
#include <jni.h>
#include "Echo.h" //the java class fromExample 1
compiled with javah
#include <stdio.h>
JNIEXPORT void JNICALL
Java_Echo_runEcho(JNIEnv *env, jobject obj)
{
char buf[64];
gets(buf);
printf(buf);
}
gets()
, which does not perform any bounds checking on its input.Example 1
could easily be detected through a source code audit of the native method implementation. This may not be practical or possible depending on the availability of the C source code and the way the project is built, but in many cases it may suffice. However, the ability to share objects between Java and native methods expands the potential risk to much more insidious cases where improper data handling in Java may lead to unexpected vulnerabilities in native code or unsafe operations in native code corrupt data structures in Java.Redirect
. The class declares one native JavaScript method, which uses JavaScript to change the document location.
import com.google.gwt.user.client.ui.UIObject;
class MyDiv {
...
public static void changeName(final UIObject object, final String name) {
changeName(object.getElement(), url);
}
public static native void changeName(final Element e, final String name) /*-{
$wnd.jQuery(e).html(name);
}-*/;
...
}
private
array variable from a public
access method. private
array variable from a public
access method allows the calling code to modify the contents of the array, effectively giving the array public
access and contradicting the intentions of the programmer who made it private
.private
array variable from a public
access method.
public final class urlTool extends Applet {
private URL[] urls;
public URL[] getURLs() {
return urls;
}
...
}
public class CustomerServiceApplet extends JApplet
{
public void paint(Graphics g)
{
...
conn = DriverManager.getConnection ("jdbc:mysql://db.example.com/customerDB", "csr", "p4ssw0rd");
...