Thursday, February 26, 2009

Loading Applets in a browser

A common misconception of most newcomers to Java is that security restrictions apply only to applets (Java classes downloaded and executed within a web browser).In fact, security restrictions can apply to all Java classes. (However, they do not apply to classes loaded from the boot classpath.) Before the Java API performs an action that is potentially unsafe, it calls the Java Security Manager to determine whether the action is permitted. Here is a partial list of the actions for which checks take place:Reading, writing, or deleting a fileOpening, waiting for, or accepting a socket connectionModifying a thread attribute (for example, priority)Accessing or updating system propertiesIf the Java Security Manager does not permit the action, the Java API will not allow the action to take place. Now, you might ask, how is my application able to do one of these so-called unsafe calls, such as read or write a file? The answer is that the Java Security Manager is not installed by default; but it can be by calling it within your class or specifying a parameter to the Java command line. To establish the Java Security Manager within code, place the following as the first line in the main() method:System.setSecurityManager( new SecurityManager() );To establish the Java Security Manager via the command line, add the following parameter to the command line:-Djava.security.managerOnce installed, the Java Security Manager checks whether a particular permission is granted to the specific requesting class; it throws a SecurityException if the permission is denied. The Java Security Manager checks by examining the call trace,so if an untrusted piece of code is invoked as part of a call to a secured method, it will fail because of the presence of the untrusted code. The permission is itself an abstract class representing access to a system resource. The permission can optionally contain a name and an action. When specified, these optional attributes further refine the permission being granted. For example, java.io.SocketPermission can be established with a host name of 66.108.43.211:9080 and an action of accept,connect,listen, which will allow the code to accept connections on, connect to, or listen on port 9080 on a host specified by IP address 66.108.43.211.Here is a list of the security restrictions that Java 2 technology environments normally impose on applets running in a browser:An applet can utilize only its own code and is not allowed to load libraries or define native methods.An applet cannot read or write files on the host that is executing it.An applet can make network connections only to the host from which it was downloaded.An applet cannot start any program on the local host.An applet is restricted from reading the system properties.