Rule: “Make sure publicly writable directories are used safely here.”
Languge: Java (15)
Environment: SonarCloud
The rules suggest the following solution:
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("w+"));
Files.createTempFile("prefix", "suffix", attr); // Compliant, created with explicit attributes.
This solution does not work on java 11 and 15.
Exception:
java.lang.IllegalArgumentException: Invalid mode
at java.base/java.nio.file.attribute.PosixFilePermissions.fromString(PosixFilePermissions.java:128)
So I replaced w+
by rwx------
.
That solves the problem on Linux.
On Windows using the PosixFilePermissions
does, however still not work. (Which is reasonable since windows is not posix-compatible)
Exception:
java.lang.UnsupportedOperationException: 'posix:permissions' not supported as initial attribute
at java.base/sun.nio.fs.WindowsSecurityDescriptor.fromAttribute(WindowsSecurityDescriptor.java:358)
at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:227)
at java.base/java.nio.file.Files.newByteChannel(Files.java:375)
at java.base/java.nio.file.Files.createFile(Files.java:652)
at java.base/java.nio.file.TempFileHelper.create(TempFileHelper.java:137)
at java.base/java.nio.file.TempFileHelper.createTempFile(TempFileHelper.java:160)
at java.base/java.nio.file.Files.createTempFile(Files.java:917)
In my opinion the suggested solution should platform independent.
My suggestion:
final File myFile = Files.createTempFile("prefix", "suffix").toFile();
myFile.setReadable(false); //deny for all
myFile.setWritable(false);
myFile.setExecutable(false);
myFile.setReadable(true, true); //allow for owner
myFile.setWritable(true, true);
myFile.setWritable(true, true); //optional
In contrast to the current suggested solution, this solution uses the platform-independent Java API.
I would suggest changing the suggested solution and change the rule to also accept the above solution.