...
password = 'tiger'.
...
...
URLRequestDefaults.setLoginCredentialsForHost(hostname, "scott", "tiger");
...
...
HttpRequest req = new HttpRequest();
req.setClientCertificate('mycert', 'tiger');
...
...
NetworkCredential netCred =
new NetworkCredential("scott", "tiger", domain);
...
...
rc = SQLConnect(*hdbc, server, SQL_NTS, "scott",
SQL_NTS, "tiger", SQL_NTS);
...
...
MOVE "scott" TO UID.
MOVE "tiger" TO PASSWORD.
EXEC SQL
CONNECT :UID
IDENTIFIED BY :PASSWORD
AT :MYCONN
USING :MYSERVER
END-EXEC.
...
...
<cfquery name = "GetSSNs" dataSource = "users"
username = "scott" password = "tiger">
SELECT SSN
FROM Users
</cfquery>
...
...
var password = "foobarbaz";
...
javap -c
command to access the disassembled code, which will contain the values of the passwords used. The result of this operation might look something like the following for Example 1
:
javap -c ConnMngr.class
22: ldc #36; //String jdbc:mysql://ixne.com/rxsql
24: ldc #38; //String scott
26: ldc #17; //String tiger
password := "letmein"
...
response.SetBasicAuth(usrName, password)
...
DriverManager.getConnection(url, "scott", "tiger");
...
javap -c
command to access the disassembled code, which will contain the values of the passwords used. The result of this operation might look something like the following for Example 1
:
javap -c ConnMngr.class
22: ldc #36; //String jdbc:mysql://ixne.com/rxsql
24: ldc #38; //String scott
26: ldc #17; //String tiger
...
webview.setWebViewClient(new WebViewClient() {
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
handler.proceed("guest", "allow");
}
});
...
Example 1
, this code will run successfully, but anyone who has access to it will have access to the password.
...
obj = new XMLHttpRequest();
obj.open('GET','/fetchusers.jsp?id='+form.id.value,'true','scott','tiger');
...
...
{
"username":"scott"
"password":"tiger"
}
...
...
DriverManager.getConnection(url, "scott", "tiger")
...
javap -c
command to access the disassembled code, which will contain the values of the passwords used. The result of this operation might look something like the following for Example 1
:
javap -c ConnMngr.class
22: ldc #36; //String jdbc:mysql://ixne.com/rxsql
24: ldc #38; //String scott
26: ldc #17; //String tiger
...
webview.webViewClient = object : WebViewClient() {
override fun onReceivedHttpAuthRequest( view: WebView,
handler: HttpAuthHandler, host: String, realm: String
) {
handler.proceed("guest", "allow")
}
}
...
Example 1
, this code will run successfully, but anyone who has access to it will have access to the password.
...
rc = SQLConnect(*hdbc, server, SQL_NTS, "scott",
SQL_NTS, "tiger", SQL_NTS);
...
...
$link = mysql_connect($url, 'scott', 'tiger');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
...
DECLARE
password VARCHAR(20);
BEGIN
password := "tiger";
END;
password = "tiger"
...
response.writeln("Password:" + password)
...
Mysql.new(URI(hostname, 'scott', 'tiger', databasename)
...
...
ws.url(url).withAuth("john", "secret", WSAuthScheme.BASIC)
...
javap -c
command to access the disassembled code, which will contain the values of the passwords used. The result of this operation might look something such as the following for Example 1
:
javap -c MyController.class
24: ldc #38; //String john
26: ldc #17; //String secret
...
let password = "secret"
let username = "scott"
let con = DBConnect(username, password)
...
...
https://user:secretpassword@example.com
...
...
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
con.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=scott;Passwd=tiger;"
...
...
credential_settings:
username: scott
password: tiger
...
Null
passwords can compromise security.null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
var storedPassword:String = null;
var temp:String;
if ((temp = readPassword()) != null) {
storedPassword = temp;
}
if(Utils.verifyPassword(userPassword, storedPassword))
// Access protected resources
...
}
...
readPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for userPassword
.null
to password variables is never a good idea as it might enable attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
string storedPassword = null;
string temp;
if ((temp = ReadPassword(storedPassword)) != null) {
storedPassword = temp;
}
if (Utils.VerifyPassword(storedPassword, userPassword)) {
// Access protected resources
...
}
...
ReadPassword()
fails to retrieve the stored password due to a database error or other problem, then an attacker can easily bypass the password check by providing a null
value for userPassword
.null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
string storedPassword = null;
string temp;
if ((temp = ReadPassword(storedPassword)) != null) {
storedPassword = temp;
}
if(Utils.VerifyPassword(storedPassword, userPassword))
// Access protected resources
...
}
...
ReadPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for userPassword
.null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
char *stored_password = NULL;
readPassword(stored_password);
if(safe_strcmp(stored_password, user_password))
// Access protected resources
...
}
...
readPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for user_password
.null
to password variables is never a good idea as it might enable attackers to bypass password verification or it might indicate that resources are protected by an empty password.null
to password variables is a bad idea because it can allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
String storedPassword = null;
String temp;
if ((temp = readPassword()) != null) {
storedPassword = temp;
}
if(Utils.verifyPassword(userPassword, storedPassword))
// Access protected resources
...
}
...
readPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for userPassword
.null
, reads credentials from an Android WebView store if they have not been previously rejected by the server for the current request, and uses them to setup authentication for viewing protected pages.
...
webview.setWebViewClient(new WebViewClient() {
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
String username = null;
String password = null;
if (handler.useHttpAuthUsernamePassword()) {
String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
username = credentials[0];
password = credentials[1];
}
handler.proceed(username, password);
}
});
...
Example 1
, if useHttpAuthUsernamePassword()
returns false
, an attacker will be able to view protected pages by supplying a null
password.null
password.null
:
...
var password=null;
...
{
password=getPassword(user_data);
...
}
...
if(password==null){
// Assumption that the get didn't work
...
}
...
null
to password variables because it might enable attackers to bypass password verification or indicate that resources are not protected by a password.null
password.
{
...
"password" : null
...
}
null
password. Null
passwords can compromise security.null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
NSString *stored_password = NULL;
readPassword(stored_password);
if(safe_strcmp(stored_password, user_password)) {
// Access protected resources
...
}
...
readPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for user_password
.null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
<?php
...
$storedPassword = NULL;
if (($temp = getPassword()) != NULL) {
$storedPassword = $temp;
}
if(strcmp($storedPassword,$userPassword) == 0) {
// Access protected resources
...
}
...
?>
readPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for userPassword
.null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
.
DECLARE
password VARCHAR(20);
BEGIN
password := null;
END;
null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
storedPassword = NULL;
temp = getPassword()
if (temp is not None) {
storedPassword = temp;
}
if(storedPassword == userPassword) {
// Access protected resources
...
}
...
getPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for userPassword
.nil
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.nil
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
@storedPassword = nil
temp = readPassword()
storedPassword = temp unless temp.nil?
unless Utils.passwordVerified?(@userPassword, @storedPassword)
...
end
...
readPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for @userPassword
.nil
as a default value when none is specified. In this case you also need to make sure that the correct number of arguments are specified in order to make sure a password is passed to the function.null
to password variables is a bad idea because it can allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
ws.url(url).withAuth("john", null, WSAuthScheme.BASIC)
...
null
password. Null
passwords can compromise security.nil
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
, attempts to read a stored value for the password, and compares it against a user-supplied value.
...
var stored_password = nil
readPassword(stored_password)
if(stored_password == user_password) {
// Access protected resources
...
}
...
readPassword()
fails to retrieve the stored password due to a database error or another problem, then an attacker could trivially bypass the password check by providing a null
value for user_password
.null
to password variables is never a good idea as it may allow attackers to bypass password verification or might indicate that resources are protected by an empty password.null
and uses it to connect to a database.
...
Dim storedPassword As String
Set storedPassword = vbNullString
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
con.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=scott;Passwd=" & storedPassword &";"
...
Example 1
succeeds, it indicates that the database user account "scott" is configured with an empty password, which an attacker can easily guess. After the program ships, updating the account to use a non-empty password will require a code change.
...
var fs:FileStream = new FileStream();
fs.open(new File("config.properties"), FileMode.READ);
var decoder:Base64Decoder = new Base64Decoder();
decoder.decode(fs.readMultiByte(fs.bytesAvailable, File.systemCharset));
var password:String = decoder.toByteArray().toString();
URLRequestDefaults.setLoginCredentialsForHost(hostname, usr, password);
...
config.properties
can read the value of password
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
string value = regKey.GetValue(passKey).ToString());
byte[] decVal = Convert.FromBase64String(value);
NetworkCredential netCred =
new NetworkCredential(username,decVal.toString(),domain);
...
password
. Any devious employee with access to this information can use it to break into the system.
...
RegQueryValueEx(hkey, TEXT(.SQLPWD.), NULL,
NULL, (LPBYTE)password64, &size64);
Base64Decode(password64, size64, (BYTE*)password, &size);
rc = SQLConnect(*hdbc, server, SQL_NTS, uid,
SQL_NTS, password, SQL_NTS);
...
password64
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
01 RECORDX.
05 UID PIC X(10).
05 PASSWORD PIC X(10).
05 LEN PIC S9(4) COMP.
...
EXEC CICS
READ
FILE('CFG')
INTO(RECORDX)
RIDFLD(ACCTNO)
...
END-EXEC.
CALL "g_base64_decode_inplace" using
BY REFERENCE PASSWORD
BY REFERENCE LEN
ON EXCEPTION
DISPLAY "Requires GLib library" END-DISPLAY
END-CALL.
EXEC SQL
CONNECT :UID
IDENTIFIED BY :PASSWORD
END-EXEC.
...
CFG
can read the value of password and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
file, _ := os.Open("config.json")
decoder := json.NewDecoder(file)
decoder.Decode(&values)
password := base64.StdEncoding.DecodeString(values.Password)
request.SetBasicAuth(values.Username, password)
...
config.json
can read the value of password
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
<beans:bean id="encoder" class="org.springframework.security.crypto.password.Md4PasswordEncoder"/>
...
config.properties
can read the value of password
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
obj = new XMLHttpRequest();
obj.open('GET','/fetchusers.jsp?id='+form.id.value,'true','scott','tiger');
...
plist
file and uses it to unzip a password-protected file.
...
NSDictionary *dict= [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"]];
NSString *encoded_password = [dict valueForKey:@"encoded_password"];
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:encoded_password options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
[SSZipArchive unzipFileAtPath:zipPath toDestination:destPath overwrite:TRUE password:decodedString error:&error];
...
Config.plist
file can read the value of encoded_password
and easily determine that the value has been base64 encoded.
...
$props = file('config.properties', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$password = base64_decode($props[0]);
$link = mysql_connect($url, $usr, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
...
config.properties
can read the value of password
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
props = os.open('config.properties')
password = base64.b64decode(props[0])
link = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = password,
db = "test")
...
config.properties
can read the value of password
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
require 'pg'
require 'base64'
...
passwd = Base64.decode64(ENV['PASSWD64'])
...
conn = PG::Connection.new(:dbname => "myApp_production", :user => username, :password => passwd, :sslmode => 'require')
PASSWD64
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
val prop = new Properties();
prop.load(new FileInputStream("config.properties"));
val password = Base64.decode(prop.getProperty("password"));
DriverManager.getConnection(url, usr, password);
...
config.properties
can read the value of password
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.plist
file and uses it to unzip a password-protected file.
...
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
let password = base64decode(dict["encoded_password"])
zipArchive.unzipOpenFile(zipPath, password:password])
}
...
Config.plist
file can read the value of encoded_password
and easily determine that the value has been base64 encoded.
...
root:qFio7llfVKk.s:19033:0:99999:7:::
...
...
...
Private Declare Function GetPrivateProfileString _
Lib "kernel32" Alias "GetPrivateProfileStringA" _
(ByVal lpApplicationName As String, _
ByVal lpKeyName As Any, ByVal lpDefault As String, _
ByVal lpReturnedString As String, ByVal nSize As Long, _
ByVal lpFileName As String) As Long
...
Dim password As String
...
password = StrConv(DecodeBase64(GetPrivateProfileString("MyApp", "Password", _
"", value, Len(value), _
App.Path & "\" & "Config.ini")), vbUnicode)
...
con.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=scott;Passwd=" & password &";"
...
Config.ini
can read the value of Password
and easily determine that the value has been base64 encoded. Any devious employee with access to this information can use it to break into the system.
...
*Get the report that is to be deleted
r_name = request->get_form_field( 'report_name' ).
CONCATENATE `C:\\users\\reports\\` r_name INTO dsn.
DELETE DATASET dsn.
...
..\\..\\usr\\sap\\DVEBMGS00\\exe\\disp+work.exe
", the application will delete a critical file and immediately crash the SAP system.
...
PARAMETERS: p_date TYPE string.
*Get the invoice file for the date provided
CALL FUNCTION 'FILE_GET_NAME'
EXPORTING
logical_filename = 'INVOICE'
parameter_1 = p_date
IMPORTING
file_name = v_file
EXCEPTIONS
file_not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
* Implement suitable error handling here
ENDIF.
OPEN DATASET v_file FOR INPUT IN TEXT MODE.
DO.
READ DATASET v_file INTO v_record.
IF SY-SUBRC NE 0.
EXIT.
ELSE.
WRITE: / v_record.
ENDIF.
ENDDO.
...
..\\..\\usr\\sap\\sys\\profile\\default.pfl
" instead of a valid date, the application will reveal all the default SAP application server profile parameter settings - possibly leading to more refined attacks.../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and write to a "Debug" console or a log file. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
var params:Object = LoaderInfo(this.root.loaderInfo).parameters;
var rName:String = String(params["reportName"]);
var rFile:File = new File("/usr/local/apfr/reports/" + rName);
...
rFile.deleteFile();
.txt
.
var fs:FileStream = new FileStream();
fs.open(new File(String(configStream.readObject())+".txt"), FileMode.READ);
fs.readBytes(arr);
trace(arr);
public class MyController {
...
public PageRerference loadRes() {
PageReference ref = ApexPages.currentPage();
Map<String,String> params = ref.getParameters();
if (params.containsKey('resName')) {
if (params.containsKey('resPath')) {
return PageReference.forResource(params.get('resName'), params.get('resPath'));
}
}
return null;
}
}
..\\..\\Windows\\System32\\krnl386.exe
", which will cause the application to delete an important Windows system file.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension ".txt".
String rName = Request.Item("reportName");
...
File.delete("C:\\users\\reports\\" + rName);
sr = new StreamReader(resmngr.GetString("sub")+".txt");
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
../../apache/conf/httpd.conf
", which will cause the application to delete the specified configuration file.Example 2: The following code uses input from the command line to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can create soft links to the file, they can use the program to read the first part of any file on the system.
char* rName = getenv("reportName");
...
unlink(rName);
ifstream ifs(argv[0]);
string s;
ifs >> s;
cout << s;
...
EXEC CICS
WEB READ
FORMFIELD(FILE)
VALUE(FILENAME)
...
END-EXEC.
EXEC CICS
READ
FILE(FILENAME)
INTO(RECORD)
RIDFLD(ACCTNO)
UPDATE
...
END-EXEC.
...
..\\..\\Windows\\System32\\krnl386.exe
", which will cause the application to delete an important Windows system file.
<cffile action = "delete"
file = "C:\\users\\reports\\#Form.reportName#">
final server = await HttpServer.bind('localhost', 18081);
server.listen((request) async {
final headers = request.headers;
final path = headers.value('path');
File(path!).delete();
}
Example 1
, there is no validation of headers.value('path')
prior to performing delete functions on files.../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
rName := "/usr/local/apfr/reports/" + req.FormValue("fName")
rFile, err := os.OpenFile(rName, os.O_RDWR|os.O_CREATE, 0755)
defer os.Remove(rName);
defer rFile.Close()
...
.txt
.
...
config := ReadConfigFile()
filename := config.fName + ".txt";
data, err := ioutil.ReadFile(filename)
...
fmt.Println(string(data))
../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
String rName = request.getParameter("reportName");
File rFile = new File("/usr/local/apfr/reports/" + rName);
...
rFile.delete();
.txt
.
fis = new FileInputStream(cfg.getProperty("sub")+".txt");
amt = fis.read(arr);
out.println(arr);
Example 1
to the Android platform.
...
String rName = this.getIntent().getExtras().getString("reportName");
File rFile = getBaseContext().getFileStreamPath(rName);
...
rFile.delete();
...
../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from the local storage to determine which file to open and echo back to the user. If malicious users can change the contents of the local storage, they can use the program to read any file on the system that ends with the extension
...
var reportNameParam = "reportName=";
var reportIndex = document.indexOf(reportNameParam);
if (reportIndex < 0) return;
var rName = document.URL.substring(reportIndex+reportNameParam.length);
window.requestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {
fs.root.getFile('/usr/local/apfr/reports/' + rName, {create: false}, function(fileEntry) {
fileEntry.remove(function() {
console.log('File removed.');
}, errorHandler);
}, errorHandler);
}, errorHandler);
.txt
.
...
var filename = localStorage.sub + '.txt';
function oninit(fs) {
fs.root.getFile(filename, {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var txtArea = document.createElement('textarea');
txtArea.value = this.result;
document.body.appendChild(txtArea);
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.TEMPORARY, 1024*1024, oninit, errorHandler);
...
../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
val rName: String = request.getParameter("reportName")
val rFile = File("/usr/local/apfr/reports/$rName")
...
rFile.delete()
.txt
.
fis = FileInputStream(cfg.getProperty("sub").toString() + ".txt")
amt = fis.read(arr)
out.println(arr)
Example 1
to the Android platform.
...
val rName: String = getIntent().getExtras().getString("reportName")
val rFile: File = getBaseContext().getFileStreamPath(rName)
...
rFile.delete()
...
- (NSData*) testFileManager {
NSString *rootfolder = @"/Documents/";
NSString *filePath = [rootfolder stringByAppendingString:[fileName text]];
NSFileManager *fm = [NSFileManager defaultManager];
return [fm contentsAtPath:filePath];
}
../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
$rName = $_GET['reportName'];
$rFile = fopen("/usr/local/apfr/reports/" . rName,"a+");
...
unlink($rFile);
.txt
.
...
$filename = $CONFIG_TXT['sub'] . ".txt";
$handle = fopen($filename,"r");
$amt = fread($handle, filesize($filename));
echo $amt;
...
../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
rName = req.field('reportName')
rFile = os.open("/usr/local/apfr/reports/" + rName)
...
os.unlink(rFile);
.txt
.
...
filename = CONFIG_TXT['sub'] + ".txt";
handle = os.open(filename)
print handle
...
../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
rName = req['reportName']
File.delete("/usr/local/apfr/reports/#{rName}")
.txt
.
...
fis = File.new("#{cfg.getProperty("sub")}.txt")
amt = fis.read
puts amt
../../tomcat/conf/server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
def readFile(reportName: String) = Action { request =>
val rFile = new File("/usr/local/apfr/reports/" + reportName)
...
rFile.delete()
}
.txt
.
val fis = new FileInputStream(cfg.getProperty("sub")+".txt")
val amt = fis.read(arr)
out.println(arr)
func testFileManager() -> NSData {
let filePath : String = "/Documents/\(fileName.text)"
let fm : NSFileManager = NSFileManager.defaultManager()
return fm.contentsAtPath(filePath)
}
..\conf\server.xml
", which causes the application to delete one of its own configuration files.Example 2: The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with adequate privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension
Dim rName As String
Dim fso As New FileSystemObject
Dim rFile as File
Set rName = Request.Form("reportName")
Set rFile = fso.GetFile("C:\reports\" & rName)
...
fso.DeleteFile("C:\reports\" & rName)
...
.txt
.
Dim fileName As String
Dim tsContent As String
Dim ts As TextStream
Dim fso As New FileSystemObject
fileName = GetPrivateProfileString("MyApp", "sub", _
"", value, Len(value), _
App.Path & "\" & "Config.ini")
...
Set ts = fso.OpenTextFile(fileName,1)
tsContent = ts.ReadAll
Response.Write tsContent
...
public static void UnzipFile(ZipArchive archive, string destDirectory)
{
foreach (var entry in archive.Entries)
{
string file = entry.FullName;
if (!string.IsNullOrEmpty(file))
{
string destFileName = Path.Combine(destDirectory, file);
entry.ExtractToFile(destFileName, true);
}
}
}
Example 1
, there is no validation of entry.FullName
prior to performing read/write operations on the data within this entry. If the Zip file was originally placed in the directory "C:\TEMP
", a Zip entry name contained "..\
segments", and the application was run under the necessary permissions, it could arbitrarily overwrite system files.
func Unzip(src string, dest string) ([]string, error) {
var filenames []string
r, err := zip.OpenReader(src)
if err != nil {
return filenames, err
}
defer r.Close()
for _, f := range r.File {
// Store filename/path for returning and using later on
fpath := filepath.Join(dest, f.Name)
filenames = append(filenames, fpath)
if f.FileInfo().IsDir() {
// Make Folder
os.MkdirAll(fpath, os.ModePerm)
continue
}
// Make File
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return filenames, err
}
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return filenames, err
}
rc, err := f.Open()
if err != nil {
return filenames, err
}
_, err = io.Copy(outFile, rc)
// Close the file without defer to close before next iteration of loop
outFile.Close()
rc.Close()
if err != nil {
return filenames, err
}
}
return filenames, nil
}
Example 1
, there is no validation of f.Name
prior to performing read/write functions on the data within this entry. If the Zip file was originally placed in the directory "/tmp/
" of a Unix-based machine, a Zip entry was "../etc/hosts
", and the application was run under the necessary permissions, it would overwrite the system hosts
file. This in turn would allow traffic from the machine to go anywhere the attacker wants, such as back to the attacker's machine.
private static final int BUFSIZE = 512;
private static final int TOOBIG = 0x640000;
...
public final void unzip(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry zipEntry = null;
int numOfEntries = 0;
long total = 0;
try {
while ((zipEntry = zis.getNextEntry()) != null) {
byte data[] = new byte[BUFSIZE];
int count = 0;
String outFileName = zipEntry.getName();
if (zipEntry.isDirectory()){
new File(outFileName).mkdir(); //create the new directory
continue;
}
FileOutputStream outFile = new FileOutputStream(outFileName);
BufferedOutputStream dest = new BufferedOutputStream(outFile, BUFSIZE);
//read data from Zip, but do not read huge entries
while (total + BUFSIZE <= TOOBIG && (count = zis.read(data, 0, BUFSIZE)) != -1) {
dest.write(data, 0, count);
total += count;
}
...
}
} finally{
zis.close();
}
}
...
Example 1
, there is no validation of zipEntry.getName()
prior to performing read/write functions on the data within this entry. If the Zip file was originally placed in the directory "/tmp/
" of a Unix-based machine, a Zip entry was "../etc/hosts
", and the application was run under the necessary permissions, it would overwrite the system hosts
file. This in turn would allow traffic from the machine to go anywhere the attacker wants, such as back to the attacker's machine.
var unzipper = require('unzipper');
var fs = require('fs');
var untrusted_zip = getZipFromRequest();
fs.createReadStream(zipPath).pipe(unzipper.Extract({ path: 'out' }));
ZZArchive* archive = [ZZArchive archiveWithURL:[NSURL fileURLWithPath: zipPath] error:&error];
for (ZZArchiveEntry* entry in archive.entries) {
NSString *fullPath = [NSString stringWithFormat: @"%@/%@", destPath, [entry fileName]];
[[entry newDataWithError:nil] writeToFile:newFullPath atomically:YES];
}
Example 1
, there is no validation of entry.fileName
prior to performing read/write functions on the data within this entry. If the Zip file was originally placed in the directory "Documents/hot_patches
" of an iOS application, a Zip entry was "../js/page.js
", it would overwrite the page.js
file. This in turn would enable an attacker to inject malicious code that might result in code execution.
...
$zip = new ZipArchive();
$zip->open("userdefined.zip", ZipArchive::RDONLY);
$zpm = $zip->getNameIndex(0);
$zip->extractTo($zpm);
...
Example 1
, there is no validation of f.Name
before performing read/write functions on the data within this entry. If the Zip file is in the directory "/tmp/
" of a Unix-based machine, a Zip entry is "../etc/hosts
", and the application is run under the necessary permissions, it will overwrite the system hosts
file. This allows traffic from the machine to go anywhere the attacker wants, such as back to the attacker's machine.
import zipfile
import tarfile
def unzip(archive_name):
zf = zipfile.ZipFile(archive_name)
zf.extractall(".")
zf.close()
def untar(archive_name):
tf = tarfile.TarFile(archive_name)
tf.extractall(".")
tf.close()
Example 2: The following example extracts files from a Zip file and insecurely writes them to disk.
import better.files._
...
val zipPath: File = getUntrustedZip()
val destinationPath = file"out/dest"
zipPath.unzipTo(destination = destinationPath)
import better.files._
...
val zipPath: File = getUntrustedZip()
val destinationPath = file"out/dest"
zipPath.newZipInputStream.mapEntries( (entry : ZipEntry) => {
entry.extractTo(destinationPath, new FileInputStream(entry.getName))
})
Example 2
, there is no validation of entry.getName
prior to performing read/write functions on the data within this entry. If the Zip file was originally placed in the directory "/tmp/
" of a Unix-based machine, a Zip entry was "../etc/hosts
", and the application was run under the necessary permissions, it would overwrite the system hosts
file. This in turn would allow traffic from the machine to go anywhere the attacker wants, such as back to the attacker's machine.
let archive = try ZZArchive.init(url: URL(fileURLWithPath: zipPath))
for entry in archive.entries {
let fullPath = URL(fileURLWithPath: destPath + "/" + entry.fileName)
try entry.newData().write(to: fullPath)
}
Example 1
, there is no validation of entry.fileName
prior to performing read/write functions on the data within this entry. If the Zip file was originally placed in the directory "Documents/hot_patches
" of an iOS application, a Zip entry was "../js/page.js
", it would overwrite the page.js
file. This in turn would enable an attacker to inject malicious code that might result in code execution.
...
uid = 'scott'.
password = 'tiger'.
WRITE: / 'Default username for FTP connection is: ', uid.
WRITE: / 'Default password for FTP connection is: ', password.
...
pass = getPassword();
...
trace(id+":"+pass+":"+type+":"+tstamp);
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
...
ResetPasswordResult passRes = System.resetPassword(id1, true);
System.Debug('New password: '+passRes.getPassword());
...
pass = GetPassword();
...
dbmsLog.WriteLine(id+":"+pass+":"+type+":"+tstamp);
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.get_password()
function returns the user-supplied plain text password associated with the account.
pass = get_password();
...
fprintf(dbms_log, "%d:%s:%s:%s", id, pass, type, tstamp);
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for any and all data, it should not be trusted implicitly, particularly when privacy is a concern.
...
MOVE "scott" TO UID.
MOVE "tiger" TO PASSWORD.
DISPLAY "Default username for database connection is: ", UID.
DISPLAY "Default password for database connection is: ", PASSWORD.
...
Session.pword
variable contains the plain text password associated with the account.
<cflog file="app_log" application="No" Thread="No"
text="#Session.uname#:#Session.pword#:#type#:#Now()#">
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
var pass = getPassword();
...
dbmsLog.println(id+":"+pass+":"+type+":"+tstamp);
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.GetPassword()
function, which returns user-supplied plain text password associated with the account.
pass = GetPassword();
...
if err != nil {
log.Printf('%s: %s %s %s', id, pass, type, tsstamp)
}
Example 1
logs a plain text password to the application eventlog. Although many developers trust the eventlog as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
pass = getPassword();
...
dbmsLog.println(id+":"+pass+":"+type+":"+tstamp);
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
...
webview.setWebViewClient(new WebViewClient() {
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
String username = credentials[0];
String password = credentials[1];
Intent i = new Intent();
i.setAction("SEND_CREDENTIALS");
i.putExtra("username", username);
i.putExtra("password", password);
view.getContext().sendBroadcast(i);
}
});
...
SEND_CREDENTIALS
action will receive the message. The broadcast is not even protected with a permission to limit the number of recipients, although in this case we do not recommend using permissions as a fix.
localStorage.setItem('password', password);
pass = getPassword()
...
dbmsLog.println("$id:$pass:$type:$tstamp")
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
...
webview.webViewClient = object : WebViewClient() {
override fun onReceivedHttpAuthRequest(view: WebView,
handler: HttpAuthHandler, host: String, realm: String
) {
val credentials = view.getHttpAuthUsernamePassword(host, realm)
val username = credentials!![0]
val password = credentials[1]
val i = Intent()
i.action = "SEND_CREDENTIALS"
i.putExtra("username", username)
i.putExtra("password", password)
view.context.sendBroadcast(i)
}
}
...
SEND_CREDENTIALS
action will receive the message. The broadcast is not even protected with a permission to limit the number of recipients, although in this case we do not recommend using permissions as a fix.
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
NSLog(@"dLatitude : %@", latitude);
NSLog(@"dLongitude : %@",longitude);
NSString *urlWithParams = [NSString stringWithFormat:TOKEN_URL, latitude, longitude];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlWithParams]];
[request setHTTPMethod:@"GET"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Add password to user defaults
[defaults setObject:@"Super Secret" forKey:@"passwd"];
[defaults synchronize];
getPassword()
function that returns user-supplied plain text password associated with the account.
<?php
$pass = getPassword();
trigger_error($id . ":" . $pass . ":" . $type . ":" . $tstamp);
?>
Example 1
logs a plain text password to the application eventlog. Although many developers trust the eventlog as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.OWA_SEC.get_password()
function returns the user-supplied plain text password associated with the account, which is then printed to the HTTP response.
...
HTP.htmlOpen;
HTP.headOpen;
HTP.title (.Account Information.);
HTP.headClose;
HTP.bodyOpen;
HTP.br;
HTP.print('User ID: ' ||
OWA_SEC.get_user_id || '');
HTP.print('User Password: ' ||
OWA_SEC.get_password || '');
HTP.br;
HTP.bodyClose;
HTP.htmlClose;
...
getPassword()
function that returns user-supplied plain text password associated with the account.
pass = getPassword();
logger.warning('%s: %s %s %s', id, pass, type, tsstamp)
Example 1
logs a plain text password to the application eventlog. Although many developers trust the eventlog as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.get_password()
function returns the user-supplied plain text password associated with the account.
pass = get_password()
...
dbms_logger.warn("#{id}:#{pass}:#{type}:#{tstamp}")
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
val pass = getPassword()
...
dbmsLog.println(id+":"+pass+":"+type+":"+tstamp)
Example 1
logs a plain text password to the file system. Although many developers trust the file system as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
import CoreLocation
...
var locationManager : CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.locationServicesEnabled
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
...
if let location: CLLocation! = locationManager.location {
var coordinate : CLLocationCoordinate2D = location.coordinate
let latitude = NSString(format:@"%f", coordinate.latitude)
let longitude = NSString(format:@"%f", coordinate.longitude)
NSLog("dLatitude : %@", latitude)
NSLog("dLongitude : %@",longitude)
let urlString : String = "http://myserver.com/?lat=\(latitude)&lon=\(longitude)"
let url : NSURL = NSURL(string:urlString)
let request : NSURLRequest = NSURLRequest(URL:url)
var err : NSError?
var response : NSURLResponse?
var data : NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error:&err)
} else {
println("no location...")
}
let defaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
// Add password to user defaults
defaults.setObject("Super Secret" forKey:"passwd")
defaults.synchronize()
getPassword
function returns the user-supplied plain text password associated with the account.
pass = getPassword
...
App.EventLog id & ":" & pass & ":" & type & ":" &tstamp, 4
...
Example 1
logs a plain text password to the application eventlog. Although many developers trust the eventlog as a safe storage location for data, it should not be trusted implicitly, particularly when privacy is a concern.
...
host_name = request->get_form_field( 'host' ).
CALL FUNCTION 'FTP_CONNECT'
EXPORTING
USER = user
PASSWORD = password
HOST = host_name
RFC_DESTINATION = 'SAPFTP'
IMPORTING
HANDLE = mi_handle
EXCEPTIONS
NOT_CONNECTED = 1
OTHERS = 2.
...
int rPort = Int32.Parse(Request.Item("rPort"));
...
IPEndPoint endpoint = new IPEndPoint(address,rPort);
socket = new Socket(endpoint.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
socket.Connect(endpoint);
...
...
char* rPort = getenv("rPort");
...
serv_addr.sin_port = htons(atoi(rPort));
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
...
...
ACCEPT QNAME.
EXEC CICS
READQ TD
QUEUE(QNAME)
INTO(DATA)
LENGTH(LDATA)
END-EXEC.
...
ServerSocket
object and uses a port number read from an HTTP request to create a socket.
<cfobject action="create" type="java" class="java.net.ServerSocket" name="myObj">
<cfset srvr = myObj.init(#url.port#)>
<cfset socket = srvr.accept()>
Passing user input to objects imported from other languages can be very dangerous.
final server = await HttpServer.bind('localhost', 18081);
server.listen((request) async {
final remotePort = headers.value('port');
final serverSocket = await ServerSocket.bind(host, remotePort as int);
final httpServer = HttpServer.listenOn(serverSocket);
});
...
func someHandler(w http.ResponseWriter, r *http.Request){
r.parseForm()
deviceName := r.FormValue("device")
...
syscall.BindToDevice(fd, deviceName)
}
String remotePort = request.getParameter("remotePort");
...
ServerSocket srvr = new ServerSocket(remotePort);
Socket skt = srvr.accept();
...
WebView
.
...
WebView webview = new WebView(this);
setContentView(webview);
String url = this.getIntent().getExtras().getString("url");
webview.loadUrl(url);
...
var socket = new WebSocket(document.URL.indexOf("url=")+20);
...
char* rHost = getenv("host");
...
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)rHost, 80, &readStream, &writeStream);
...
<?php
$host=$_GET['host'];
$dbconn = pg_connect("host=$host port=1234 dbname=ticketdb");
...
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM pricelist WHERE name = $1');
$result = pg_execute($dbconn, "my_query", array("ticket"));
?>
...
filename := SUBSTR(OWA_UTIL.get_cgi_env('PATH_INFO'), 2);
WPG_DOCLOAD.download_file(filename);
...
host=request.GET['host']
dbconn = db.connect(host=host, port=1234, dbname=ticketdb)
c = dbconn.cursor()
...
result = c.execute('SELECT * FROM pricelist')
...
def controllerMethod = Action { request =>
val result = request.getQueryString("key").map { key =>
val user = db.getUser()
cache.set(key, user)
Ok("Cached Request")
}
Ok("Done")
}
...
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
var inputStream : NSInputStream?
var outputStream : NSOutputStream?
...
var readStream : Unmanaged<CFReadStream>?
var writeStream : Unmanaged<CFWriteStream>?
let rHost = getQueryStringParameter(url.absoluteString, "host")
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, rHost, 80, &readStream, &writeStream);
...
}
func getQueryStringParameter(url: String?, param: String) -> String? {
if let url = url, urlComponents = NSURLComponents(string: url), queryItems = (urlComponents.queryItems as? [NSURLQueryItem]) {
return queryItems.filter({ (item) in item.name == param }).first?.value!
}
return nil
}
...
...
Begin MSWinsockLib.Winsock tcpServer
...
Dim Response As Response
Dim Request As Request
Dim Session As Session
Dim Application As Application
Dim Server As Server
Dim Port As Variant
Set Response = objContext("Response")
Set Request = objContext("Request")
Set Session = objContext("Session")
Set Application = objContext("Application")
Set Server = objContext("Server")
Set Port = Request.Form("port")
...
tcpServer.LocalPort = Port
tcpServer.Accept
...