EVP_DecryptUpdate
, which will result in a failure to decrypt the ciphertext.
...
EVP_DecryptInit_ex(&ctx, EVP_aes_256_gcm(), NULL, key, iv);
...
if(!EVP_DecryptFinal_ex(&ctx, outBuf+outBytes, &tmpOutBytes))
prtErrAndExit(1, "ERROR: EVP_DecryptFinal_ex did not work...\n");
...
KeyGenerator
, possibly resulting in the use of a smaller than recommended key:
...
final String CIPHER_INPUT = "123456ABCDEFG";
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecretKey secretKey = keyGenerator.generateKey();
byte[] byteKey = secretKey.getEncoded();
....
OpenSSL::Cipher#update
, which will result in a failure to decrypt the ciphertext:
require 'openssl'
...
decipher = OpenSSL::Cipher::AES.new(128, :GCM)
decipher.decrypt
decipher.key = key
decipher.iv = iv
plain = decipher.final #missed update method
...
SLComposeServiceViewController isContentValid
to validate the untrusted data received before using it.
#import <MobileCoreServices/MobileCoreServices.h>
@interface ShareViewController : SLComposeServiceViewController
...
@end
@interface ShareViewController ()
...
@end
@implementation ShareViewController
- (void)didSelectPost {
NSExtensionItem *item = self.extensionContext.inputItems.firstObject;
NSItemProvider *itemProvider = item.attachments.firstObject;
...
// Use the received items
...
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
}
...
@end
SLComposeServiceViewController isContentValid
to validate the untrusted data received before using it.SLComposeServiceViewController isContentValid
callback method to validate it:
import MobileCoreServices
class ShareViewController: SLComposeServiceViewController {
...
override func didSelectPost() {
let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
let itemProvider = extensionItem.attachments?.first as! NSItemProvider
...
// Use the received items
...
self.extensionContext?.completeRequestReturningItems([], completionHandler:nil)
}
...
}
webview
uses a URL to communicate with your application, the receiving application should validate the calling URL before proceeding with further actions. The receiving application has the option to verify that it wants to open the calling URL using the UIApplicationDelegate application:didFinishLaunchingWithOptions:
or UIApplicationDelegate application:willFinishLaunchingWithOptions:
delegate methods.UIApplicationDelegate application:didFinishLaunchingWithOptions:
delegate method fails to validate the calling URL and always processes the untrusted URL:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NS Dictionary *)launchOptions {
return YES;
}
webview
uses a URL to communicate with your application, the receiving application should validate the calling URL before proceeding with further actions. The receiving application has the option to verify that it wants to open the calling URL using the UIApplicationDelegate application:didFinishLaunchingWithOptions:
or UIApplicationDelegate application:willFinishLaunchingWithOptions:
delegate methods.UIApplicationDelegate application:didFinishLaunchingWithOptions:
delegate method fails to validate the calling URL and always processes the untrusted URL:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
static public byte[] EncryptWithRSA(byte[] plaintext, RSAParameters key) {
try {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512);
rsa.ImportParameters(key);
return rsa.Encrypt(plaintext, true);
}
catch(CryptographicException e) {
Console.WriteLine(e.Message);
return null;
}
}
EVP_PKEY * get_RSA_key() {
unsigned long err;
EVP_PKEY * pkey;
RSA * rsa;
rsa = RSA_generate_key(512, 35, NULL, NULL);
if (rsa == NULL) {
err = ERR_get_error();
printf("Error = %s\n",ERR_reason_error_string(err));
return NULL;
}
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
return pkey;
}
...
myPrivateKey := rsa.GenerateKey(rand.Reader, 1024);
...
public static KeyPair getRSAKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair key = keyGen.generateKeyPair();
return key;
}
...
crmfObject = crypto.generateCRMFRequest(
"CN=" + name.value,
password.value,
authenticator,
keyTransportCert,
"setCRMFRequest();",
512, null, "rsa-dual-use");
...
...
CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
key,
kCCKeySizeDES, // 64-bit key size
iv,
plaintext,
sizeof(plaintext),
ciphertext,
sizeof(ciphertext),
&numBytesEncrypted);
...
...
$keysize = 1024;
$options = array('private_key_bits' => $keysize, 'private_key_type' => OPENSSL_KEYTYPE_RSA);
$res = openssl_pkey_new($options);
...
...
from Crypto.PublicKey import RSA
key = RSA.generate(1024)
...
require 'openssl'
...
pkey = OpenSSL::PKey::RSA.new 1024
...
...
let iv = getTrueRandomIV()
...
let cStatus = CCCrypt(UInt32(kCCEncrypt),
UInt32(kCCAlgorithmDES),
UInt32(kCCOptionPKCS7Padding),
key,
UInt32(kCCKeySizeDES), // 64-bit key size
iv,
plaintext,
plaintextLength,
ciphertext,
ciphertextLength,
&numBytesEncrypted)
...
root
privileges have caused innumerable Unix security disasters. It is imperative that you carefully review privileged programs for all kinds of security problems, but it is equally important that privileged programs drop back to an unprivileged state as quickly as possible in order to limit the amount of damage that an overlooked vulnerability might be able to cause.root
user to another.root
when a signal fires or a sub-process is executed, the signal handler or sub-process will operate with root privileges. An attacker may be able to leverage these elevated privileges to do further damage.root
privileges have caused innumerable Unix security disasters. It is imperative that you carefully review privileged programs for all kinds of security problems, but it is equally important that privileged programs drop back to an unprivileged state as quickly as possible in order to limit the amount of damage that an overlooked vulnerability might cause.root
user to another.root
when a signal fires or a sub-process is executed, the signal handler or sub-process will operate with root privileges. An attacker might be able to leverage these elevated privileges to do further damage.root
privileges have caused innumerable Unix security disasters. It is imperative that you carefully review privileged programs for all kinds of security problems, but it is equally important that privileged programs drop back to an unprivileged state as quickly as possible in order to limit the amount of damage that an overlooked vulnerability might be able to cause.root
user to another.root
when a signal fires or a sub-process is executed, the signal handler or sub-process will operate with root privileges. An attacker may be able to leverage these elevated privileges to do further damage.root
privileges have caused innumerable Unix security disasters. It is imperative that you carefully review privileged programs for all kinds of security problems, but it is equally important that privileged programs drop back to an unprivileged state as quickly as possible in order to limit the amount of damage that an overlooked vulnerability might be able to cause.root
user to another.root
when a signal fires or a sub-process is executed, the signal handler or sub-process will operate with root privileges. An attacker may be able to leverage these elevated privileges to do further damage.
NSData *imageData = [NSData dataWithContentsOfFile:file];
CC_MD5(imageData, [imageData length], result);
let encodedText = text.cStringUsingEncoding(NSUTF8StringEncoding)
let textLength = CC_LONG(text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLength = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
CC_MD5(encodedText, textLength, result)
...
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.
...
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
String 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.
...
webview.setWebViewClient(new WebViewClient() {
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
String username = new String(Base64.decode(credentials[0], DEFAULT));
String password = new String(Base64.decode(credentials[1], DEFAULT));
handler.proceed(username, password);
}
});
...
...
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.serve
view of the static files
application which is not designed to be deployed in a production environment. According to Django documentation:static files
tools are mostly designed to help with getting static files successfully deployed into production. This usually means a separate, dedicated static file server, which is a lot of overhead to mess with when developing locally. Thus, the staticfiles app ships with a quick and dirty helper view that you can use to serve files locally in development.DEBUG
is True
.setPersistent:YES
.
...
UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:@"myPasteboard" create:YES];
[pasteboard setPersistent:YES];
...
setPersistent(true)
.
...
let pasteboard = UIPasteboard(name: UIPasteboard.Name(rawValue: "myPasteboard"), create: true)!
pasteboard.setPersistent(true)
...
NSURLCredential
which will be distributed to all synchronized devices and stored in Apple's iCloud environment.NSURLCredential
containing the user's credentials in the form or a username/password pair or a client certificate, a persistence attribute needs to be defined. The possible values are:NSURLCredentialPersistenceNone
: Credential should not be stored.NSURLCredentialPersistenceForSession
: Credential should be stored only for this session.NSURLCredentialPersistencePermanent
: Credential should be stored in the Keychain.NSURLCredentialPersistenceSynchronizable
: Credential should be stored permanently in the Keychain, and in addition should be distributed to other devices based on the owning Apple ID.NSURLCredentialPersistenceSynchronizable
attribute implies the distribution of the credential and its storage in the Apple's cloud environment. Depending upon the privacy requirements of the application, storing the credential in the Apple cloud environment may not be acceptable.
...
NSURLCredential *credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceSynchronizable];
NSURLCredentialStorage *shared = [NSURLCredentialStorage sharedCredentialStorage];
[shared setDefaultCredential:credential forProtectionSpace:protectionSpace];
...
NSURLCredential
which will be distributed to all synchronized devices and stored in Apple's iCloud environment.NSURLCredential
containing the user's credentials in the form or a username/password pair or a client certificate, a persistence attribute needs to be defined. The possible values are:NSURLCredentialPersistenceNone
: Credential should not be stored.NSURLCredentialPersistenceForSession
: Credential should be stored only for this session.NSURLCredentialPersistencePermanent
: Credential should be stored in the Keychain.NSURLCredentialPersistenceSynchronizable
: Credential should be stored permanently in the Keychain, and in addition should be distributed to other devices based on the owning Apple ID.NSURLCredentialPersistenceSynchronizable
attribute implies the distribution of the credential and its storage in the Apple's cloud environment. Depending upon the privacy requirements of the application, storing the credential in the Apple cloud environment may not be acceptable.
...
let credential = NSURLCredential(user:foo, password:password, persistence:.Synchronizable)
let shared = NSURLCredentialStorage.sharedCredentialStorage()
shared.setCredential(credential, forProtectionSpace:protectionSpace)
...
NSURLCredential
instance locally but fails to remove the copy stored on other devices and iCloud.NSURLCredential
containing the user's credentials in the form or a username/password pair or a client certificate, a persistence attribute needs to be defined. The possible values are:NSURLCredentialPersistenceNone
: Credential should not be stored.NSURLCredentialPersistenceForSession
: Credential should be stored only for this session.NSURLCredentialPersistencePermanent
: Credential should be stored in the Keychain.NSURLCredentialPersistenceSynchronizable
: Credential should be stored permanently in the Keychain, and in addition should be distributed to other devices based on the owning AppleID.NSURLCredentialPersistenceSynchronizable
credentials are distributed to other devices and iCloud, failing to completely remove the credential from all places will leave instances that could be leaked.
...
// Create the credential
NSURLCredential *credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceSynchronizable];
NSURLCredentialStorage *shared = [NSURLCredentialStorage sharedCredentialStorage];
[shared setDefaultCredential:credential forProtectionSpace:protectionSpace];
// Use the credential as needed
...
// Removes the credential
[shared removeCredential:credential forProtectionSpace:protectionSpace];
...
NSURLCredential
instance locally but fails to remove the copy stored on other devices and iCloud.NSURLCredential
containing the user's credentials in the form or a username/password pair or a client certificate, a persistence attribute needs to be defined. The possible values are:NSURLCredentialPersistenceNone
: Credential should not be stored.NSURLCredentialPersistenceForSession
: Credential should be stored only for this session.NSURLCredentialPersistencePermanent
: Credential should be stored in the Keychain.NSURLCredentialPersistenceSynchronizable
: Credential should be stored permanently in the Keychain, and in addition should be distributed to other devices based on the owning AppleID.NSURLCredentialPersistenceSynchronizable
credentials are distributed to other devices and iCloud, failing to completely remove the credential from all places will leave instances that could be leaked.
...
// Create the credential
let credential = NSURLCredential(user:foo, password:password, persistence:.Synchronizable)
let shared = NSURLCredentialStorage.sharedCredentialStorage()
shared.setCredential(credential, forProtectionSpace:protectionSpace)
// Use the credential as needed
...
// Removes the credential
shared.removeCredential(credential, forProtectionSpace:protectionSpace)
...
Documents
directory without properly masking it first.Documents
directory is intended to store non-transient application data, such as user-created content or local information allowing the app to run in offline mode. If UIFileSharingEnabled
is set in your application's Info.plist
file, files here will be accessible via iTunes. When writing sensitive data to the Documents
directory, the data may be exposed in unencrypted backups or through the iTunes interface.Documents
directory:
...
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *passwd_path = [docsDirectory stringByAppendingPathComponent:@"passwords.txt"];
NSString *password = [user password];
[password writeToFile:passwd_path atomically:YES encoding:NSUTF8StringEncoding error:nil];
...
Documents
directory without properly masking it first.Documents
directory is intended to store non-transient application data, such as user-created content or local information allowing the app to run in offline mode. If UIFileSharingEnabled
is set in your application's Info.plist
file, files here will be accessible via iTunes. When writing sensitive data to the Documents
directory, the data may be exposed in unencrypted backups or through the iTunes interface.Documents
directory:
let documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let passwd_path = NSURL(fileURLWithPath: documents).URLByAppendingPathComponent("secret.txt")
let password = getUserPassword()
try password.writeToURL(passwd_path, atomically:true, encoding: NSUTF8StringEncoding)
$collection->find(array("username" => $_GET['username']))
$collection->find(array("username" => array('$ne' => "foo")))
chroot()
should be dropped immediately after the operation is performed.chroot()
, it must first acquire root
privilege. As soon as the privileged operation has completed, the program should drop root
privilege and return to the privilege level of the invoking user.chroot()
to restrict the application to a subset of the file system below APP_HOME
in order to prevent an attacker from using the program to gain unauthorized access to files located elsewhere. The code then opens a file specified by the user and processes the contents of the file.
...
chroot(APP_HOME);
chdir("/");
FILE* data = fopen(argv[1], "r+");
...
setuid()
with some non-zero value means the application is continuing to operate with unnecessary root
privileges. Any successful exploit carried out by an attacker against the application can now result in a privilege escalation attack because any malicious operations will be performed with the privileges of the superuser. If the application drops to the privilege level of a non-root
user, the potential for damage is substantially reduced.
String canned_acl = request.getParameter("acl");
CreateBucketRequest createBucketRequest = CreateBucketRequest.builder()
.bucket("foo")
.acl(canned_acl)
.createBucketConfiguration(CreateBucketConfiguration.builder().locationConstraint(region.id()).build())
.build();
acl
parameter to be selected from a limited set, an attacker can set it to public-read-write
and grant full anonymous access to the bucket.
<cfquery name = "GetCredentials" dataSource = "master">
SELECT Username, Password
FROM Credentials
WHERE DataSource="users"
</cfquery>
...
<cfquery name = "GetSSNs" dataSource = "users"
username = "#Username#" password = "#Password#">
SELECT SSN
FROM Users
</cfquery>
...
master
can read the value of Username
and Password
. Any devious employee with access to this information can use it to break into the system.localStorage
and sessionStorage
can expose sensitive information unwittingly.localStorage
and sessionStorage
maps to allow developers to persist program values. The sessionStorage
map provides storage for the invoking page and lasts only for the duration of the page instance and the immediate browser session. The localStorage
map, however, provides storage that is accessible over multiple page instances and multiple browser instances. This functionality allows an application to persist and utilize the same information in multiple browser tabs or windows.sessionStorage
scope to the localStorage
or vice versa.sessionStorage
object. However, the developer also stores the information within the localStorage
object.
...
try {
sessionStorage.setItem("userCCV", currentCCV);
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded.');
}
}
...
...
var retrieveObject = sessionStorage.getItem("userCCV");
try {
localStorage.setItem("userCCV",retrieveObject);
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded.');
}
...
var userCCV = localStorage.getItem("userCCV");
...
}
...
localStorage
object, the CCV information is now available in other browser tabs and also on new invocations of the browser. This will by-pass the application logic for the intended workflow.
...
String address = request.getParameter("address");
Properties props = new Properties();
props.put(Provider_URL, "rmi://secure-server:1099/");
InitialContext ctx = new InitialContext(props);
ctx.lookup(address);