You are on page 1of 11

CLASS LOADERS

A class loader is an object that is responsible for loading classes. The class ClassLoader is an
abstract class. Given the name of a class, a class loader should attempt to locate or generate
data that constitutes a definition for the class. A typical strategy is to transform the name into a
file 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 Java
classes into the Java Virtual Machine. Usually classes are only loaded on demand. The Java run
time system does not need to know about files and file systems because of class
loaders. 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 of
objects. The most important type of object contained in a Jar file is a Java class. A class can be
thought of as a named unit of code. The class loader is responsible for locating libraries, reading
their contents, and loading the classes contained within the libraries. This loading is typically
done "on demand", in that it does not occur until the class is actually used by the program. A
class 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 a
string 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 to
uniquely identify a class implementation. The variable resolveIt is a flag to tell the class loader
that classes referenced by this class name should be resolved (that is, any referenced class
should be loaded as well).
CLASS LOADING PROCESS

Each Java class must be loaded by a class loader. Furthermore, Java programs may make use
of external libraries (that is, libraries written and provided by someone other than the author of
the 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 loader
Https://www.ThesisScientist.com
The bootstrap class loader loads the core Java libraries (<JAVA_HOME>/lib directory). This class
loader, which is part of the core JVM, is written in native code.

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). It
is implemented by the sun.misc.Launcher$ExtClassLoader class.

The system class loader loads code found on java.class.path, which maps to the
system CLASSPATH variable. This is implemented by thesun.misc.Launcher$AppClassLoader class.
USER DEFINED CLASS LOADERS

By default, all user classes are loaded by the default system class loader, but it is possible to
replace it by a user-defined ClassLoader (which defaults to the original root system class
loader), 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 LOADERS

While a Java program is executing, it may in its turn request that a particular class or set of
classes be loaded, possibly from across the network. After incoming code has been vetted and
determined 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 a
set of classes partitioned into separate name spaces. There is one name space for classes that
come from the local file system, and a separate name space for each network source.

Https://www.ThesisScientist.com
When a class is imported from across the network it is placed into the private name space
associated with its origin. When a class references another class, it is first looked for in the
name space for the local system (built-in classes), then in the name space of the referencing
class. There is no way that an imported class can "spoof" a built-in class. Built-in classes can
never accidentally reference classes in imported name spaces--they can only reference such
classes explicitly. Similarly, classes imported from different places are separated from each
other.

BYTECODE VERIFICATION

Bytecode verification is a crucial security component for Java applets, on the Web and on
embedded devices such as smart cards. Although the Java compiler ensures that Java source
code doesn't violate the safety rules, when an application such as the HotJava Browser imports
a code fragment from anywhere, it doesn't actually know if code fragments follow Java
language rules for safety: the code may not have been produced by a known-to-be trustworthy
Java compiler. In such a case, how is the Java run-time system on your machine to trust the
incoming bytecode stream? The answer is simple: the Java run-time system doesn't trust the
incoming code, but subjects it to bytecode verification.

The tests range from simple verification that the format of a code fragment is correct, to
passing each code fragment through a simple theorem prover to establish that it plays by the
rules:

it doesn't forge pointers,


it doesn't 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 of
guarantees that interfaces cannot be violated.

The Byte Code Verifier

The bytecode verifier traverses the bytecodes, constructs the type state information, and
verifies 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 the
Java compiler, to the class loader and bytecode verifier and hence on to the Java virtual
machine, which contains the interpreter and runtime system. The important issue is that the
Java class loader and the bytecode verifier make no assumptions about the primary source of

Https://www.ThesisScientist.com
the bytecode stream--the code may have come from the local system, or it may have travelled
halfway around the planet.

The bytecode verifier acts as a sort of gatekeeper: it ensures that code passed to the Java
interpreter is in a fit state to be executed and can run without fear of breaking the Java
interpreter. Imported code is not allowed to execute by any means until after it has passed the
verifier's 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 protected

While all this checking appears excruciatingly detailed, by the time the bytecode verifier has
done 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 doesn't have to

Https://www.ThesisScientist.com
check anything. There are no operand type checks and no stack overflow checks. The
interpreter can thus function at full speed without compromising reliability.

SECURITY MANAGER

A security manager is an object that defines a security policy for an application. This policy
specifies actions that are unsafe or sensitive. Any actions not allowed by the security policy
cause a SecurityException to be thrown. An application can also query its security manager to
discover which actions are allowed.

Typically, a web applet runs with a security manager provided by the browser or Java Web Start
plugin. Other kinds of applications normally run without a security manager, unless the
application itself defines one. If no security manager is present, the application has no security
policy and acts without restrictions.

INTERACTING WITH THE SECURITY MANAGER

The 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 permission
to 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 shut
down the application.

The SecurityManager class defines many other methods used to verify other kinds of
operations. For example, SecurityManager.checkAccessverifies thread accesses,
and SecurityManager.checkPropertyAccess verifies access to the specified property. Each
operation or group of operations has its own checkXXX() method.

Https://www.ThesisScientist.com
In addition, the set of checkXXX() methods represents the set of operations that are already
subject to the protection of the security manager. Typically, an application does not have to
directly invoke any checkXXX() methods.

RECOGNIZING A SECURITY VIOLATION

Many actions that are routine without a security manager can throw a SecurityException when
run with a security manager. This is true even when invoking a method that isn't documented
as throwing SecurityException. For example, consider the following code used to read a file:

reader = new FileReader("xanadu.txt");

In the absence of a security manager, this statement executes without error,


provided xanadu.txt exists and is readable

PERMISSIONS

A permission represents access to a system resource. In order for a resource access to be


allowed for an applet (or an application running with a security manager), the corresponding
permission 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, Serializable

A permission typically has a name (often referred to as a "target name") and, in some cases, a
comma-separated list of one or more actions. For example, the following code creates a
FilePermission 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 Policy
reference implementation, the policy can be specified within one or more policy configuration
files. The policy file(s) specify what permissions are allowed for code from specified code
sources. A sample policy file entry granting code from the /home/sysadmin directory read
access to the file /tmp/abc is

grant codeBase "file:/home/sysadmin/" {


permission java.io.FilePermission "/tmp/abc", "read";
};

Https://www.ThesisScientist.com
Permission objects are similar to String objects in that they are immutable once they have been
created. Subclasses should not provide methods that can change the state of permission once it
has 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
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.AudioPermission

AllPermission

The java.security.AllPermission is a permission that implies all other permissions.

SecurityPermission

A java.security.SecurityPermission is for security permissions. A SecurityPermission contains a


name (also referred to as a "target name") but no actions list; you either have the named
permission or you don't.

The target name is the name of a security configuration parameter (see below). Currently
the SecurityPermission object is used to guard access to the Policy, Security, Provider, Signer,
and Identity objects.

UnresolvedPermission

Https://www.ThesisScientist.com
The java.security.UnresolvedPermission class is used to hold Permissions that were
"unresolved" when the Policy was initialized. An unresolved permission is one whose
actual Permission class does not yet exist at the time the Policy is initialized (see below).

AWTPermission

A java.awt.AWTPermission is for AWT permissions.

FilePermission

A java.io.FilePermission represents access to a file or directory. A FilePermission consists of a


pathname and a set of actions valid for that pathname.

Pathname is the pathname of the file or directory granted the specified actions.

SerializablePermission

A java.io.SerializablePermission is for serializable permissions. A SerializablePermission contains


a name (also referred to as a "target name") but no actions list; you either have the named
permission or you don't.

The target name is the name of the Serializable permission

ReflectPermission

A java.lang.reflect.ReflectPermission is for reflective operations. A ReflectPermission is a named


permission and has no actions. The only name currently defined issuppressAccessChecks, which
allows suppressing the standard language access checks -- for public, default (package) access,
protected, and private members -- performed by reflected objects at their point of use.

RuntimePermission

A java.lang.RuntimePermission is for runtime permissions. A RuntimePermission contains a


name (also referred to as a "target name") but no actions list; you either have the named
permission or you don't.

The target name is the name of the runtime permission

NetPermission

Https://www.ThesisScientist.com
A java.net.NetPermission is for various network permissions. A NetPermission contains a name
but no actions list; you either have the named permission or you don't.

SocketPermission

A java.net.SocketPermission represents access to a network via sockets. A SocketPermission


consists 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 local
machine). The wildcard "*" may be included once in a DNS name host specification. If it is
included, 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 port
number, signifies all ports numbered N and above, while a specification of the form "-N"
indicates all ports numbered N and below.

SQLPermission

The permission for which the SecurityManager will check when code that is running in an
applet 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.setLogWriter

If there is no SQLPermission object, this method throws a java.lang.SecurityException as a


runtime exception.

PropertyPermission

A java.util.PropertyPermission is for property permissions.


The name is the name of the property ("java.home", "os.name", etc).

LoggingPermission
A SecurityManager will check the java.util.logging.LoggingPermission object when code running
with a SecurityManager calls one of the logging control methods (such as Logger.setLevel).
Https://www.ThesisScientist.com
Currently there is only one named LoggingPermission, "control". Control grants the ability to
control the logging configuration; for example by adding or removing Handlers, by adding or
removing Filters, or by changing logging levels.

Normally you do not create LoggingPermission objects directly; instead they are created by the
security policy code based on reading the security policy file.

SSLPermission

The 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; you
either have the named permission or you don't.

The target name is the name of the network permission

AuthPermission

The 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 don't.

Currently the AuthPermission object is used to guard access to the Subject,


SubjectDomainCombiner, LoginContext and Configuration objects.

PrivateCredentialPermission

The javax.security.auth.PrivateCredentialPermission class is used to protect access to private


Credentials 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 Permission's actions is, "read". The target name must abide by the
following syntax:

CredentialClass {PrincipalClass "PrincipalName"}*

DelegationPermission

The javax.security.auth.kerberos.DelegationPermission class is used to restrict the usage of the


Kerberos delegation model; ie, forwardable and proxiable tickets.

The target name of this Permission specifies a pair of kerberos service principals.

ServicePermission

Https://www.ThesisScientist.com
The javax.security.auth.kerberos.ServicePermission class is used to protect Kerberos services
and the credentials necessary to access those services. There is a one to one mapping of a
service principal and the credentials necessary to access the service. Therefore granting access
to a service principal implicitly grants access to the credential necessary to establish a security
context with the service principal. This applies regardless of whether the credentials are in a
cache or acquired via an exchange with the KDC. The credential can be either a ticket granting
ticket, 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 the
context the credential can be used within.

AudioPermission

The AudioPermission class represents access rights to the audio system resources.
An AudioPermission contains a target name but no actions list; you either have the named
permission or you don't.

The target name is the name of the audio permission

Https://www.ThesisScientist.com

You might also like