Saturday, 15 July 2017

Update policy file to grant permissions

Below step-by-step procedure explains how to open a policy file and add permissions to it.

Step 1: Open terminal (or) command prompt and run the ‘policytool’ command.

It opens below window.

Step2: File -> Open.

Open the policy file. In my previous post, I created a policy file ‘demoPolicy’. I am going to open that file.

Step 3: Let’s give permissions to the java application to access the properties  'user.home', 'java.home'.

Click on the button ‘Add Policy Entry’. It opens ‘Policy Entry’ window like below.


Type the url ‘file:C:/Users/krishna/Documents/Study/Security/examples’ in codebase field. ‘file:C:/Users/krishna/Documents/Study/Security/examples’ is the location where my Test file is located.

Click on the button ‘Add Permission’.

It opens below dialog box.

From the ‘Permission”’ drop down, select the drop down as ‘PropertyPermission’, it automatically populates the right hand side text fields.

Update the second text field to ‘user.home’.

Select the Actions: as ‘read’.

Press the button Ok.

In the same way, you can add permission to the property ‘java.home’.

Once you added the permission, the window will be updated like below.

Click on the button ‘Done’. You can able to see the newly added code base location below.


Go to File -> Save the policy file.

Contents of the demoPolicy file are updated like below.

demoPolicy
/* AUTOMATICALLY GENERATED ON Sat Jul 15 14:49:43 IST 2017*/
/* DO NOT EDIT */

grant codeBase "https://github.com" {
};

grant codeBase "file:C:/Users/krishna/Documents/Study/Security/examples" {
  permission java.util.PropertyPermission "user.home", "read";
  permission java.util.PropertyPermission "java.home", "read";
};

Now we can run our ‘Test.java’ application, by specify the policy file.


Test.java
public class Test {
 private static void printProperties() {

  String osName = System.getProperty("os.name");
  System.out.println("osName: " + osName);

  String javaVersion = System.getProperty("java.version");
  System.out.println("javaVersion: " + javaVersion);

  String userHome = System.getProperty("user.home");
  System.out.println("userHome: " + userHome);

  String javaHome = System.getProperty("java.home");
  System.out.println("javaHome: " + javaHome);

 }

 public static void main(String args[]) {
  printProperties();
 }
}



Previous                                                 Next                                                 Home

Create policy file in JAVA

Java provides 'policytool' command, to manage (create, edit) policy file. ‘policytool’ command is in the ‘bin’ directory of java installation.

Open command prompt (or) shell and run ‘policytool’ command. It opens below window.

Click on the button ‘Add Policy Entry’. It opens ‘Policy Entry’ window.

By using policy entry, we can specify the permissions for the code from a given code base (for ex: some url like https://github.com) and the organization who signed this code etc.,

What is codebase?
It specifies the location from where the source code exists. If you do not specify any value for this, then it do not add any permission check on from where this code is coming.

What is SignedBy?
It specifies the alias of a certificate that stored in the keystore. The source code must be signed by the private key of the source code provider. By using the public key (of this alias) presented in the keystore, we check the authenticity of the signer.

I just given the codebase name as ‘https://github.com’ and left the SignedBy as empty.

Click on the button ‘Done’. You can see, new policy entry is added.

Save the policy file
File -> Save As…

Give the policy file name as ‘demoPolicy’ and save.

Once the policy file is saved successfully, you can able to see below successful window.

You can open the demoPolicy file in any text editor. ‘demoPolicy’ file has below content

demoPolicy
/* AUTOMATICALLY GENERATED ON Thu Jul 13 12:29:46 IST 2017*/
/* DO NOT EDIT */

grant codeBase "https://github.com" {
};

In my next post, I am going to explain how to update the policy file to grant the permissions.



Previous                                                 Next                                                 Home

Introduction to policy file in Java

Policy file is a simple ASCII text file, that specifies set of rules, that are used by java security manager to prevent the application from performing malicious actions.

Let me try to explain with an example.

PropertyUtil.java
package com.sample.util;

public class PropertyUtil {

 public static void printProperties() {

  String osName = System.getProperty("os.name");
  System.out.println("osName: " + osName);

  String javaVersion = System.getProperty("java.version");
  System.out.println("javaVersion: " + javaVersion);

  String userHome = System.getProperty("user.home");
  System.out.println("userHome: " + userHome);

  String javaHome = System.getProperty("java.home");
  System.out.println("javaHome: " + javaHome);

 }
}

Test.java
package com.sample.app;

import com.sample.util.PropertyUtil;

public class Test {
 public static void main(String args[]){
  PropertyUtil.printProperties();
 }
}

Output
osName: Windows 10
javaVersion: 1.8.0_131
userHome: C:\Users\Krishna
javaHome: C:\Program Files\Java\jre1.8.0_131

Now let’s try to run the same application ‘Test.java’ by enabling security manager. By default security manager is not enabled in Java applications, you need to enable it by using the command line option ‘-Djava.securiy.manager’.


How to enable security manager in Eclipse?

Go to ‘Arguments’ tab and add '-Djava.security.manager' in VM arguments section.


Click on the button ‘Run’, you can able to see the below output.

osName: Windows 10
javaVersion: 1.8.0_131
Exception in thread "main" java.security.AccessControlException: access denied ("java.util.PropertyPermission" "user.home" "read")
 at java.security.AccessControlContext.checkPermission(Unknown Source)
 at java.security.AccessController.checkPermission(Unknown Source)
 at java.lang.SecurityManager.checkPermission(Unknown Source)
 at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
 at java.lang.System.getProperty(Unknown Source)
 at com.sample.util.PropertyUtil.printProperties(PropertyUtil.java:13)
 at com.sample.app.Test.main(Test.java:7)

As you observe the output, java runtime throws 'AccessControlException' exception, while reading the property 'user.home'. It is because, when you ran java application by enabling security manager, it uses the default java policy file, that comes with java installation and apply the permissions defined in the policy file.

Where is the location of java policy file?
It is in the 'lib\security' directory of the java installation.

Windows: java.home\lib\security\java.policy
UNIX: java.home/lib/security/java.policy

Ex:
C:\Program Files (x86)\Java\jdk1.8.0_102\jre\lib\security


java.policy

// Standard extensions get all permissions by default

grant codeBase "file:${{java.ext.dirs}}/*" {
        permission java.security.AllPermission;
};

// default permissions granted to all domains

grant {
        // Allows any thread to stop itself using the java.lang.Thread.stop()
        // method that takes no argument.
        // Note that this permission is granted by default only to remain
        // backwards compatible.
        // It is strongly recommended that you either remove this permission
        // from this policy file or further restrict it to code sources
        // that you specify, because Thread.stop() is potentially unsafe.
        // See the API specification of java.lang.Thread.stop() for more
        // information.
        permission java.lang.RuntimePermission "stopThread";

        // allows anyone to listen on dynamic ports
        permission java.net.SocketPermission "localhost:0", "listen";

        // "standard" properies that can be read by anyone

        permission java.util.PropertyPermission "java.version", "read";
        permission java.util.PropertyPermission "java.vendor", "read";
        permission java.util.PropertyPermission "java.vendor.url", "read";
        permission java.util.PropertyPermission "java.class.version", "read";
        permission java.util.PropertyPermission "os.name", "read";
        permission java.util.PropertyPermission "os.version", "read";
        permission java.util.PropertyPermission "os.arch", "read";
        permission java.util.PropertyPermission "file.separator", "read";
        permission java.util.PropertyPermission "path.separator", "read";
        permission java.util.PropertyPermission "line.separator", "read";

        permission java.util.PropertyPermission "java.specification.version", "read";
        permission java.util.PropertyPermission "java.specification.vendor", "read";
        permission java.util.PropertyPermission "java.specification.name", "read";

        permission java.util.PropertyPermission "java.vm.specification.version", "read";
        permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
        permission java.util.PropertyPermission "java.vm.specification.name", "read";
        permission java.util.PropertyPermission "java.vm.version", "read";
        permission java.util.PropertyPermission "java.vm.vendor", "read";
        permission java.util.PropertyPermission "java.vm.name", "read";
};


How to run above program without error?
By adding below statements to the java.policy file, we can run the program
permission java.util.PropertyPermission "user.home", "read";
permission java.util.PropertyPermission "java.home", "read";

Note
Properties like "user.home", "java.home" are security sensitive, it is recommended to not give permissions to the application about the location of user home directory and java home directory.





Previous                                                 Next                                                 Home

java security tutorial

Policy file

Introduction to policy file in Java
Create policy file in JAVA
Update policy file to grant permissions

JAAS

Introduction to JAAS
JAAS: Hello World Authentication Application
Specifying jaas configuration file location in java security file
JAAS: Reading module options

Miscellaneous

Java Utility Class for Digital Signature with RSA and DSA Support

Previous                                                 Next                                                 Home

Mock instance void method

In this post, I am going to show how to mock instance void methods. Sometimes you don’t want to call void methods, while testing a function (which in turn calling this void method). By using ‘expectLastCall’ method of EasyMock class, you can mock instance void methods.

Following statements are used to mock the instance void method 'sendStringToLogger'.

StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "sendStringToLogger");
stringUtil.sendStringToLogger();
PowerMock.expectLastCall().times(1);
PowerMock.replayAll();

Following is the complete working application.

MethodNotImplementedException.java
package com.sample.model;

public class MethodNotImplementedException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public MethodNotImplementedException() {
  super();
 }

 public MethodNotImplementedException(String message) {
  super(message);
 }

}

StringUtil.java
package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = str.toUpperCase();
  sendStringToLogger();
  return upperCase + upperCase;
 }
 
 public void sendStringToLogger(){
  throw new MethodNotImplementedException();
 }
}


StringUtilTest.java

package com.sample.util;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void toUpperAndRepeatStringTwice() {
  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "sendStringToLogger");

  stringUtil.sendStringToLogger();
  PowerMock.expectLastCall().times(1);
  
  PowerMock.replayAll();

  String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

  assertEquals(result, "HELLO PTRHELLO PTR");

 }
}




Previous                                                 Next                                                 Home

Monday, 10 July 2017

Mocking: Accept any argument of given type to instance method

In my previous post, I explained how to pass any object as an argument to mocked instance method.  In this post, I am going to explain how to tell the mocked method accept any argument of given type. EasyMock class provide 'isA()' by using this we can tell the mocked method to accept any object of this type as argument.

Following snippet is used to mock the method 'toUpper' which accepts any argument of type string and return 'HELLO PTR'.

StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "toUpper");
EasyMock.expect(stringUtil.toUpper(EasyMock.isA(String.class))).andReturn("HELLO PTR").times(1);
EasyMock.replay(stringUtil);
String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

Find the following working application.

StringUtil.java
package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
 public String toUpper(String str) {
  throw new MethodNotImplementedException();
 }

 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = toUpper(str);
  return upperCase + upperCase;
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void toUpperAndRepeatStringTwice() {
  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "toUpper");

  EasyMock.expect(stringUtil.toUpper(EasyMock.isA(String.class))).andReturn("HELLO PTR").times(1);

  EasyMock.replay(stringUtil);

  String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

  assertEquals(result, "HELLO PTRHELLO PTR");

  PowerMock.verifyAll();
 }
}



Previous                                                 Next                                                 Home

Sunday, 9 July 2017

Change context root of a dynamic web project in Eclipse

In this post, I am going to explain how to change the context root of a dynamic project that deployed in tomcat server.

For example, I created new dynamic web project, ‘HelloWorld’ and deployed in tomcat. By default, my project name is the context name.



I am going to show you two approaches to change the context root.
a.   By directly updating the server.xml file of tomcat
b.   By using Eclipse IDE

Since I deployed the application using Eclipse, my server.xml is located in below location.
<ECLIPSE_WORKSPACE>\Servers\Tomcat v7.0 Server at localhost-config

Approach1: By directly updating the server.xml file of tomcat
When you deploy the ‘HelloWorld’ application in tomcat, there is an entry like below is created in server.xml file of tomcat.

<Context docBase="HelloWorld" path="/HelloWorld" reloadable="true" source="org.eclipse.jst.jee.server:HelloWorld"/>

The Context element represents a web application.

Below table summarizes the attributes associated with the Context element.

Attribute
Description
docBase
Pathname to the web application archive file. You may specify an absolute pathname for this directory or WAR file, or a pathname that is relative to the appBase directory of the owning Host
path
The context path of this web application, which is matched against the beginning of each request URI to select the appropriate web application for processing.
reloadable
Set to true, if you want to reload the changes automatically.

Now, open the ‘server.xml’ file, change the value of the attribute ‘path’ to whatever the name you want to give to the context.

For example, I given the name to ‘myDemoApp’.

<Context docBase="HelloWorld" path="/myDemoApp" reloadable="true" source="org.eclipse.jst.jee.server:HelloWorld"/>

Stop the tomcat server.
Start the server


Now hit the url ‘http://localhost:8080/myDemoApp/’, you can able to see below message.


Approach2: By using Eclipse IDE
Right click on the project -> Properties

Go to ‘Web project settings’ and change the context root name to the name that you want.

Apply the settings.

It opens below window. Press Ok.

Clean the server. Right click on the server -> Clean.

Press the button Yes.

Now start the application on server and hit the below url.

You can able to see below window again.


You can open the server.xml file and see the below Context element.

<Context docBase="HelloWorld" path="/testDemo" reloadable="true" source="org.eclipse.jst.jee.server:HelloWorld"/>


Previous                                                    Next                                                    Home