How to check if a file is owned by the current user in Java?

271 Views Asked by At

I want to show a warning if a file is read that is not owned by the user that started the JVM.

In my application, this file can make the program write arbitrary files. So I want to reduce the risk of a privilege escalation attack, if an admin processes this file.

Files.getOwner(path)

retruns a UserPrincipal that represents the file owner. But I can't find a platform independent way to check if this UserPrincipal matches the current user.

I could use

System.getProperty("user.name")

to get the current user and try to match the names. But these properties can be manipulated and this doesn't work if the file owner is a group, for example.

2

There are 2 best solutions below

1
queeg On BEST ANSWER

If you can reliably tell the owner of a file but not the owner of the process we could combine those two: create a temporary file, get the owner and remove the file again.

File tempFile = File.createTempFile("MyAppName-", ".tmp");
UserPrincipal u = Files.getOwner(tempFile.toPath());
tempFile.deleteOnExit();
tempFile.delete();

// UserPrincipal u will contain the current process user.
2
queeg On

If you already have a principal of the file owner, the question would remain how to reliably get the current user running the application.

Maybe this solution can help? However it seems to make use of Sprint security: https://www.javaguides.net/2019/06/spring-security-get-current-logged-in-user-details.html

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();

// getUsername() - Returns the username used to authenticate the user.
System.out.println("User name: " + userDetails.getUsername());

// getAuthorities() - Returns the authorities granted to the user.
System.out.println("User has authorities: " + userDetails.getAuthorities());