Unit8 security (2) java


Published on


Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Unit8 security (2) java

  1. 1. CLASS LOADERSA class loader is an object that is responsible for loading classes. The class ClassLoader is anabstract class. Given the name of a class, a class loader should attempt to locate or generatedata that constitutes a definition for the class. A typical strategy is to transform the name into afile name and then read a "class file" of that name from a file system.The Java Classloader is a part of the Java Runtime Environment that dynamically loads Javaclasses into the Java Virtual Machine. Usually classes are only loaded on demand. The Java runtime system does not need to know about files and file systems because of classloaders. Delegation is an important concept to understand when learning about class loaders.A software library is a collection of more or less related object code. In the Java language,libraries are typically packaged in Jar files. Libraries can contain various different sorts ofobjects. The most important type of object contained in a Jar file is a Java class. A class can bethought of as a named unit of code. The class loader is responsible for locating libraries, readingtheir contents, and loading the classes contained within the libraries. This loading is typicallydone "on demand", in that it does not occur until the class is actually used by the program. Aclass with a given name can only be loaded once by a given classloader.At its simplest, a class loader creates a flat name space of class bodies that are referenced by astring name. The method definition is: Class r = loadClass(String className, boolean resolveIt);The variable className contains a string that is understood by the class loader and is used touniquely identify a class implementation. The variable resolveIt is a flag to tell the class loaderthat classes referenced by this class name should be resolved (that is, any referenced classshould be loaded as well).CLASS LOADING PROCESSEach Java class must be loaded by a class loader. Furthermore, Java programs may make useof external libraries (that is, libraries written and provided by someone other than the author ofthe program) or may itself be composed, at least in part, by a number of libraries.When the JVM is started, three class loaders are used: 1. Bootstrap class loader 2. Extensions class loader 3. System class loaderThe bootstrap class loader loads the core Java libraries (<JAVA_HOME>/lib directory). This classloader, which is part of the core JVM, is written in native code.
  2. 2. The extensions class loader loads the code in the extensions directories(<JAVA_HOME>/lib/ext or any other directory specified by the java.ext.dirs system property). Itis implemented by the sun.misc.Launcher$ExtClassLoader class.The system class loader loads code found on java.class.path, which maps to thesystem CLASSPATH variable. This is implemented by thesun.misc.Launcher$AppClassLoader class.USER DEFINED CLASS LOADERSBy default, all user classes are loaded by the default system class loader, but it is possible toreplace it by a user-defined ClassLoader (which defaults to the original root system classloader), and even to chain class loaders as desired.This makes it possible (for example): to load or unload classes at runtime (for example to load libraries dynamically at runtime, even from a HTTP resource). This is an important feature for:  implementing scripting languages,  using bean builders,  allowing user-defined extensibility  allowing multiple namespaces to communicate. This is one of the foundations of CORBA / RMI protocols, for example. to change the way the bytecode is loaded (for example, it is possible to use encrypted Java class bytecode). to modify the loaded bytecode (for example, for load-time weaving of aspects when using Aspect Oriented Programming).SECURITY CHECKS IN CLASS LOADERSWhile a Java program is executing, it may in its turn request that a particular class or set ofclasses be loaded, possibly from across the network. After incoming code has been vetted anddetermined clean by the bytecode verifier, the next line of defense is the Java bytecode loader.The environment seen by a thread of execution running Java bytecodes can be visualized as aset of classes partitioned into separate name spaces. There is one name space for classes thatcome from the local file system, and a separate name space for each network source.When a class is imported from across the network it is placed into the private name spaceassociated with its origin. When a class references another class, it is first looked for in thename space for the local system (built-in classes), then in the name space of the referencing
  3. 3. class. There is no way that an imported class can "spoof" a built-in class. Built-in classes cannever accidentally reference classes in imported name spaces--they can only reference suchclasses explicitly. Similarly, classes imported from different places are separated from eachother.BYTECODE VERIFICATIONBytecode verification is a crucial security component for Java applets, on the Web and onembedded devices such as smart cards. Although the Java compiler ensures that Java sourcecode doesnt violate the safety rules, when an application such as the HotJava Browser importsa code fragment from anywhere, it doesnt actually know if code fragments follow Javalanguage rules for safety: the code may not have been produced by a known-to-be trustworthyJava compiler. In such a case, how is the Java run-time system on your machine to trust theincoming bytecode stream? The answer is simple: the Java run-time system doesnt trust theincoming code, but subjects it to bytecode verification.The tests range from simple verification that the format of a code fragment is correct, topassing each code fragment through a simple theorem prover to establish that it plays by therules:  it doesnt forge pointers,  it doesnt violate access restrictions,  it accesses objects as what they are (for example, InputStream objects are always used as InputStreams and never as anything else).A language that is safe, plus run-time verification of generated code, establishes a base set ofguarantees that interfaces cannot be violated.The Byte Code VerifierThe bytecode verifier traverses the bytecodes, constructs the type state information, andverifies the types of the parameters to all the bytecode instructions.The illustration shows the flow of data and control from Java language source code through theJava compiler, to the class loader and bytecode verifier and hence on to the Java virtualmachine, which contains the interpreter and runtime system. The important issue is that theJava class loader and the bytecode verifier make no assumptions about the primary source ofthe bytecode stream--the code may have come from the local system, or it may have travelledhalfway around the planet.
  4. 4. The bytecode verifier acts as a sort of gatekeeper: it ensures that code passed to the Javainterpreter is in a fit state to be executed and can run without fear of breaking the Javainterpreter. Imported code is not allowed to execute by any means until after it has passed theverifiers tests. Once the verifier is done, a number of important properties are known:  There are no operand stack overflows or underflows  The types of the parameters of all bytecode instructions are known to always be correct  Object field accesses are known to be legal--private, public, or protectedWhile all this checking appears excruciatingly detailed, by the time the bytecode verifier hasdone its work, the Java interpreter can proceed, knowing that the code will run securely.Knowing these properties makes the Java interpreter much faster, because it doesnt have tocheck anything. There are no operand type checks and no stack overflow checks. Theinterpreter can thus function at full speed without compromising reliability.
  5. 5. SECURITY MANAGERA security manager is an object that defines a security policy for an application. This policyspecifies actions that are unsafe or sensitive. Any actions not allowed by the security policycause a SecurityException to be thrown. An application can also query its security manager todiscover which actions are allowed.Typically, a web applet runs with a security manager provided by the browser or Java Web Startplugin. Other kinds of applications normally run without a security manager, unless theapplication itself defines one. If no security manager is present, the application has no securitypolicy and acts without restrictions.INTERACTING WITH THE SECURITY MANAGERThe security manager is an object of type SecurityManager; to obtain a reference to this object,invoke System.getSecurityManager. SecurityManager appsm = System.getSecurityManager();If there is no security manager, this method returns null.Once an application has a reference to the security manager object, it can request permissionto do specific things. Many classes in the standard libraries do this. For example, System.exit,which terminates the Java virtual machine with an exit status,invokes SecurityManager.checkExit to ensure that the current thread has permission to shutdown the application.The SecurityManager class defines many other methods used to verify other kinds ofoperations. For example, SecurityManager.checkAccessverifies thread accesses,and SecurityManager.checkPropertyAccess verifies access to the specified property. Eachoperation or group of operations has its own checkXXX() method.In addition, the set of checkXXX() methods represents the set of operations that are alreadysubject to the protection of the security manager. Typically, an application does not have todirectly invoke any checkXXX() methods.RECOGNIZING A SECURITY VIOLATIONMany actions that are routine without a security manager can throw a SecurityException whenrun with a security manager. This is true even when invoking a method that isnt documentedas throwing SecurityException. For example, consider the following code used to read a file: reader = new FileReader("xanadu.txt");
  6. 6. In the absence of a security manager, this statement executes without error,provided xanadu.txt exists and is readablePERMISSIONSA permission represents access to a system resource. In order for a resource access to beallowed for an applet (or an application running with a security manager), the correspondingpermission must be explicitly granted to the code attempting the access.Java uses Permission abstract class for representing access to a system resource. public abstract class Permission extends Object implements Guard, SerializableA permission typically has a name (often referred to as a "target name") and, in some cases, acomma-separated list of one or more actions. For example, the following code creates aFilePermission object representing read access to the file named abc in the /tmp directory: perm = new java.io.FilePermission("/tmp/abc", "read");In this, the target name is "/tmp/abc" and the action string is "read".The policy for a Java application environment is represented by a Policy object. In the Policyreference implementation, the policy can be specified within one or more policy configurationfiles. The policy file(s) specify what permissions are allowed for code from specified codesources. A sample policy file entry granting code from the /home/sysadmin directory readaccess to the file /tmp/abc isgrant codeBase "file:/home/sysadmin/" { permission java.io.FilePermission "/tmp/abc", "read";};Permission objects are similar to String objects in that they are immutable once they have beencreated. Subclasses should not provide methods that can change the state of permission once ithas been created.PERMISSION DESCRIPTION & RISKS java.security.AllPermission java.security.SecurityPermission java.security.UnresolvedPermission java.awt.AWTPermission java.io.FilePermission java.io.SerializablePermission java.lang.reflect.ReflectPermission java.lang.RuntimePermission
  7. 7. java.net.NetPermission java.net.SocketPermission java.sql.SQLPermission java.util.PropertyPermission java.util.logging.LoggingPermission javax.net.ssl.SSLPermission javax.security.auth.AuthPermission javax.security.auth.PrivateCredentialPermission javax.security.auth.kerberos.DelegationPermission javax.security.auth.kerberos.ServicePermission javax.sound.sampled.AudioPermissionAllPermissionThe java.security.AllPermission is a permission that implies all other permissions.SecurityPermissionA java.security.SecurityPermission is for security permissions. A SecurityPermission contains aname (also referred to as a "target name") but no actions list; you either have the namedpermission or you dont.The target name is the name of a security configuration parameter (see below). Currentlythe SecurityPermission object is used to guard access to the Policy, Security, Provider, Signer,and Identity objects.UnresolvedPermissionThe java.security.UnresolvedPermission class is used to hold Permissions that were"unresolved" when the Policy was initialized. An unresolved permission is one whoseactual Permission class does not yet exist at the time the Policy is initialized (see below).AWTPermissionA java.awt.AWTPermission is for AWT permissions.FilePermissionA java.io.FilePermission represents access to a file or directory. A FilePermission consists of apathname and a set of actions valid for that pathname.Pathname is the pathname of the file or directory granted the specified actions.
  8. 8. SerializablePermissionA java.io.SerializablePermission is for serializable permissions. A SerializablePermission containsa name (also referred to as a "target name") but no actions list; you either have the namedpermission or you dont.The target name is the name of the Serializable permissionReflectPermissionA java.lang.reflect.ReflectPermission is for reflective operations. A ReflectPermission is a namedpermission and has no actions. The only name currently defined issuppressAccessChecks, whichallows suppressing the standard language access checks -- for public, default (package) access,protected, and private members -- performed by reflected objects at their point of use.RuntimePermissionA java.lang.RuntimePermission is for runtime permissions. A RuntimePermission contains aname (also referred to as a "target name") but no actions list; you either have the namedpermission or you dont.The target name is the name of the runtime permissionNetPermissionA java.net.NetPermission is for various network permissions. A NetPermission contains a namebut no actions list; you either have the named permission or you dont.SocketPermissionA java.net.SocketPermission represents access to a network via sockets. A SocketPermissionconsists of a host specification and a set of "actions" specifying ways to connect to that host.The host is specified as host = (hostname | IPaddress)[:portrange] portrange = portnumber | -portnumber | portnumber-[portnumber]The host is expressed as a DNS name, as a numerical IP address, or as "localhost" (for the localmachine). The wildcard "*" may be included once in a DNS name host specification. If it isincluded, it must be in the leftmost position, as in "*.sun.com".The port or portrange is optional. A port specification of the form "N-", where N is a portnumber, signifies all ports numbered N and above, while a specification of the form "-N"indicates all ports numbered N and below.
  9. 9. SQLPermissionThe permission for which the SecurityManager will check when code that is running in anapplet calls one of the setLogWriter methods. These methods include those in the following list.  DriverManager.setLogWriter  DriverManager.setLogStream (deprecated)  javax.sql.DataSource.setLogWriter  javax.sql.ConnectionPoolDataSource.setLogWriter  javax.sql.XADataSource.setLogWriterIf there is no SQLPermission object, this method throws a java.lang.SecurityException as aruntime exception.PropertyPermissionA java.util.PropertyPermission is for property permissions.The name is the name of the property ("java.home", "os.name", etc).LoggingPermissionA SecurityManager will check the java.util.logging.LoggingPermission object when code runningwith a SecurityManager calls one of the logging control methods (such as Logger.setLevel).Currently there is only one named LoggingPermission, "control". Control grants the ability tocontrol the logging configuration; for example by adding or removing Handlers, by adding orremoving Filters, or by changing logging levels.Normally you do not create LoggingPermission objects directly; instead they are created by thesecurity policy code based on reading the security policy file.SSLPermissionThe javax.net.ssl.SSLPermission class is for various network permissions.An SSLPermission contains a name (also referred to as a "target name") but no actions list; youeither have the named permission or you dont.The target name is the name of the network permissionAuthPermissionThe javax.security.auth.AuthPermission class is for authentication permissions.An AuthPermission contains a name (also referred to as a "target name") but no actions list;you either have the named permission or you dont.Currently the AuthPermission object is used to guard access to the Subject,SubjectDomainCombiner, LoginContext and Configuration objects.
  10. 10. PrivateCredentialPermissionThe javax.security.auth.PrivateCredentialPermission class is used to protect access to privateCredentials belonging to a particular Subject. The Subject is represented by a Set of Principals.The target name of this Permission specifies a Credential class name, and a Set of Principals.The only valid value for this Permissions actions is, "read". The target name must abide by thefollowing syntax:CredentialClass {PrincipalClass "PrincipalName"}*DelegationPermissionThe javax.security.auth.kerberos.DelegationPermission class is used to restrict the usage of theKerberos delegation model; ie, forwardable and proxiable tickets.The target name of this Permission specifies a pair of kerberos service principals.ServicePermissionThe javax.security.auth.kerberos.ServicePermission class is used to protect Kerberos servicesand the credentials necessary to access those services. There is a one to one mapping of aservice principal and the credentials necessary to access the service. Therefore granting accessto a service principal implicitly grants access to the credential necessary to establish a securitycontext with the service principal. This applies regardless of whether the credentials are in acache or acquired via an exchange with the KDC. The credential can be either a ticket grantingticket, a service ticket or a secret key from a key table.A ServicePermission contains a service principal name and a list of actions which specify thecontext the credential can be used within.AudioPermissionThe AudioPermission class represents access rights to the audio system resources.An AudioPermission contains a target name but no actions list; you either have the namedpermission or you dont.The target name is the name of the audio permission