Description
When everyone can write to a configuration file, token or key file, or allow-list, other users can change what the application reads.
Potential impact
Altered settings can bypass access controls or change application behavior. Empty or invalid data can interrupt the service.
Remediation
- On POSIX file systems, pass attributes such as
rw-------toFiles.createFileorFiles.createTempFileto restrict access at creation. If several users must write, grant access to the required group or ACL entries only. - Before reading an existing file, verify its owner, effective permissions and contents. Validate or replace untrusted content.
File.setWritable(true, true)alone leaves existing group or other-user write access in place. Stop if a required permission change fails. - Keep sensitive files in directories only the owner can modify. Use options that avoid following symbolic links where needed.
Examples
Before
java
import java.io.*;
import java.nio.file.*;
public class InsecureConfigReader {
// 취약: 월드 쓰기 후 같은 파일을 신뢰하고 읽음
public static String loadApiToken() throws Exception {
File f = new File("/var/app/config/token.txt");
if (!f.exists()) {
f.getParentFile().mkdirs();
f.createNewFile();
}
// 잘못된 권한: 모든 사용자에게 쓰기 허용
f.setWritable(true, false); // world-writable
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
return br.readLine(); // 공격자가 바꾼 내용을 그대로 신뢰
}
}
}
After
java
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Set;
public class SecureConfigReader {
public static String loadApiToken() throws Exception {
Path path = Paths.get("/var/app/config/token.txt");
Files.createDirectories(path.getParent());
// 1) POSIX 권한을 소유자 전용으로 강제 (rw-------)
Set<PosixFilePermission> ownerOnly = PosixFilePermissions.fromString("rw-------");
if (Files.notExists(path)) {
Files.createFile(path, PosixFilePermissions.asFileAttribute(ownerOnly));
} else {
// 기존 파일이라면 Others/Group 쓰기 제거
Files.setPosixFilePermissions(path, ownerOnly);
}
// 2) 추가 방어: JVM File API로도 world write 제거 후, 소유자 쓰기만 허용
File f = path.toFile();
f.setWritable(false, false); // group/others 쓰기 제거
f.setWritable(true, true); // owner만 쓰기 허용
try (BufferedReader br = Files.newBufferedReader(path)) {
return br.readLine();
}
}
}
The example sets POSIX mode rw------- and assumes a trusted owner and parent directory. If you rely on the two final setWritable calls, check that both return true before reading. Tightening permissions cannot restore altered contents.