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
...
unsigned char
cast to an int
, but the return value is assigned to a char
type.EOF
.EOF
.
char c;
while ( (c = getchar()) != '\n' && c != EOF ) {
...
}
getchar()
is cast to a char
and compared to EOF
(an int
). Assuming c
is a signed 8-bit value and EOF
is a 32-bit signed value, then if getchar()
returns a character represented by 0xFF, the value of c
will be sign extended to 0xFFFFFFFF in the comparison to EOF
. Since EOF
is typically defined as -1 (0xFFFFFFFF), the loop will terminate erroneously.amount
can hold a negative value when it is returned. Because the function is declared to return an unsigned int, amount
will be implicitly converted to unsigned.
unsigned int readdata () {
int amount = 0;
...
if (result == ERROR)
amount = -1;
...
return amount;
}
Example 1
is met, then the return value of readdata()
will be 4,294,967,295 on a system which uses 32-bit integers.accecssmainframe()
, the variable amount
can hold a negative value when it is returned. Because the function is declared to return an unsigned value, amount
will be implicitly cast to an unsigned number.
unsigned int readdata () {
int amount = 0;
...
amount = accessmainframe();
...
return amount;
}
accessmainframe()
is -1, then the return value of readdata()
will be 4,294,967,295 on a system that uses 32-bit integers.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.Denial of Wallet (DoW)
attack can occur when attackers exploit the cost-per-use model of cloud-based AI services by initiating a high volume of requests, which leads to unsustainable financial burdens on the provider. This can result in financial ruin for the provider, as the cost of processing excessive requests becomes unmanageable.Example 2: A chat model is utilized without configuring a
import openai
# OpenAI GPT model setup
openai.api_key = "your-api-key"
def generate_large_response(prompt):
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=1000
)
return response
# Submitting unbounded requests with high complexity and token count
prompt = "Generate an extensive article on AI."
response = generate_large_response(prompt)
print(response)
rate_limiter
parameter while interacting with the LLM model.
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(
model_name="claude-3-opus-20240229",
# not using rate_limiter
)
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();
}
1
must be passed to the first parameter (the version number) of the following file system function:
__xmknod
2
must be passed to the third parameter (the group argument) of the following wide character string functions:
__wcstod_internal
__wcstof_internal
_wcstol_internal
__wcstold_internal
__wcstoul_internal
3
must be passed as the first parameter (the version number) of the following file system functions:
__xstat
__lxstat
__fxstat
__xstat64
__lxstat64
__fxstat64
FILE *sysfile = fopen(test.file, "w+");
FILE insecureFile = *sysfile;
sysfile
is dereferenced in the assignment of insecureFile
, use of insecureFile
can result in a wide variety of problems.
FILE *sysfile = fopen(test.file, "r+");
res = fclose(sysfile);
if(res == 0){
printf("%c", getc(sysfile));
}
getc()
function runs after the file stream for sysfile
is closed, getc()
results in undefined behavior and can cause a system crash or potential modification or reading of the same or different file.
std::auto_ptr<foo> p(new foo);
foo* rawFoo = p.get();
delete rawFoo;
delete
, the management class knows not to use the pointer any further.int a = (Int32)i + (Int32)j;
throws an unhandled exception and crashes the application at runtime.
class Program
{
static int? i = j;
static int? j;
static void Main(string[] args)
{
j = 100;
int a = (Int32)i + (Int32)j;
Console.WriteLine(i);
Console.WriteLine(j);
Console.WriteLine(a);
}
}
aN
and bN
, but in the default case, the programmer accidentally set the value of aN
twice.
switch (ctl) {
case -1:
aN = 0; bN = 0;
break;
case 0:
aN = i; bN = -i;
break;
case 1:
aN = i + NEXT_SZ; bN = i - NEXT_SZ;
break;
default:
aN = -1; aN = -1;
break;
}
game
without initializing it.
struct Game {
address player;
}
function play(uint256 number) payable public {
…
Game game;
game.player = msg.sender;
…
}
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
}
}
PWD_COMPARE
procedure can be used by code that does not have access to sys.dba_users
to check a user's password.
CREATE or REPLACE procedure PWD_COMPARE(p_user VARCHAR, p_pwd VARCHAR)
AUTHID DEFINED
IS
cursor INTEGER;
...
BEGIN
IF p_user != 'SYS' THEN
cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cursor, 'SELECT password FROM SYS.DBA_USERS WHERE username = :u', DBMS_SQL.NATIVE);
DBMS_SQL.BIND_VARIABLE(cursor, ':u', p_user);
...
END IF;
END PWD_COMPARE;
sys
password. One way to cause an exception is to pass an overly long argument to p_user
. After the attacker knows that the cursor has leaked, they just have to guess the cursor and assign new bind variables.
DECLARE
x VARCHAR(32000);
i INTEGER;
j INTEGER;
r INTEGER;
password VARCHAR2(30);
BEGIN
FOR i IN 1..10000 LOOP
x:='b' || x;
END LOOP;
SYS.PWD_COMPARE(x,'password');
EXCEPTION WHEN OTHERs THEN
FOR j IN 1..10000
DBMS_SQL.BIND_VARIABLE(j, ':u', 'SYS');
DBMS_SQL.DEFINE_COLUMN(j, 1, password, 30);
r := DBMS_SQL.EXECUTE(j);
IF DBMS_SQL.FETCH_ROWS(j) > 0 THEN
DBMS_SQL.COLUMN_VALUE(j, 1, password);
EXIT;
END IF;
END LOOP;
...
END;
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
}
}