java security policy doesn't work as expected, always give AccessControlException - java

First, I've this working code:
import java.io.FileWriter;
import java.io.IOException;
public class TestPolicy {
public static void main(String[] args) {
FileWriter writer;
try {
writer = new FileWriter("testPolicy.txt");
writer.write("hello1");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It runs well with
D:\Documents\myproject\mynet\mytest\java\security\target\classes>java -classpath . TestPolic
And it will generate a new file called [testPolicy.txt]
Then I added a ../../src/myPolicy.txt with content:
grant codeBase "file:D:\Documents\myproject\mynet\mytest\java\security\target\classes*" {
permission java.io.FilePermission "testPolicy.txt", "read,write";
};
I expected, as long as I specified "read,write" permission, it should also run well. But it runs with exception:
D:\Documents\myproject\mynet\mytest\java\security\target\classes>java -classpath . -Djava.security.manager -Djava.security.policy=../../src/myPolicy.txt TestPolicy
Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "testPolicy.txt" "write")
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.checkWrite(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileWriter.<init>(Unknown Source)
at TestPolicy.main(TestPolicy.java:8)
Where did I get wrong, how to fix it?
Thanks a lot.

Use forward slashes instead of backslashes in the codeBase URL in your myPolicy.txt. You may also need a slash between the "classes" and the "*".
Per the PolicyFiles documentation:
Note: a codeBase value is a URL and thus should always utilize slashes (never backslashes) as the directory separator, even when the code source is actually on a Windows system. Thus, if the source location for code on a Windows system is actually C:\somepath\api\, then the policy codeBase entry should look like:
grant codeBase "file:/C:/somepath/api/" {
...
};

Related

I'm writing a javafx custom LoginModule and receive the below AccessControlException concerning javafx permissions. Is this a policy file issue?

Windows 10 - cmd prompt:
I've created a simple JavaFX application that accepts a username and pw. When I attempt to run the code I get the below error message.
All that should be happening initially is a gui gets loaded. When I run this code without security.manager the gui loads and operates correctly, albeit a LoginContext cannot be instantiated. But even when running with security.manager the LoginContext would not be instantiated until the form fields have data inputted and the enter key is pressed. At this early stage the LoginContext or LoginModule should not be playing any role in this problem....I think.
Cmd prompt:\TestLogin>java -classpath LoginMain.jar;TestLoginModule.jar
-Djava.security.manager
-Djava.security.policy==jaasPolicy.policy
-Djava.security.auth.login.config==jaasConfig.config
com.login.LoginGui
/* Login configuration file */
DbLogin {
com.login.security.TestLoginModule required debug=true;
};
/* policy file */
grant codebase "file:./TestLoginModule.jar" {
permission javax.security.auth.AuthPermission "modifyPrincipals";
};
grant codebase "file:./LoginMain.jar" {
permission javax.security.auth.AuthPermission "createLoginContext.TestLoginModule";
};
grant codebase "file:./LoginMain.jar" {
permission javax.security.auth.AuthPermission "createLoginContext.other";
};
public static void main(String[] args) {
try {
/* testing Thread class vs Javafx thread */
//Thread t = new Thread(()->{
System.out.println("launching javafx");
launch(args);
/*
System.out.println("Before sleep");
try {
Thread.sleep(5000);
}catch(InterruptedException ex) {
}
System.out.println("after sleep");
});
t.start();
*/
}catch(Exception ex) {
System.out.println("LoginGui.main -> error -> " + ex.getMessage());
}
}
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.security.AccessControlException: access denied ("java.util.PropertyPermission" "javafx.verbose" "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 java.lang.Boolean.getBoolean(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:241)
... 5 more
If I need to include in my policy file the following permission, java.util.PropertyPermission "javafx.verbose" "read", or some form of it. What's the correct syntax? Where and how in policy do I set this permission?
I'm feeling my way through this process, building custom LoginModules, counting on the error messages to lead me to the promise land.
grant codeBase "file:javafx-sdk-11/lib/javafx.base.jar" {
permission java.security.AllPermission;
};
grant codeBase "file:javafx-sdk-11/lib/javafx.controls.jar" {
permission java.security.AllPermission;
};
grant codeBase "file:javafx-sdk-11/lib/javafx.fxml.jar" {
permission java.security.AllPermission;
};
grant codeBase "file:javafx-sdk-11/lib/javafx.graphics.jar" {
permission java.security.AllPermission;
};
grant codeBase "file:javafx-sdk-11/lib/javafx.media.jar" {
permission java.security.AllPermission;
};
grant codeBase "file:javafx-sdk-11/lib/javafx.swing.jar" {
permission java.security.AllPermission;
};
grant codeBase "file:javafx-sdk-11/lib/javafx.web.jar" {
permission java.security.AllPermission;
};
This should solve your problem
. A good guide to you is check out the bugs.openjdk.java.net
They have a collection of solved & unsolved bugs.^^

Elasticsearch 2.0.0 security manager with groovy script

I'm using brand new Elasticsearch 2.0.0 from a Java application.
When calling the prepareUpdate() method with an inline groovy script that has the following code:
import org.elasticsearch.common.logging.*
import groovy.json.*
ESLogger logger = ESLoggerFactory.getLogger('events-sequence.groovy')
def TOKEN_SEPARATOR = "###"
def flow = [ ]
try {
ctx._source.events.reverseEach { e ->
def context = e.tuplenized_context ? JsonOutput.toJson(e.tuplenized_context) : "[]"
flow << (e.name.toLowerCase() + TOKEN_SEPARATOR + context.toLowerCase())
}
ctx._source.flow = flow.join(TOKEN_SEPARATOR)
} catch (Throwable t) {
logger.error("Error applying derivation", t)
throw t
}
I'm receiving the following exception:
java.security.AccessControlException: access denied ("java.util.PropertyPermission" "groovy.json.faststringutils.write.to.final.fields" "read")
According to the stacktrace, this happens when calling the JsonOutput.toJson() method:
java.lang.ExceptionInInitializerError
at groovy.json.internal.CharBuf.addJsonFieldName(CharBuf.java:516)
at groovy.json.JsonOutput.writeMap(JsonOutput.java:423)
at groovy.json.JsonOutput.writeObject(JsonOutput.java:267)
at groovy.json.JsonOutput.writeIterator(JsonOutput.java:441)
at groovy.json.JsonOutput.writeObject(JsonOutput.java:269)
at groovy.json.JsonOutput.toJson(JsonOutput.java:187)
at groovy.json.JsonOutput$toJson.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at 3974cbb354b454f7c665982a3a8f854ede6125fb$_run_closure1.doCall(3974cbb354b454f7c665982a3a8f854ede6125fb:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1019)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:442)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2030)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.reverseEach(DefaultGroovyMethods.java:2172)
at org.codehaus.groovy.runtime.dgm$532.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:274)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at 3974cbb354b454f7c665982a3a8f854ede6125fb.run(3974cbb354b454f7c665982a3a8f854ede6125fb:17)
at org.elasticsearch.script.groovy.GroovyScriptEngineService$GroovyScript.run(GroovyScriptEngineService.java:248)
at org.elasticsearch.action.update.UpdateHelper.executeScript(UpdateHelper.java:251)
at org.elasticsearch.action.update.UpdateHelper.prepare(UpdateHelper.java:196)
at org.elasticsearch.action.update.UpdateHelper.prepare(UpdateHelper.java:79)
at org.elasticsearch.action.bulk.TransportShardBulkAction.shardUpdateOperation(TransportShardBulkAction.java:408)
at org.elasticsearch.action.bulk.TransportShardBulkAction.shardOperationOnPrimary(TransportShardBulkAction.java:203)
at org.elasticsearch.action.support.replication.TransportReplicationAction$PrimaryPhase.performOnPrimary(TransportReplicationAction.java:579)
at org.elasticsearch.action.support.replication.TransportReplicationAction$PrimaryPhase$1.doRun(TransportReplicationAction.java:452)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.security.AccessControlException: access denied ("java.util.PropertyPermission" "groovy.json.faststringutils.write.to.final.fields" "read")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
at java.security.AccessController.checkPermission(AccessController.java:884)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1294)
at java.lang.System.getProperty(System.java:753)
at groovy.json.internal.FastStringUtils.<clinit>(FastStringUtils.java:37)
... 42 more
In my elasticsearch.yml config file, I've added these 2 lines:
script.inline: on
script.indexed: on
Is there anything else I need to configure so that I can serialize an object to JSON within a groovy script?
EDIT: I've also tried to initialize Elasticsearch setting the following option:
export ES_JAVA_OPTS=-Dgroovy.json.faststringutils.write.to.final.fields\=true
But had no luck, since the problem seems to be that there are no permissions to access the groovy.json.faststringutils.write.to.final.fields system property, whatever its value is.
EDIT 2: All modifying the default java.policy file, specifying a new policy file with the -Djava.security.manager and -Djava.security.policy=file:///my.policy options and disabling the security manager via the -Dsecurity.manager.enabled=false option didn't work.
I've reported this as an issue to the Elasticsearch guys, and they've already fixed it. Actually, here's the commit, but it won't be available until version 2.1.
Is there any workaround or configuration option to make it work now?
None of the other suggestions here worked for me either, but I did find that I could disable the ES security manager by adding the following to my elasticsearch.yml file...
security.manager.enabled: false
Note that this is deprecated as of 2.2.0 and will likely be removed soon. This is not a best practice and should be avoided when dynamic scripts are allowed.
You will have to update your policy file with the system property read permission.
Add: permission java.util.PropertyPermission "groovy.json.faststringutils.write.to.final.fields", "read" to the grant block.
The default policy file (java.policy) resides under $JAVA_HOME/lib/security, unless specified otherwise using java.security.policy system property.
Alternatively, run the JVM without a security manager with -Dsecurity.manager.enabled=false
A better way of implementing it is to define your script under /config/scripts. As your script is static, you gain following advantages out of it:
No inline scripting required which makes your application safe.
Script is compiled once and used again. This gives you performance gain.
No need to change any java security policy.

Java applet with rxtx components for serial communication

I am trying to build an applet that can open a serial port and communicate with the same. I have used rxtxcomm.jar for the serial communications. I have an applet built that works in the eclipese environment perfectly. I built the Jar file and signed the same, but when run in the browser the console shows the foll:
java.lang.ExceptionInInitializerError thrown while loading gnu.io.RXTXCommDriver
Exception in thread "thread applet-zhas_xbeeComm.xtalk-1" java.lang.ExceptionInInitializerError
at zhas_xbeeComm.Xconnect$1.run(Xconnect.java:46)
at java.security.AccessController.doPrivileged(Native Method)
at zhas_xbeeComm.Xconnect.connect(Xconnect.java:40)
at zhas_xbeeComm.xtalk.init(xtalk.java:22)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission loadLibrary.rxtxSerial)
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.checkLink(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:123)
... 6 more
I have even used doPrivileged method around the connect and open functions but it aint working! Please help!!
Here is a snippet of the code of the applet:
{
/** Function to open a port and begin reading and writing */
public void connect ( final String portName ) throws Exception
{
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
// privileged code goes here, for example:
// 1. added try catch for no such port exception;
try {
portIdentifier = CommPortIdentifier.getPortIdentifier(portName); //line 46
} catch (NoSuchPortException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Just had the same problem.
Please make sure that the first call to RXTX library is in doPrivileged block.
If it will try to load library before privileged block - it will fail with this error.
Some additional info:
http://hacky.typepad.com/blog/2009/05/using-rxtxcomm-in-applets.html

Applet signed throw: java.security.AccessControlException. How can I make it run?

After hours of work (I'm not a java programmer) I've managed to pack and put inside an applet wich make an ftp-upload to a remote server. The main file is "prova.class" inside "invia.jar"; I use a third-part library, placed in "edtftpj.jar". I have signed both file and included them in the page with the following code:
Index.html
<applet width="300" height="300" classpath="./" code="prova.class" archive="invio.jar,edtftpj.jar"> </applet>
now, when I point the browser to my page I found this message on the consolle:
Could not read property 'edtftp.log.level' due to security permissions
Could not read property 'edtftp.log.log4j' due to security permissions
Could not read property 'edtftp.log.log4j' due to security permissions
java.security.AccessControlException: access denied (java.net.SocketPermission www.artkiller-web.com resolve)
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.checkConnect(Unknown Source)
at sun.plugin2.applet.Applet2SecurityManager.checkConnect(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getByName(Unknown Source)
at com.enterprisedt.net.ftp.FTPClient.connect(FTPClient.java:966)
at com.enterprisedt.net.ftp.FileTransferClient.connect(FileTransferClient.java:386)
at prova.start(prova.java:44)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Any Idea of how to work-it around?
thank u in advance
ArtoAle
You need to wrap the connection url in a privileged block of code.
Also looks like you are having issues reading from the properties file, The properties file you can package right in your jar, if your trying to read the properties file from the client machine you will need to wrap that code in a privileged block of code as well.
Here is a block of code I used in a another answer for getting a URL through the access controller.
try
{
final String imageURL = "http://www.google.com/intl/en_ALL/images/logo.gif";
URL url = (URL) AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
return new URL(imageURL);
}
catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
}
});
if(url == null)
{
// Something is wrong notify the user
}
else
{
// We know the url is good so continue on
img = ImageIO.read(url);
}
}
catch (IOException e)
{
System.out.println(e);
}

AccessControlException: access denied - caller function failed to load properties file

I am having a jar archive environment which is gonna call my class in a folder like this:
java -jar "emarket.jar" ../tournament 100
My compiled class is deployed into the ../tournament folder, this command runs well.
After I changed my code to load a properties file, it gets the following exception message:
Exception in thread "main" java.security.AccessControlException: access denied (java.io.FilePermission agent.properties 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.checkRead(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at Agent10479475.getPropertiesFromConfigFile(Agent10479475.java:110)
at Agent10479475.<init>(Agent10479475.java:100)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at emarket.client.EmarketSandbox.instantiateClientObjects(EmarketSandbox.java:92)
at emarket.client.EmarketSandbox.<init>(EmarketSandbox.java:27)
at emarket.client.EmarketSandbox.main(EmarketSandbox.java:166)
I am wondering why this security checking will fail. I issue the getPropertitiesFromConfigFile() function inside my class's default constructor, like this:
public class Agent10479475 extends AbstractClientAgent
{
//default constructor
public Agent10479475()
{
//set all properties to their default values in constructor
FT_THRESHOLD = 400;
FT_THRESHOLD_MARGIN = 50;
printOut("Now loading properties from a config file...", "");
getPropertiesFromConfigFile();
printOut("Finished loading","");
}
private void getPropertiesFromConfigFile()
{
Properties props = new Properties();
try
{
props.load(new FileInputStream("agent.properties"));
FT_THRESHOLD = Long.parseLong(props.getProperty("FT_THRESHOLD"));
FT_THRESHOLD_MARGIN = Long.parseLong(props.getProperty("FT_THRESHOLD_MARGIN "));
}
catch(java.io.FileNotFoundException fnfex)
{
printOut("CANNOT FIND PROPERTIES FILE :", fnfex);
}
catch(java.io.IOException ioex)
{
printOut("IOEXCEPTION OCCURED :", ioex);
}
}
}
My class is loading its own .properties file under the same folder. why would the Java environment complains about such a denial of access?
Must I config the emarket.client.EmarketSandbox class, which is not written by me and stored inside the emarket.jar, to access my agent.properties file?
Any hints or suggestions is much appreciated. Many thanks in advance.
Permissions are required to access the system properties files, and your code is clearly running in a sandbox that does not grant the permission. You either need to
modify the sandbox security rules to allow access to that file,
add a specific API you can call to pass the "agent.properties" file contents, or
find some other way to get the properties to your code that doesn't involve reading a file at all.
An example of the last might to pass the properties in the file as command line arguments, or put the file into your JAR file so that you can read it as a resource (modulo the security sandbox not blocking that as well.)
But it must be said that there is something weird about a JAR file that won't let you read files on your own machine. Why is it doing this? Is this a homework exercise ... about security managers, permissions, etc?
You can put the file "agent.properties" inside your jar and access it via getResourceAsStream. As I don't know your security policy in your sandbox in detail, that might work with the permissions or not.

Categories