The Java Security Manager allows to specify the permissions of some piece of code by defining clauses like:
...
grant codebase http://foo.bar.com/test.jar {
permission java.io.FilePermission "${user.dir}/*", "read,write"; };
...
in a policy file (default: <JRE_root>\lib\security.
This grants code stemming from the given URL to read and write from/to the user's home directory (which is of course a no-no but that's another story).
But how do I define "NO permission", i.e. if that piece of code should NOT be allowed to read or write anywhere? I tried to specify:
...
permission java.io.FilePermission "/-", "";
...
"/-" means the root directory and everything below it (i.e. everything) and the second argument "" was meant to signal "". But when I specify this like above I get a "token error". Apparently "" is not a valid "action". But how else does one then express "nothing" or "no permission" in these policy files?
Simply don't add any permissions lines. Classes will typically be given permissions to read their own code and resources. (See the API docs for java.io.FilePermission.)
Related
I am trying to write the equivalent java code for setting 600 permission for a file in Windows. Below is the method I am using:
acl.setPermissions(EnumSet.of(
AclEntryPermission.READ_DATA, AclEntryPermission.WRITE_DATA, AclEntryPermission.WRITE_ATTRIBUTES,
AclEntryPermission.SYNCHRONIZE, AclEntryPermission.WRITE_NAMED_ATTRS, AclEntryPermission.APPEND_DATA
));
I tried to create file using only AclEntryPermission.READ_DATA and AclEntryPermission.WRITE_DATA but I get access-denied error.
Unless I add the other parameters listed in above method, file is not being created.
Can someone brief or point me to a resource explaining the other attributes ( I tried to google but I only get the oracle docs link giving a one line explanation of the attribute) ?
Also please tell if I need to add any other parameters from the AclEntryPermission enum.
I have to make some code for java classes about files permission, and I found FilePermission class. But when I tried to use it to change my files permissions, nothing happened. I know i can use file.setReadable or something. But my question is whether I can change permissions using FilePermission class and if not what this class is meant for
String pathToFolder="C:\\tmp\\file.txt";
FilePermission folderPermission = new FilePermission("C:\\tmp\\*", "read");
PermissionCollection permission = folderPermission.newPermissionCollection();
permission.add(folderPermission);
FilePermission dataPermission = new FilePermission(pathToFolder, "write");
permission.add(dataPermission);
if(permission.implies(new FilePermission(pathToFolder, "read, write"))) {
System.out.println("Read, Write permission is granted for the path "+pathToFolder);
}
else {
System.out.println("No Read, Write permission is granted for the path " + pathToFolder);
}
Now I can use it to compare two permissions on PermissioCollection, but it still doesnt change permissions on real files.
Thanks for all your help and sorry for my English.
Java documentation for FilePermission, clearly states that, this java class is used to represent the actions (i.e read/write/delete/execute/readlink). It does NOT change the permission of existing file/folder.
You can tough perform an "implies" action as you have defined in your example.
FilePermission class helps to resolve crucial file access decisions (using implies method) which if implemented manually can lead to errors or security breaches like any other permission class.
I have a series of folders containing books on a server which I am accessing with this piece of code. I want to make each of these folders an object so I can do some work with the files inside them later on. I'm trying to use this method to return a list of the folders as Book objects.
public List<Book> getBooks(File folder){
List<Book> books = new ArrayList<Book>();
for (File f : folder.listFiles()){
if (f.isDirectory()){
System.out.println(f.getAbsolutePath() + "" + f.listFiles());
books.add(new Book(f));
}
}
return books;
}
The println statement in this block is printing, as it should, the direct path to the folder and then the memory address along with some other information. However, somewhere in the folder it is printing out null when listFiles() is called. The folder that it is doing this on is not empty. This supposedly empty folder is then passed to my class init method.
public Book(File bookFolder) {
this.bookFolder = bookFolder;
this.bookPath = bookFolder.getAbsolutePath();
System.out.println(bookFolder + " " + bookFolder.listFiles());
for (File f : bookFolder.listFiles()) {
...
}
}
The println statement in this block prints out the exact same path to the folder and then a different memory address, which is also expected. When it hits the "empty" folder it prints null for the memory address again.
Now, for the real issue, the line with the for loop is where the program crashes and throws a NullPointerException which isn't even described in the documentation for the listFiles method.
Why could this be happening? Also, why are my non-empty folders returning null?
The documentation for the listFiles() method clearly states that it "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs."
One of the most common reasons that a directory cannot be listed is that the process lacks the right permissions. Are you running this as yourself, or in some sort of service that runs as a different user?
By the way, the File API is a great example of how bad life can be without exceptions.
For developers who have already included the following solutions :
Added the storage permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2.The directory from you want to list the files exists.
Enabled the permission in the device you are testing in the app permission settings
BELOW CODE WILL SOLVE YOUR PROBLEM IF YOUR DEVICE SDK IS GREATER THAN OR EQUALS TO ANDROID 10(Q)
In the manifest file include this code inside tag
<application android:requestLegacyExternalStorage="true"...</application>
Let me know if your problem is solved!
I had a similar problem with dir.listfiles(); returning null for the user folder \AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\
it was the folder had by default Permissions set on "everyone" Deny all
what screwed me over i think was the fact that I never expected any Deny permission to exist there.
also for any one thats unclear on what i mean by a deny permission
when you set deny for user permissions it overrides the allow for user permissions unless you remove it and it was on a default install of windows 10 home.
For me it was caused by trailing spaces. Use variable.trim()
I want to know whether the user launched our Java-based application from a read-only file system like from a .dmg, so functions like auto-update will be able to show meaningful information instead of aborting with an error. I first thought checking the .app's path would be sufficient (when launched from a .dmg it is something like /Volumes/MyApp 1.2.3/MyApp.app, but this won't work, because the user might have installed the application on a different partition. What other things may I check?
You can use -[NSURL getResourceValue:forKey:error:] with the key NSURLVolumeIsReadOnlyKey. You would apply this to the app bundle URL as returned by [[NSBundle mainBundle] bundleURL]. So:
NSBundle* bundle = [NSBundle mainBundle];
NSURL* bundleURL = bundle.bundleURL;
NSNumber* readOnly;
NSError* error;
if ([bundleURL getResourceValue:&readOnly forKey:NSURLVolumeIsReadOnlyKey error:&error])
{
BOOL isReadOnly = [readOnly boolValue];
// act on isReadOnly value
}
else
{
// Handle error
}
If OSX is POSIX compliant, to determine if filesystem is mounted R/O, You can use statvfs() or fstatvfs(), returned struct statvfs field f_flag should have ST_RDONLY bit set for R/O filesystem.
As it was pointed in comments, check if this information is correctly provided by OS.
JNA and this question may be usefull for Java.
A few more ideas, which may be usefull here (access(), open(), utime() ).
OS X specific statfs() may be used too, but this function is not portable (Linux and *BSD have slightly different statfs() functions).
You can also check directly from Java whether a certain path points to something within a read-only directory by querying the FileStore associated with your path:
File classpathRoot = new File(MyClass.class.getClassLoader().getResource("").getPath());
/* getPath() actually returns a String instead of a Path object,
* so we need to take this little detour */
Path yourAppPath = classpathRoot.toPath();
boolean isReadOnly = Files.getFileStore(yourAppPath).isReadOnly();
I am testing that a method I have written is throwing a file exception. I am triggering the exception by setting the read permissions on the file to false
File f = new File(unreadableFile);
f.setReadable(false);
// Run test
f.setReadable(true);
The problem is that the f.setReadable(true) is not setting the permissions back to what they should be. I have another test which tests the normal mode of operations, and it always fails because f.setReadable(true) didn't restore the file to what it was before the exception test was run. I have checked the permissions on disk, and it is wrong.
Quoting the docs
Returns true if and only if the operation succeeded. The operation will fail if the user does not have permission to change the access permissions of this abstract pathname. If readable is false and the underlying file system does not implement a read permission, then the operation will fail.
Check the return value and check if you have permissions to do the operation. The operation is much like delete() and can fail if the you do not have permissions.