Java SocketPermission policy question

Vivin Paliath picture Vivin Paliath · Nov 12, 2010 · Viewed 8.2k times · Source

I have a client and server program that attempt to communicate with each other. In my policy file for the server, I have specified the following:

grant signedBy "vivin" {
  permission java.io.FilePermission "-", "read, write";
  permission java.net.SocketPermission "localhost:2220-2230", "accept, connect, listen, resolve", signedBy "vivin";
};

And in my client's policy-file I have:

grant signedBy "vivin" {
  permission java.net.SocketPermission "localhost:2220-2230", "accept, connect, listen, resolve", signedBy "vivin";
};

I start up my server and it listens on port 2225. I then start up my client and it tries to connect to the server that is listening on port 2225. Unfortunately, I get this error on the server:

[java] Exception in thread "main" java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:45944 accept,resolve)
[java]  at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
[java]  at java.security.AccessController.checkPermission(AccessController.java:546)
[java]  at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
[java]  at java.lang.SecurityManager.checkAccept(SecurityManager.java:1157)
[java]  at java.net.ServerSocket.implAccept(ServerSocket.java:457)
[java]  at java.net.ServerSocket.accept(ServerSocket.java:421)

The port number keeps changing; I am assuming that it is the port number for the client (where the server connects back to the client?). Is that correct? For this assignment, there is a restriction specified on the port numbers:

Your client and server should use the Java Security manager, and your project must include policy files for each that defines the necessary permissions for them to run. Allow your server and client to contact each other on localhost using ports in the range 2220-2230.

How can I adhere to this restriction? Or does this only apply to the port that the server listens on? I figure I can make it work if I give accept and resolve permissions for ports greater than 2231. But I don't know if that runs afoul of the restriction.

Answer

ordnungswidrig picture ordnungswidrig · Nov 12, 2010

Because the client choses it's local tcp port randomly (i suppose) you should give it the proper permission:

grant signedBy "vivin" {
  permission java.net.SocketPermission "localhost:1024-", "connect, resolve", signedBy "vivin";
};

The client is not listening for incoming connections and does not need the permissions for "listen" and "accept". On the server you likely can drop the permission for "connect" as long as the server is not making outgoing tcp connection.