Saturday, June 2, 2018

Control Access to a Java Object using Access Controller Mechanism and Security Manager - JAAS(Java Authentication and Authorization System)


When building distributed java applications that span across multiple Java virtual machines (Using RMI), It is important to protect the state of an object for integrity and confidentiality . These security requirements exist when concerned objects are inside a run time system(e.g., in memory), in transit(e.g., stored in IP packets), or stored externally(e.g., saved on disk).

Guarding Java Objects

There are applications scenarios where the supplier of a resource is not in the same thread as the consumer of that resource, and the consumer thread cannot provide the supplier thread the access control context information (because the context in security-sensitive , or  the context is too large to pass , or for other reasons). For this case GuardedObject is provided to protect access to the resource.

Guarded Operations - Access control using synchronize calls
  • Guarded objects encapsulate data shared by several active objects or tasks and they can be accessed only with a specific lock held.
  • They do not own their own threads but can synchronize calls from various threads.
  • Operations that are protected are called guarded operations. 
  • A guarded operation is considered critical enough to need to enforce mutual exclusion.
  • A guarded object is an object that owns at least one guarded operation.
  • One way to implement a guarded object is to give it a mutex so every operation that is explicitly set to be guarded locks the mutex at the beginning of the operation and releases it at the end
Mutex :
  • A mutual exclusion (mutex) is a program object that prevents simultaneous access to a shared resource. 
  • This concept is used in concurrent programming with a critical section, a piece of code in which processes or threads access a shared resource.
GuardedObject
  • A GuardedObject(also known as protected objects, synchronized objects, or monitors) is an object that is used to protect access control to another object.
  • A GuardedObject encapsulates a target object and a Guard object, such that access to the target object is possible only if the Guard object allows it.
  • Once an object is encapsulated by a GuardedObject, access to that object is controlled by the getObject method, which invokes the checkGuard method on the Guard object that is guarding access. If access is not allowed, a SecurityException  exception will be thrown.

  • Above solid lines represent method call and dotted line represent object reference.
  • When a requester asks for a guarded object , the guarded object is consulted and the reference to the object is returned to the requestor if the guard object allows it. 
  • Security check done in the consumer side and Consumer environment too security sensitive
  • Don't know what information needed by provider and Don't want a dialog for each request
  • Information is too security sensitive and too much information to pass on.
  • Guaranteed to occur in a context where the protection mechanism would allow it

API Design :
The interface Guard contains only one method  : 
public abstract void checkGuard(Object object)
The signature of the GuardedObject class are the following: 
public GuardedObject (Object o, Guard g)
public Object getObject()

Example - 1 (PropertyPermission)

Step 1:(Encapulate an objects protection semeantics inside a guard)
Create the Protected Object that requires protection
ProtectedObject protObject = new ProtectedObject("my_username","my_password");

Step 2:(Provider Side)
Create the Guard object i,e the permission that will protect the object. In this case those threads who will have the read access to the "java.home" environment variable can access the object as well and create the GuardedObject using Protected Object and Guard.
ProtectedObject protObject = new ProtectedObject("my_username","my_password");
Guard guard = new PropertyPermission("java.home", "read");
GuardedObject guardedObject = new GuardedObject(protObject , guard);

Step 3:(Consumer Side)
Get the guarded object, only threads with the required permission can access the object.
ProtectedObject proObject = (ProtectedObject) guardedObject.getObject();
System.out.println("Protected object is " + proObject);

Full Example
import java.io.Serializable;
import java.security.AccessControlException;
import java.security.Guard;
import java.security.GuardedObject;
import java.util.PropertyPermission;

public class ControlAccessObjectExample1 {
 public static void main(String[] args) {
    ProtectedObject protObject  = new ProtectedObject("my_username","my_password"); 
    Guard guard = new PropertyPermission("java.home", "read");
    GuardedObject guardedObject = new GuardedObject(protObject , guard);
    try {
       ProtectedObject proObject = (ProtectedObject)guardedObject.getObject();
       System.out.println("Protected object is " + proObject);
    } catch (AccessControlException e) {
       System.err.println("Cannot access the object - permission is denied");
    }
 }
}
class ProtectedObject implements Serializable {
 private String username;
 private String password;
 
 public ProtectedObject(String username,String password){
  this.username = username;
  this.password = password;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
}

Example - 2(FilePermission)

Step 1:(Encapulate an objects protection semeantics inside a guard)
Create the Protected Object that requires protection
FileInputStream fis = new FileInputStream("E:/sjena/abc.txt");

Step 2:(Provider Side)
Create the Guard object i,e the permission that will protect the object. In this case those threads who will have the read access to the "abc.txt" can access the object as well and create the GuardedObject using Protected Object and Guard.
FileInputStream fis = new FileInputStream("E:/sjena/abc.txt");
FilePermission permission = new FilePermission("E:/sjena/abc.txt", "read");
GuardedObject guardedObject = new GuardedObject(fis, permission);

Step 3:(Consumer Side)
Get the guarded object, only threads with the required permission can access the object.
FileInputStream inputStream = (FileInputStream)guardedObject.getObject();
System.out.println("Protected object is " + inputStream);

Full Example
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilePermission;
import java.security.AccessControlException;
import java.security.GuardedObject;

public class ControlAccessObjectExample2 {
 public static void main(String[] args) throws FileNotFoundException {
   FileInputStream fis = new FileInputStream("E:/sjena/abc.txt");
   Guard guard = new FilePermission("E:/sjena/abc.txt", "read");
   GuardedObject guardedObject = new GuardedObject(fis, guard);
   try {
     FileInputStream inputStream = (FileInputStream)guardedObject.getObject();
     System.out.println("Protected object is " + inputStream);
   } catch (AccessControlException e) {
     System.err.println("Cannot access the object - permission is denied");
   }
 }
}

Conclusion 1 : new FileInputStream("E:/sjena/abc.txt");
The implementation of this constructor must be aware that a security check needs to be done , must understand what sort of check is appropriate and also must sprinkle all constructors with the similar checks.
public FileInputStream(File arg0) throws FileNotFoundException {
 this.channel = null;
 this.closeLock = new Object();
 this.closed = false;
 String arg1 = arg0 != null ? arg0.getPath() : null;
 SecurityManager arg2 = System.getSecurityManager();
 if (arg2 != null) {
      arg2.checkRead(arg1);
 }
 /////////////////////
}

Conclusion 2 :  PropertyPermission (or) FilePermission
In both the examples, the getObject() methiod in turn invokes the checkGuard method on the Guard object guard and because guard is a Permission , its checkGuard method is in fact:

public abstract class Permission implements Guard, Serializable {
    /////////////////////
    public void checkGuard(Object arg0) throws SecurityException {
      SecurityManager arg1 = System.getSecurityManager();
      if (arg1 != null) {
          arg1.checkPermission(this);
      }
   }
}
The above implementation ensures that a proper access  control check takes place within the consumer context , when access to the stream is first requested.

Conclusion 3 : FileInputStream is =(FileInputStream)go.getObject();
After object go is passed to the consumer , it will recover the FileInputStream, but only if the consumer is permitted to obtain read access to file "E:/sjena/abc.txt"

Conclusion 4 :
The implementation of FileInputStream itself need not be security aware (as long as it is always protected by a GuardedObject), the above design does not further perform security checks once a FileInputStream is returned to the consumer and this is the same behavior implemented in the FileInputStream class today. 

Conclusion 5 :
We can radically rewrite the FileInputStream class as follows, For every constructor , if it does not take a Guard object guard as a parameter , a suitable Guard is automatically generated . For every access method (such as read(bytes)), the uniform security check in the form of g.checkGuard() is invoke first.

Permission:
  • Every Java class carries a set of permissions that defines the activities that the class is allowed to perform.
  • Classes of the core Java API are always given the permission to perform any action (depends upon the java.security file)
  • All other classes must explicitly be given permission to perform sensitive operations
  • Most of these permissions are listed in the policy file
  • Any Java API may extends the system of permission provided by the standard mechanism

Although you can write your own guards, the Permission class already implements the guard interface. Hence, any permission can be used to guard an object as follows:

Class Definition:
public class GuardTest {
   public static void main(String args[]) {
      GuardedObject go = new GuardedObject(new XYZPayrollRequest(),
      new XYZPayrollPermission("sdo", "view"));
      try {
         Object o = go.getObject();
         System.out.println("Got access to object");
     } catch (AccessControlException ace) {
        System.out.println("Can't access object");
    } 
  }  
}   

When the getObject() method is called, it in turn calls the checkGuard() method of the XYZPayrollPermission class, which (as it inherits from the Permission class) will call the checkPermission() method of the access controller, passing the XYZ payroll request object as an argument.

On a typical machine, a java program may have below permissions  :
  • access to the local memory
  • access to the local filesystem
  • access to the filesystem of other machines on the local network
  • access to different kind of servers (e.g. RMI servers)
  • for applet, access to a web server which may be either local or on the internet

Below are the standard permissions,
  • File Permission: class java.io.FilePermission
  • Socket Permission: class java.net.SocketPermission
  • Property Permission: class java.util.PropertyPermission
  • Runtime Permission: class java.lang.RuntimePermission
  • AWT Permission: class java.awt.AWTPermission 
  • Net Permission: class java.net.NetPermission
  • Security Permission: class java.security.SecurityPermission
  • Serializable Permission: class java.io.SerializablePermission
  • Reflection Permission: class java.lang.ReflectionPermission
  • All Permission: class java.security.AllPermission
Permission Class

1. The Permission abstract class is the base of the types listed in the policy file
2. Permissions have three properties 
  • a type (the name of the class) 
  • a name (e.g. th name of the file the application has been granted to access) 
  • some actions
3. Name and action are optional , the name is chosen arbitrarily.
4. The presence of actions depends upon the semantics of the specific type of permission
5. All the permissions defined in the Java system are based on the Permission class , this class abstract the notion of permission, name and action
6. The Permission class is abstract and defines the following methods :
  • public Permission (String name) 
  • public abstract boolean equals (Object o) 
  • public abstract int hashCode() 
  • public abstract String getActions() 
  • public abstract boolean implies (Permission p) 
  • public final String getName()
  • public String toString() 
  • public PermissionCollection newPermissionCollection() 
  • public void checkGuard (Object obj)  


The File Permissions
A FilePermission represents access to a file or directory.
A FilePermission consists of a pathname and a set of actions valid for that pathname.
class : java.io.FilePermission
name : name of the file you want operate on
actions : read, write, delete, execute
example : permission java.io.FilePermission "<>, "read, delete,execute, write"; permission java.io.FilePermission "\${user.home}/-", "read"; 

The Socket Permissions
A 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. 
class : java.net.SocketPermission 
name : host:port 
actions : accept, listen, connect, resolve 
example : permission java.net.SocketPermission "*:1024-", "accept, connect" permission java.net.SocketPermission "*.bfh.ch", "connect, resolve";

The Property Permissions
A PropertyPermission is for property permissions. The name is the name of the property (java.home, os.name, etc). The naming convention follows the hierarchical property naming convention. 
Also, an asterisk may appear at the end of the name, following a ".", or by itself, to signify a wildcard match. For example: "java.*" or "*" is valid, "*java" or "a*b" is not valid. The actions to be granted are passed to the constructor in a string containing a list of zero or more comma-separated keywords. The possible keywords are "read" and "write". 
class : java.util.PropertyPermission 
name : name of the Java VM property you want access 
actions : read, write 
example : permission java.util.PropertyPermission "java.*", "read" 

The Runtime Permissions
A 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.
class : java.lang.RuntimePermission 
name : accessClassInPackage, accessDeclaredMembers, createClassLoader, reateSecurityManager, defineClassInPackage, exitVM, getClassLoader, getProtectionDomain, loadlibrary, modifyThread, modifyThreadGroup, queuePrintJob, readFileDescriptor, setContectClassLoader, setFactory, setIO, setSecurityManager, stopThread, writeFileDescriptor 
actions : none 
example : permission java.lang.RuntimePermission "queuePrintJob";

The Security Permissions
class : java.security.SecurityPermission
name : addIdentityCertificate, clearProviderProperties, createAccessControlContext, getDomainCombiner, getPolicy, getProperty, getSignerPrivateKey, insertProvider, loadProviderProperties, printIdentity, puttAllProviderProperties, putProviderProperty, removeIdentityCertificate, removeProvider, removeProviderProperty, setIdentityInfo, setIdentityPublicKey, setPolicy, setProperty, setSignerKeyPair, setSystemScope
actions : none
example : permission java.security.SecurityPermission "insertProvider.BC";

The AllPermissions :
AllPermission is a special permission mainly used during the development phase of a program. For production installation, there is no reason to grant this special permission.
class : java.security.AllPermissions
name : none
actions : none
example : permission java.security.AllPermissions;

Java provides three main packages for the security :

1. Java Cryptography Extension (JCE) provides
  • encryption
  • secure keys exchange
  • secure message digest
  • an alternate key management system
2. Java Secure Socket Layer (JSSL) provides
  • tools for secure communications
3. Java Authentification and Authorization System (JAAS) provides
  • tools for authenticating the user of a program and authorize or deny the access to sensitive data.
  • protect end user from the influence of developer.
  • end user gives permissions to the developer to access ressources of the user’s end machine
  • JAAS allows developer to grant or deny access to their programs based on the credentials provided by the users.

Authentication - The process or action of identifying an individual, usually based on a username and password i,e verifying the identity of a user or process

Authorization - The process of specifying access rights/privileges to resources related to information security and computer security in general and to access control in particular.

Java Access Controller Mechanism
  • Java access controller is the most powerful security feature of the Java platform.it protects most of the vital resources on a user's machine, and it allows users (or system administrators) to customize the security policy of  a particular application simply by modifying entries in the java.policy (and/or other similar) files.
  • Java access controller is able to control access to a well-established set of system resources (files, sockets, etc.), but it is extensible as well i,e you can create your own permission classes that the access controller can use in order to grant or to deny access to any resource that you like.





The typical anatomy of a Java program is :
  • The bytecode verifier ensures that the Java class files follow the rules of Java
  • The class loader load classes into memory. When programmatically used, it can also set permissions for the classes it load
  • The access controller allows or prevent access from the core API to the operating system, based upon policies defined by the end user
  • The security manager is the primary inteface between the core API and the operating system. It has the ultimate responsibility for allowing or preventing access to all system resources
  • The security package allow to add security feature to your own application. The classes of the security package are in the packages java.security.* and javax.security.*

Security Manager:
  • Security Manager constantly monitors the code and It is a special java object that is responsible for guarding security polices for java applications. 
  • Java Security Manager’s responsibilities are not just to prevent applets from accessing local disk or local network and It is always consulted before any potentially dangerous operation is requested by a java application.  
  • Java Security Manager is responsible for determining most of the parameters of the sandbox.
  •  If, for example, a Java application needs to open a file, create a Socket connection to another machine or read some of the properties of the virtual machine, the security manager decide whether or not that particular operation should be permitted. 
  • The security manager is used only if it is explicitly installed, i.e. the application is started with the -Djava.security.manager option. 
  • A security manager may be programmatically installed by calling the System.setSecurityManager() method. 
  • Java applications (by default) have no security manager
FileInputStream constructor
public FileInputStream(File arg0) throws FileNotFoundException {
      this.channel = null;
      this.closeLock = new Object();
      this.closed = false;
      String arg1 = arg0 != null ? arg0.getPath() : null;
      SecurityManager arg2 = System.getSecurityManager();
      if (arg2 != null) {
          arg2.checkRead(arg1);
      }
      /////////////////////////
}
  • If there is a security manager installed and the program is not granted with the corresponding FilePermission, a SecurityException will be thrown. 
  • SecurityException is a subclass of RuntimeException and therefore doesn’t need to be explicitly caught 
Operating on Security Manager

1. The System class provide two methods to work with the security manager 
    SecurityManager getSecurityManager();
    void setSecurityManager (SecurityManager sm);
    
2. There may be at most one security manager in the virtual machine
3. Specifying the parameter -Djava.security.manager force the virtual machine to execute the setSecurityManager() method before it calls the main() method. 
4. It is possible to extends the SecurityManager class to provide a different implementation of the sandbox. 

Methods of the Security Manager:
1. The security manager provide some public methods which can be called anywhere in your own code. 
2. These methods are organised into differents groups :
  • Methods relating to file access 
  • Methods relating to network access 
  • Methods protecting the virtual machine 
  • Methods protecting programs threads 
  • Methods protection system resources 
  • Methods protecting security aspects

6 comments:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging. web design company in velachery

    ReplyDelete
  2. They can take a class face to face, a virtual report gathering, PMI section courses, preparing with an official, concentrating the PMP Examination Specification, perusing the PMP manual just as other investigation material books, including the accreditation handbook. ExcelR PMP Certification

    ReplyDelete
  3. I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.
    ExcelR digital marketing course in sydney

    ReplyDelete