Writing a Security Manager
标签:
securitymanagerit |
分类: Java |
Writing a Security Manager
To write your own security manager, you must create a subclass of the SecurityManager class. Your SecurityManager subclass overrides various methods from SecurityManager to customize the verifications and approvals needed in your Java application.This page walks through an example security manager that restricts reading and writing to the file system. To get approval from the security manager, a method that opens a file for reading invokes one of SecurityManager's
checkRead()methods. Similarly, a method that opens a file for writing invokes one of SecurityManager'scheckWrite()methods. If the security manager approves the operation then thecheckXXX()method returns, otherwisecheckXXX()throws a SecurityException.To impose a stricter policy on file system accesses, our example SecurityManager subclass must override SecurityManager's
checkRead()andcheckWrite()methods. SecurityManager provides three versions ofcheckRead()and two versions ofcheckWrite(). Each of which should verify whether the application is allowed to open a file for I/O. A policy frequently implemented by browsers is that applets loaded over the network cannot read from or write to the local file system unless the user approves it.The policy implemented by our example prompts the user for a password when the application attempts to open a file for reading or for writing. If the password is correct then the access is allowed.
All security managers must be a subclass of SecurityManager. Thus, our
PasswordSecurityManagerhttp://doc.javanb.com/java-Tutorial-5-0-en/images/sourceIcon.gif class extends SecurityManager.Next, PasswordSecurityManager declares a private instance variableclass PasswordSecurityManager extends SecurityManager { . . . }passwordto contain the password that the user must enter in order to allow the restricted file system accesses. The password is set upon construction:The next method in the PasswordSecurityManager class is a private helper method namedPasswordSecurityManager(String password) { super(); this.password = password; }accessOK(). This method prompts the user for a password and verifies it. If the user enters a valid password, the method returns true; otherwise, it returns false.Finally at the end of the PasswordSecurityManager class are the three overriddenprivate boolean accessOK() { int c; DataInputStream dis = new DataInputStream(System.in); String response; System.out.println("What's the secret password?"); try { response = dis.readLine(); if (response.equals(password)) return true; else return false; } catch (IOException e) { return false; } }checkRead()methods and the two overriddencheckWrite()methods:All thepublic void checkRead(FileDescriptor filedescriptor) { if (!accessOK()) throw new SecurityException("Not a Chance!"); } public void checkRead(String filename) { if (!accessOK()) throw new SecurityException("No Way!"); } public void checkRead(String filename, Object executionContext) { if (!accessOK()) throw new SecurityException("Forget It!"); } public void checkWrite(FileDescriptor filedescriptor) { if (!accessOK()) throw new SecurityException("Not!"); } public void checkWrite(String filename) { if (!accessOK()) throw new SecurityException("Not Even!"); }checkXXX()methods callaccessOK()to prompt the user for a password. If access is not OK, thencheckXXX()throws a SecurityException. Otherwise,checkXXX()returns normally. Note that SecurityException is a runtime exception, and as such does not need to be declared in thethrowsclause of these methods.
checkRead()andcheckWrite()are just a few of the many of SecurityManager'scheckXXX()methods that verify various kinds of operations. You can override or add any number ofcheckXXX()methods to implement your security policy. You do not need to override all of SecurityManager'scheckXXX()methods, just the ones that you want to customize. However, the default implementation provided by the SecurityManager class for allcheckXXX()methods throws a SecurityException. In other words, by default the SecurityManager class disallows all operations that are subject to security restrictions. So you may find that you have to override many of SecurityManager'scheckXXX()methods to get the behavior you want.All of SecurityManager's
checkXXX()methods operate in the same way:Make sure that you implement your overridden
- If access is allowed, the method returns.
- If access is not allowed, the method throws a SecurityException.
checkXXX()methods in this manner.Well, that's it for our SecurityManager subclass. As you can see implementing a SecurityManager is simple. You just:
- Create a SecurityManager subclass.
- Override a few methods.
The tricky part is determining which methods to override and implementing your security policy. Deciding What SecurityManager Methods to Override will help you figure out which methods you should override depending on what types of operations you'd like to protect. The next page shows you how to install the PasswordSecurityManager class as the on-duty security manager for your Java application.
Installing Your Security Manager
Once you've completed writing yourSecurityManagersubclass, you can install it as the current security manager for your Java application. You do this with thesetSecurityManager()method from theSystemclass.Here's a small test application,
SecurityManagerTesthttp://doc.javanb.com/java-Tutorial-5-0-en/images/sourceIcon.gif, that installs the PasswordSecurityManager class from the previous page as the current security manager. Then to verify that the security manager is in place and operational, the SecurityManagerTest application opens two files--one for reading and one for writing--and copies the contents of the first file into the second.The
main()method begins by installing a new security manager:The bold line in the previous code snippet creates a new instance of the PasswordSecurityManager class with the password "Booga Booga". This instance is passed to System'stry { System.setSecurityManager(new PasswordSecurityManager("Booga Booga")); } catch (SecurityException se) { System.out.println("SecurityManager already set!"); }setSecurityManager()method, which installs the object as the current security manager for the running application. This security manager will remain in effect for the duration of the execution of this application.You can set the security manager for your application only once. In other words, your Java application can invoke
System.setSecurityManager()only one time during its lifetime. Any subsequent attempt to install a security manager within a Java application will result in a SecurityException.The rest of the program copies the contents of this file
inputtext.txtinto an output file namedoutputtext.txt. This is a simple test to verify that the PasswordSecurityManager has been properly installed.The bold lines in the previous code snippet are restricted file system accesses. These method calls will result in a call to PasswordSecurityManager'stry { DataInputStream fis = new DataInputStream( new FileInputStream("inputtext.txt")); DataOutputStream fos = new DataOutputStream( new FileOutputStream("outputtext.txt")); String inputString; while ((inputString = fis.readLine()) != null) { fos.writeBytes(inputString); fos.writeByte('\n'); } fis.close(); fos.close(); } catch (IOException ioe) { System.err.println("I/O failed for SecurityManagerTest."); }checkAccess()method.Running the Test Program
When you run the SecurityManagerTest application, you are prompted twice for a password: once when the application opens the input file and once when the application opens the output file. If you type in the correct password, the access is granted--the file object--and the application proceeds to the next statement. If you type in an incorrect password,checkXXX()throws a SecurityException, which the test application makes no attempt to catch so the application terminates.This is an example of the output from the application when you type in the password correctly the first time, but incorrectly the second:
Notice that the error message that the application prints is the error message for theWhat's the secret password? Booga Booga What's the secret password? Wrong password java.lang.SecurityException: Not Even! at PasswordSecurityManager.checkWrite(PasswordSecurityManager.java:46) at java.io.FileOutputStream.(FileOutputStream.java) at SecurityManagerTest.main(SecurityManagerTest.java:15)checkWrite(String)method.

加载中…