Problem setting Policy using Policy.setPolicy  
Author Message
Aaron.Adler





PostPosted: 2003-8-8 3:40:00 Top

java-programmer, Problem setting Policy using Policy.setPolicy Hi,

I'm trying to create my own Policy class and then set the policy to it
using Policy.setPolicy. Doing this doesn't seem to set the policy
correctly. However, if I call setPolicy twice instead of once it seems
to work correctly.

My test consists of trying to create a policy that will only allow
writing to a subdirectory and not to its parent directory. If I only
call setPolicy once, I can write to both the subdirectory and to the
parent directory. If I call setPolicy twice, then writing to the
parent directory causes a SecurityException as it should. The code
that I'm using is included below.

Is there something that I'm doing incorrectly?

Thanks in advance for your help,
Aaron

(I'm also posting this to Sun's "Security General" java forum)

----------


import java.io.IOException;
import java.io.File;
import java.io.FilePermission;

import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;

import java.io.FileWriter;

public class PT {

public static void main(String[] args) {
PT t2 = new PT();
}

public PT() {
// set up policy and security manager

MyPolicy mp = new MyPolicy();

// If you only set the policy once, for some reason it doesn't
// seem to really set the policy and lets you write to both
// the parent and sub directories. If you set the policy twice
// then it seems to work and does not let you write to the
// parent directory.
Policy.setPolicy(mp);
// uncomment the following line to get it to work
//Policy.setPolicy(mp);

System.setSecurityManager(new SecurityManager());

try {
// replace mydir with some appropriate directory
String name = "/mydir/test.txt";
System.out.println("trying to write to "+name);

File f2 = new File(name);
System.out.println("can write? "+f2.canWrite());


FileWriter fw = new FileWriter(name);
fw.write("abc");
fw.close();

System.out.println("wrote to "+name);
}
catch (Exception e) {
e.printStackTrace();
}
try {
// replace mydir and subdir with appropriate directories
String name = "/mydir/subdir/test.txt";
System.out.println("trying to write to "+name);

File f2 = new File(name);
System.out.println("can write? "+f2.canWrite());

FileWriter fw = new FileWriter(name);
fw.write("abc");
fw.close();

System.out.println("wrote to "+name);
}
catch (Exception e) {
e.printStackTrace();
}
}

private class MyPolicy extends Policy {
private Permissions p;
public MyPolicy() {
p = new Permissions();

// make mydir and subdir match the choices above
FilePermission fp = new FilePermission("/mydir/subdir/-",
"read,write,delete");
p.add(fp);
}

public PermissionCollection getPermissions(CodeSource cs) {
return p;
}

public void refresh() {
}
}

}