By extending the abstract class java.lang.SecurityManager, you can specify a security policy for the current Java program.
Any code loaded over the Internet by your program is then subject to that policy, for example.
A Java program has only one SecurityManager. You can look up the current SecurityManager by calling System.getSecurityManager(). This method returns null to indicate that the default security policy is being used.
The default policy is rather lax. However, you can install a custom security manager. This allows you to do the following, among other things:
- Prevent Java code from deleting, writing, or reading certain files.
- Monitor or disallow certain socket connections.
- Control which Threads may access which other Threads or ThreadGroups.
- Control access to packages, and to system properties.
For example, the method call that checks whether the calling code is allowed to delete a certain file is declared:
public void checkDelete( String file );
The method must either return quietly, or throw a SecurityException. This is typical of the public methods in class SecurityManager.
To provide a custom security manager, write a subclass of SecurityManager and override some of its check methods. Although the SecurityManager class is abstract, none of its methods are abstract.
You still want to override a fair number of them, though, since the check methods inherited from SecurityManager always throw a SecurityException. You don't have to call on these methods yourself for the security manager to be effective.
Once the security manager is installed, various library methods call on it to check for security clearance. To install your SecurityManager, create an instance of it, and call System.setSecurityManager().
Here is a little program (SMDemo.java) that demonstrates how to use a custom security manager. You should create files named DELETEME and KEEPME before running the program:
import java.io.File;
class MySecurityManager extends SecurityManager
{
public void checkDelete( String file )
{
// Only allow the file "DELETEME" to be deleted.
if ( !file.equals( "c:\\DELETEME.txt" ) )
throw new SecurityException( "cannot delete: " + file );
}
// Override many more checkXXX() methods here...
}
public class SMDemo
{
public static void main( String argv[] )
{
MySecurityManager m = new MySecurityManager();
File deleteme = new File("c:\\DELETEME.txt" );
File keepme = new File("c:\\KEEPME.txt" );
System.setSecurityManager( m );
deleteme.delete(); // Should be OK.
keepme.delete(); // Should get a SecurityException.
System.exit(0);
}
}
After you execute the program, you should see that the file DELETEME is gone and the KEEPME file is still there, the program having triggered a SecurityException upon trying to delete it.