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

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);
}

Related

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

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/" {
...
};

javax.net.ssl.SSLException: Invalid Padding length

I am getting this exception when trying to execute a webservice over https. This exception occures the movement I try to get the service instance.
I followed the below steps for generating the webservice client using wsImport.exe tool.
I manualy downloaded the wsdl from the site
Used wsImport tool to generate the client java files
Added the java files to my project in eclipse
Wrote a test client as below to test the service instance
public static void main(String[] args) {
String certificatesTrustStorePath = "c:/Apps/Java/jdk1.8.0_25/jre/lib/security/cacerts";
// if I don't set the store path, I get below error
//javax.net.ssl.SSLHandshakeException:
//sun.security.validator.ValidatorException: PKIX path building failed:
//sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
System.setProperty("javax.net.ssl.trustStore", certificatesTrustStorePath);
URL wsdlLocation = null;
String https_url ="https://localhost/services/WebService/wsdl/WebService.wsdl";
try {
wsdlLocation = new URL(https_url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//This is the line where I get the below execption
WebServiceService webServiceService = new WebServiceService(wsdlLocation,
new QName("http://webservice.com", "WebServiceService"));
}
With the above code I below execption
Exception in thread "main" com.sun.xml.internal.ws.wsdl.parser.InaccessibleWSDLException: 2 counts of InaccessibleWSDLException.
javax.net.ssl.SSLException: Invalid Padding length: 76
javax.net.ssl.SSLException: Invalid Padding length: 50
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(Unknown Source)
at javax.xml.ws.Service.<init>(Unknown Source)
at com.webservice.WebServiceService.<init>(WebServiceService.java:42)
at com.client.Client.main(Client.java:46)
Everytime I execute, the numbers in the front ot "Invalid Pad length" is different. this time it is 76 and 50. other time it was 67, 106. etc
Please help,
I am using latest version of Java i.e. 1.8.0_51.
It seems similar to this problem: https://community.oracle.com/thread/2506695
Have you tried using bouncycastle?
Java 8 has this issue... tested with Java 7. Same code is working fine.

What's the difference between http://localhost:8000/ and http://127.0.0.1:8000/ for Java Applets

I have a question/problem related to Java Applet security...
I use the Applet that has to take files from server (ASP.NET) and represent the information from it. Applet take files using the code:
URL u = new URL(getCodeBase(), filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
This code appears in two places:
Init() method
Some another method Test() that called manually from JavaScript
So, when I try to load the page with Applet using the URL http://127.0.0.1:8000/Test.aspx, everything works fine and I can read file content from both methods. But if I change the URL on http://localhost:8000/, only the first method works properly and I can get files content and for the second one I get the next error message in JavaConsole:
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,resolve)
What it the difference in this case? Why 'localhost' is impossible in this case? Is there any way how to grant access to 'localhost' the same as 127.0.0.1?
here is simplest applet's example:
public class TestApplet extends Applet {
public void init()
{
System.out.println( "init...");
readDocument();
}
public void readDocument()
{
System.out.println( "read test.txt file...");
URL base = getCodeBase();
String filename = "test.txt";
try {
URL u = new URL(base, filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
System.out.println(d.readLine());
System.out.println("Done!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and next code used on the client side:
<applet archive="/Content/test.jar" code="test.TestApplet.class" name="testApplet" mayscript></applet>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var testApplet = document.testApplet;
testApplet.readDocument();
});
</script>
this code works perfectly when I try to use http://127.0.0.1:8000/Test.aspx
and doesn't work when I user http://localhost:8000/Test.aspx. I java console I see the next:
init...
read test.txt file...
some text...
Done!
read test.txt file...
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,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.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.TestApplet.readDocument(TestApplet.java:30)
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.plugin.javascript.JSInvoke.invoke(Unknown Source)
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.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
P.S.: Applet is signed.
The problem is the call from JavaScript. If you are using JavaScript to call your method, the permissions of the call get down to the intersection of the JavaScript bridge's permissions (i.e. nothing) and the permissions of your own code - even if your own code is signed.
To avoid this, and use the full privileges of your applet's code, put the security-relevant parts inside a AccessController.doPrivileged(...) call. (Of course, your applet should first check that this can't do anything malicious.)
I have no idea why it works if you are using the IP address directly instead of localhost, though.
localhost is an alias for 127.0.0.1 so you may have to set/fix it in your enviroment. Under Windows you have to edit the file C:\Windows\System32\drivers\etc\hosts.
localhost is typically resolved to both ::1 and 127.0.0.1 and the OS/libc is usually set up so that IPv6 is preferred in these circumstances.
Therefore, it's likely you're allowing only 127.0.0.1 and not IPv6 connections from ::1.

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

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