CWE 276 - Incorrect Default Permissions
About CWE ID 276
Incorrect Default Permissions
This Vulnerability occurs when installed file permissions are set to allow anyone to modify those files. This can lead to confidentiality and integrity violations, as unauthorized actors can read or modify sensitive data or code.
Impact
Unauthorized Access
Data Breach
Privilege Escalation
Malicious File Upload
Denial of Service (DoS)
Example with Code Explanation
Let us consider an example case and understand the CWE-276 with context of Vulnerable code and Mitigated code.
C
C
Vulnerable Code
#include <stdio.h>
int main() {
// Vulnerable code: Incorrect default permissions
FILE *file = fopen("sensitive_data.txt", "w"); // Create or overwrite the file
if (file != NULL) {
// Write some sensitive data to the file
fprintf(file, "This is sensitive data that should not be accessible to all users.");
fclose(file);
printf("File created successfully.\n");
} else {
printf("Error: Unable to create the file.\n");
}
return 0;
}
The Above code is vulnerable since the program attempts to create a file named sensitive_data.txt
and write sensitive information to it. However, the default permissions are not explicitly set, so the file will inherit the default permissions provided by the underlying operating system.
On many systems, the default permissions for a newly created file might be set to allow read
, write
, and execute
access for the owner
of the file, as well as read
and execute
access for all other users
on the system. This means that any user on the system can potentially read the contents of sensitive_data.txt
, even if it was intended to be private and accessible only by specific authorized users.
Some of the ways the Vulnerable code can be mitigated is:
Set Explicit File Permissions: Explicitly set appropriate file permissions when creating the file using the
fopen
function. You can use thechmod
function (on Unix-like systems) or platform-specific functions to set the file permissions explicitly. Restrict access to authorized users only, based on the principle of least privilege.Validate File Paths: Ensure that the file path used to create the file is secure and does not allow path traversal attacks.
Validate and sanitize
user inputs to prevent attackers from specifying arbitrary file paths.Use Safe File Handling Functions: Consider using safer file handling functions to reduce the risk of buffer overflows or other security vulnerabilities. For example, instead of
fprintf
, usefprintf_s
or similar functions where available.Secure File Uploads: If the file is intended to accept user-uploaded content, validate and sanitize the uploaded file to prevent the upload of malicious files. Additionally, store uploaded files in a separate, restricted directory with proper permissions.
Limit Filesystem Access: Run the application with the least necessary privileges to further reduce the impact of any potential file-related vulnerabilities.
Mitigated Code
#include <stdio.h>
#include <sys/stat.h>
#include <openssl/evp.h>
int main() {
// Secure file path for storing sensitive_data.txt
const char* file_path = "/path/to/sensitive_data.txt";
// Secure code: Use mkstemp to create a temporary file with a random name and secure permissions (e.g., 0600)
char tmp_path[] = "/tmp/sensitive_data_XXXXXX";
int fd = mkstemp(tmp_path);
if (fd == -1) {
printf("Error: Unable to create a temporary file.\n");
return 1;
}
// Secure code: Use fdopen to get a FILE pointer from the file descriptor
FILE *file = fdopen(fd, "w");
if (file == NULL) {
printf("Error: Unable to open the temporary file.\n");
close(fd);
return 1;
}
// Write sensitive data to the file
fprintf(file, "This is sensitive data that should not be accessible to all users.");
// Close the file
fclose(file);
// Secure code: Use OpenSSL to encrypt the temporary file with AES-256-CBC and a secret key
unsigned char key[] = "secretkey"; // This should be generated randomly and securely stored
unsigned char iv[] = "initialvector"; // This should be generated randomly and securely stored
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
printf("Error: Unable to create a cipher context.\n");
return 1;
}
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) != 1) {
printf("Error: Unable to initialize encryption.\n");
EVP_CIPHER_CTX_free(ctx);
return 1;
}
FILE *in = fopen(tmp_path, "rb");
if (in == NULL) {
printf("Error: Unable to open the temporary file for reading.\n");
EVP_CIPHER_CTX_free(ctx);
return 1;
}
FILE *out = fopen(file_path, "wb");
if (out == NULL) {
printf("Error: Unable to open the final file for writing.\n");
EVP_CIPHER_CTX_free(ctx);
fclose(in);
return 1;
}
unsigned char inbuf[1024];
unsigned char outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
while ((inlen = fread(inbuf, 1, 1024, in)) > 0) {
if (EVP_EncryptUpdate(ctx, outbuf, &outlen, inbuf, inlen) != 1) {
printf("Error: Unable to encrypt data.\n");
EVP_CIPHER_CTX_free(ctx);
fclose(in);
fclose(out);
return 1;
}
fwrite(outbuf, 1, outlen, out);
}
if (EVP_EncryptFinal_ex(ctx, outbuf, &outlen) != 1) {
printf("Error: Unable to finalize encryption.\n");
EVP_CIPHER_CTX_free(ctx);
fclose(in);
fclose(out);
return 1;
}
fwrite(outbuf, 1, outlen, out);
// Free the cipher context and close the files
EVP_CIPHER_CTX_free(ctx);
fclose(in);
fclose(out);
// Delete the temporary file
remove(tmp_path);
printf("File created and secured successfully.\n");
return 0;
}
The Mitigated code does the following:
Temporary File Creation: The code uses
mkstemp
to create a temporary file with a random name in the "/tmp" directory. Temporary files are usually created with restrictive permissions (e.g., 0600) by default, reducing the risk of unauthorized access.Secure File Handling: The code uses
fdopen
to obtain aFILE
pointer from the file descriptor of the temporary file. This ensures that file operations are performed using the file descriptor, maintaining security throughout the file handling process.Encryption with OpenSSL: The code uses the OpenSSL library to encrypt the sensitive data stored in the temporary file. It employs AES-256-CBC encryption with a secret key and initialization vector (IV) to protect the confidentiality of the data.
Random Key and IV: In a secure implementation, the key and IV should be generated randomly and securely stored. In the provided example, static values ("secretkey" and "initialvector") are used, which is not secure. In a real-world scenario, generate these values securely.
Proper Resource Cleanup: After the encryption process is complete, the code closes the files properly and deletes the temporary file using
remove
. This ensures that no residual sensitive data is left behind.
JAVA
JAVA
Vulnerable Code
import java.io.FileWriter;
import java.io.IOException;
public class IncorrectDefaultPermissionsExample {
public static void main(String[] args) {
// Vulnerable code: Incorrect default permissions
try {
FileWriter fileWriter = new FileWriter("sensitive_data.txt");
fileWriter.write("This is sensitive data that should not be accessible to all users.");
fileWriter.close();
System.out.println("File created successfully.");
} catch (IOException e) {
System.out.println("Error: Unable to create the file.");
e.printStackTrace();
}
}
}
In the above code, the program attempts to create a file named sensitive_data.txt
and write sensitive information to it using a FileWriter
. However, the default permissions
are not explicitly set, so the file will inherit the default permissions provided by the underlying operating system.
Some of the ways the Vulnerable code can be mitigated is:
Follow the Principle of Least Privilege (POLP): Grant the minimum necessary permissions required for a resource or user to perform their intended tasks. Avoid setting excessive permissions, especially for sensitive resources or data.
Sanitize Default Settings: Review default settings for resources like files, directories, and network connections to ensure they are secure by default. Limit access to critical operations and resources.
Implement Strong Authentication: Use strong authentication mechanisms, such as complex passwords or cryptographic keys, to ensure that only authorized users or processes can access resources.
Enforce Proper Access Controls: Implement access control mechanisms to restrict resource access based on user roles, groups, or specific permissions.
Avoid Using Default Credentials: Do not rely on default credentials or passwords provided by frameworks, libraries, or systems. Always change default credentials to unique, strong passwords.
Secure Configuration Management: Ensure that configurations are appropriately managed and monitored to prevent unauthorized changes that might alter default permissions.
Mitigated Code
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
public class CorrectDefaultPermissionsExample {
public static void main(String[] args) {
// Improved code: Correct default permissions
FileWriter fileWriter = null;
try {
// Create a set of permissions for the file
Set<PosixFilePermission> permissions = new HashSet<>();
permissions.add(PosixFilePermission.OWNER_READ); // Read permission for owner
permissions.add(PosixFilePermission.OWNER_WRITE); // Write permission for owner
// Create a temporary file with a random name and the specified permissions
Path tempFile = Files.createTempFile("secret", ".txt", PosixFilePermissions.asFileAttribute(permissions));
// Write some sensitive data to the file
fileWriter = new FileWriter(tempFile.toFile());
fileWriter.write("This is sensitive data that should not be accessible to all users.");
fileWriter.close();
System.out.println("File created successfully.");
} catch (IOException e) {
System.out.println("Error: Unable to create the file.");
e.printStackTrace();
} finally {
// Close and delete the file in case of an error
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (tempFile != null) {
tempFile.toFile().delete();
}
}
}
}
The Mitigated code does the following:
Using
java.nio.file.Files.createTempFile
: The code usesFiles.createTempFile
to create a temporary file with a random name in the default temporary-file directory. The methodcreateTempFile
ensures that the temporary file is created securely with appropriate permissions.Setting Specific File Permissions: The code creates a
Set<PosixFilePermission>
to specify the desired file permissions for the temporary file. In this case, the permissions are set to allow read and write access for the file owner only (OWNER_READ
andOWNER_WRITE
). This restricts access to the sensitive data, ensuring it is accessible only to the creator.Cleaning Up Resources: The code uses a
finally
block to ensure that resources (e.g., theFileWriter
and the temporary file) are properly closed and deleted, even in the event of an exception or error. This helps prevent leaving sensitive data behind and reduces the risk of unauthorized access to the data.Secure File Handling: The code initializes the
FileWriter
only after the temporary file is created successfully. This ensures that the sensitive data is written to the temporary file with the appropriate permissions and not directly to a file with default permissions.
💡 This example uses the **`PosixFilePermission`** class, which is only supported on POSIX-compliant file systems. If you are using a different file system, you may need to use a different class or method to set the file permissions.
PHP
PHP
Vulnerable Code
<?php
// Vulnerable code: Incorrect default permissions
$file = fopen('sensitive_data.txt', 'w');
if ($file) {
fwrite($file, 'This is sensitive data that should not be accessible to all users.');
fclose($file);
echo "File created successfully.";
} else {
echo "Error: Unable to create the file.";
}
?>
In this code, the PHP code attempts to create a file named sensitive_data.txt
and write sensitive information to it using fopen
and fwrite
. However, the default permissions are not explicitly set, so the file will inherit the default permissions provided by the underlying operating system or PHP configuration.
Some o the ways the Vulnerable code can be mitigated is:
Use Directory with Secure Permissions: Consider using a dedicated directory with secure permissions to store sensitive files. Set restrictive permissions on the directory and ensure that only authorized users can access the files within it.
Implement Proper Error Handling: Implement robust error handling to handle any potential failures when creating or accessing files. Avoid exposing detailed error messages to users, as they might aid attackers in understanding the system's configuration.
Utilize Safe Temporary File Handling: If the sensitive data is intended to be temporary, consider using PHP's
tempnam
function to create a temporary file with a unique name and set secure permissions. Remember to clean up temporary files after their use.Explicitly Set File Permissions: Set the appropriate permissions for the file using PHP's
chmod
function. Ensure that the file permissions are restrictive enough to limit access to the file.
Mitigated Code
// Improved code: Correct default permissions
try {
// Generate a random file name
$file_name = uniqid('secret') . '.txt';
// Check if the file already exists
if (file_exists($file_name)) {
throw new Exception("File already exists.");
}
// Create and open the file
$file = fopen($file_name, 'w');
// Write some sensitive data to the file
fwrite($file, 'This is sensitive data that should not be accessible to all users.');
// Close the file
fclose($file);
// Set permissions to read and write for owner only
chmod($file_name, 0600);
echo "File created and secured successfully.";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
// Delete the file in case of an error
if (isset($file) && $file) {
fclose($file);
unlink($file_name);
}
}
The Mitigated code does the following:
Random File Name: The code generates a random file name using
uniqid('secret') . '.txt'
. This helps ensure that the file name is unique and less predictable, reducing the risk of attackers guessing or trying to access sensitive files.File Existence Check: Before creating the file, the code checks if a file with the same name already exists using
file_exists($file_name)
. If the file exists, an exception is thrown, preventing accidental overwriting of existing sensitive data.Secure File Handling: The code uses PHP's
fopen
,fwrite
, andfclose
functions to create, write to, and close the file securely. The file handle is explicitly closed usingfclose
, even if an exception occurs, to release the resources and ensure proper cleanup.Secure File Permissions: The code sets the file permissions explicitly to
0600
usingchmod($file_name, 0600)
, allowing read and write access for the owner only and no permissions for group or others.Exception Handling: The code uses a
try-catch
block to catch any exceptions that might occur during file handling and outputs appropriate error messages. This helps prevent exposing sensitive information and assists with debugging potential issues.
Mitigation
Some common mitigation techniques include:
Principle of Least Privilege: Follow the principle of least privilege when setting file permissions. Give users and processes only the minimum necessary permissions required for their intended functionality, avoiding overly permissive settings.
Explicitly Set Permissions: Always explicitly set file permissions when creating or modifying files. Avoid relying on default permissions provided by the operating system, as they may be too permissive.
Secure Temporary File Handling: If sensitive data needs temporary storage, use dedicated temporary directories with restricted access. Consider using language-specific functions or libraries to create temporary files securely.
Validate and Sanitize User Input: Validate and sanitize user input, especially when it's used to construct file paths or filenames. This helps prevent path traversal and other directory-related attacks.
Check for File Existence: Before creating or overwriting a file, check if the file already exists to avoid accidentally overwriting sensitive data.
Error Handling and Logging: Implement proper error handling and logging mechanisms to catch and handle any exceptions or errors related to file handling. Avoid exposing sensitive information in error messages.
References
Last updated
Was this helpful?