...
Each Java class runs in its appropriate domain, as determined by its code source. For any code running under a security manager to perform a secured action such as reading or writing a file, the code must be granted permission to perform that particular action. Privileged code can access privileged resources on behalf of an unprivileged caller by using the AccessController.doPrivileged() method. This is necessary, for example, when a system utility needs to open a font file on behalf of the user to display a document, but the application lacks permission to do so. To perform this action, the system utility uses its full privileges for obtaining the fonts, ignoring the privileges of the caller. Privileged code runs with all the privileges of the protection domain associated with the code source. These privileges often exceed those required to perform the privileged operation. Ideally, code should be granted only the minimum set of privileges required to complete its operation.
19SEC53-J. Define custom security permissions for fine-grained security describes another approach to eliminating excess privileges.
Noncompliant Code Example
This noncompliant code example shows a library method that allows callers to perform a privileged operation (reading a file) using the wrapper method performActionOnFile():
...
In this example, the trusted code grants privileges beyond those required to read a file, even though read access to the file was the only permission needed by the doPrivileged() block. Consequently, this code violates the principle of least privilege by providing the code block with superfluous privileges.
Compliant Solution
The two-argument form of doPrivileged() accepts an AccessControlContext object from the caller and restricts the privileges of the contained code to the intersection of privileges of the protection domain and those of the context passed as the second argument. Consequently, a caller that wishes to grant only permission to read the file can provide a context that has only the file-reading permissions.
...
Callers that lack permission to create an appropriate AccessControlContext can request one using AccessController.getContext() to create the instance.
Applicability
Failure to follow the principle of least privilege can result in untrusted, unprivileged code performing unintended privileged operations. However, carefully restricting privileges adds complexity. This added complexity and the associated reduction of maintainability must be traded off against any security improvement.
Bibliography
...