Repository navigation
Check each file by what the code does to it, and read text as text - #470
MarkusPaulsen wants to merge 20 commits into
Conversation
The first time a student class of another package loads during a test, Byte Buddy reads class files through the class loader, which opens the AspectJ runtime JAR on the boot class path. The file check blamed that read on the student frames below it, the transformation failed, and the agent stopped enforcement, failing every test in ArchUnit with instrumentation, for Maven and Gradle. The file check now skips such a read, as the network check already did. Both now require every frame between the checked call and the Byte Buddy transformer to be the JDK, Byte Buddy or the Ares agent on the system class loader, so a class loader or URL handler of the supervised code keeps the call checked.
Both runtime checks took the String argument of new Scanner(String) and new StringReader(String) for a file name and refused a read of a file called like the text, in all four modes, although neither opens a file. AspectJ now intercepts only the Scanner constructors that take a File or a Path and ignores the charset name next to it. Instrumentation reads no argument of either constructor as a path; a Scanner on a file is checked where it opens the stream underneath. New tests scan and read text and read the permitted file with a charset name, and refuse Scanner(File), Scanner(File, String) and Scanner(Path) on the forbidden file, which no test covered before.
Under AspectJ, an allowed command could write its output into any file, append to one or read its input from a forbidden one through the ProcessBuilder redirects, since the JDK opens those files itself; Ares now checks redirectInput, redirectOutput, redirectError and the Redirect factories as reads and writes, as instrumentation already did. ProcessBuilder.environment() handed supervised code every environment variable, which System.getenv is refused for, and is now refused the same way in both architecture engines. The network policy page says how host names, addresses and listening are matched.
…here they lie Whether writing a file needed createAllFiles or overwriteAllFiles depended on the API. FileWriter, PrintWriter, FileOutputStream and Files.newBufferedWriter fired both a create and an overwrite pointcut, so an existing file needed both flags and the refusal said "overwrite" while the create check had failed. RandomAccessFile "rw", FileChannel.open with CREATE and, under AspectJ, Files.writeString and Files.write were checked as overwrites only, so an overwrite-only policy let them create new files. A create-only policy refused every writer that put content into the new file. Both runtime backends now derive the open mode the way the JDK does: the write methods add WRITE (or CREATE, TRUNCATE_EXISTING, WRITE when given no option), a channel without a write option opens for reading, and a write without CREATE_NEW or CREATE needs the file to exist. An opening for writing becomes one check at the moment it is made: an overwrite when the named file exists, a create when it does not. Files.copy with REPLACE_EXISTING follows the same rule for its destination. A write through a file that is already open (FileChannel, RandomAccessFile) is allowed where either flag covers the file, since its opening was checked. DELETE_ON_CLOSE now adds its delete check instead of replacing the others, and RandomAccessFile.writeBytes/writeChars/writeUTF no longer read their text as a path. Class.getResourceAsStream and ClassLoader.getResourceAsStream are checked as a read of the file the resource is found in (or its JAR), not of the resource name taken as a path relative to the working directory. AspectJ now intercepts Class.getResourceAsStream as well.
…tic rules Under a policy without file allowances the static rules refused System.in.read(), new BufferedInputStream(System.in), a BufferedWriter over System.out, Properties.load(Reader) and, with WALA, reads from byte or char arrays, because the file method lists named the wrappers InputStream.read, Reader, Writer, Buffered* and Properties.load/store. None of them opens a file: the constructor or method that does is listed on its own, so the wrapper entries are removed from both lists. The provider methods newInputStream, newOutputStream, newByteChannel, newFileChannel and newAsynchronousFileChannel are added, since they open a file without any other listed call. The thread list carried a class-level java.lang.Thread entry, so Thread.currentThread(), getName() or isInterrupted() were refused under a policy without thread allowances. The entry is narrowed to what starts, stops, waits for or reconfigures a thread, with the builders and the Arrays.parallel* operations listed explicitly; the getters stay allowed. System.setOut/setErr/setIn were reported as reflection (ArchUnit) or class loading (WALA). They stay refused, since they replace the streams of the whole JVM, but now as environment access. Logger.getLogger(String) was refused as reflection; a named logger is harmless and is allowed, while Logger.addHandler, which lets code run whenever anything in the JVM logs, is refused as environment access. Class.getResourceAsStream moves from the reflection list to the file list and Class.getClassLoader leaves the WALA class-loading list, so a class-path resource is decided by the file permission. With fewer sinks, the WALA run over the ancestor-package fixture now reports a different Ares test class first, one whose method takes an argument; the fixture test accepted only methods without arguments, so its pattern now accepts any parameter list.
ReflectionTestUtils.newInstance and invokeMethod turned every exception of the called code into an AssertionFailedError with a generic text, so an Ares SecurityException read "check your constructor" and assertThrows(SecurityException.class, ...) failed. A SecurityException is now passed on unchanged; other exceptions are still reported as failures.
The file system reference explains that writing needs createAllFiles for a new file and overwriteAllFiles for an existing one, whatever API is used, that a class-path resource is read from the build output, and that wrappers over memory need no entry. The thread reference explains that thread getters are allowed. What Ares does not protect against now says that file metadata (Files.exists, size, timestamps) is not checked. The contributor pages follow the new method lists and action derivation.
Java 25 builds a StringReader on Reader.of(CharSequence), whose class is a nested class of java.io.Reader, so instrumentation again took the text of Scanner(String) and StringReader(String) for a file name. No argument of the constructor of such a JDK nested reader is now read as a path.
… each file Four file operations were checked against the wrong permission, or not at all, in both runtime backends. A file system provider opens files directly: path.getFileSystem().provider().newInputStream(path), newOutputStream, newByteChannel, newFileChannel and newAsynchronousFileChannel. AspectJ did not intercept any of them, and the instrumentation backend did not either, so any file permission let code read and write every file this way. Both backends now intercept them and decide them like the Files methods: by their options, writing by whether the file exists. A provider method counts as one of FileSystemProvider whichever provider class runs it. Files.newInputStream and the provider's newInputStream always read, so an option such as DELETE_ON_CLOSE no longer replaces the read check. Under instrumentation the provider is also the inner step of Files.createTempFile, which the temp-file exemption now accepts. RandomAccessFile in mode "rw", "rws" or "rwd" was checked as a write only, although such a file can be read as well. It now also needs the read permission. Files.move never checked its source for reading, so a policy granting overwrite and delete but not read let code move a secret file into a folder it could read. It also checked both paths for overwrite and delete. Files.move and FileSystemProvider.move now check each side: the source for read and delete, the target for create when it is missing and for overwrite when it exists. FileSystemProvider.copy now follows the Files.copy rule, so under instrumentation the provider step inside Files.copy no longer checks the source as an overwrite. PrintWriter(String|File, String charset) and Formatter(String|File, String charset) read the charset name as a path and refused a correct submission. Only the file argument is checked now. A constructor without arguments, such as new Formatter() inside String.format, names no path and is not filtered. FileOpeningRolesTest checks each case allowed and refused in all four modes. The RandomAccessFile writer leaves FileWriteFlagsTest, whose policies grant no read, and is covered by the new test instead.
A review of the file rework found five gaps. RandomAccessFile in a write mode needed read even for a file that does not exist yet, so under instrumentation ImageIO.write to a new file was refused by a policy granting create, overwrite and delete without read. Opening a file for reading and writing now needs read only when the file exists. ImageIO.createImageOutputStream(File) and new FileImageOutputStream(File) open their file the same way; AspectJ now checks them so too, where it checked the first as a plain overwrite and did not intercept the second. FileSystemProvider.createLink, createSymbolicLink and deleteIfExists were intercepted by neither backend nor listed for the static rules. They now follow Files.createLink, Files.createSymbolicLink and Files.deleteIfExists. SecureDirectoryStream.newByteChannel, newDirectoryStream and move, reachable on macOS as well as on Linux, were not intercepted either. A secure directory stream reads a relative path against its own folder, which Ares cannot see, so both backends now refuse a relative path given to it unless the action is allowed for every path, and check an absolute one like any other. Its move has the roles of Files.move. The static lists named SecureDirectoryStream.deleteFile and deleteDirectory with a Path parameter, which never matches the erased call, so they now name Object. FileChannel.transferTo was always refused under AspectJ, because its write firing reached the unknown-action branch. Under instrumentation the JDK's FileChannelImpl was excluded from instrumentation altogether, so neither transfer was checked and a socket on the other side never went through the network check. FileChannelImpl is now watched for its two transfers only. Both backends recognise the channel by its type and check each side: transferTo needs read on its file, write on a file target and send to a network target; transferFrom needs write on its file, read on a file source and receive from a network source. The instrumentation probe now names the class the agent really reports. The Javadoc of the copy, move and transfer check and the contributor page describe the firings as they now work.
On Linux the provider opens a new temp file through its newFileChannel, which the temp-file exemption did not name, so Files.createTempFile was refused under instrumentation for a policy without file rules.
On Windows a process redirect bypassed the file permissions under instrumentation. ProcessBuilder.redirectOutput(Redirect.appendTo(file)) let an allowed command append to a file the policy does not allow, because the JDK's Windows ProcessImpl opens a redirect file natively when the process starts, and on Linux and macOS only the FileOutputStream it opens there was checked. AspectJ checked the redirect where the student names the file. Instrumentation now does the same: ProcessBuilder.redirectOutput, redirectError, Redirect.to and Redirect.appendTo are checked as a write, a create for a missing file and an overwrite for an existing one, in both backends, and redirectInput and Redirect.from as a read. Only the File argument is read as a path; the command strings held by the builder are not, which before refused every redirect of a builder under AspectJ. On Linux and macOS the stream the JDK opens when the process starts is checked by the same rule, so both checks agree.
Naming a file for a process redirect writes or reads that file, but the static method lists did not name the redirect methods. A policy without any file rule therefore never refused a redirect before the run. Both lists now name ProcessBuilder.redirectInput, redirectOutput and redirectError and Redirect.from, to and appendTo with a File. The tests that expected the refusal at run time without any file rule are now static probes.
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen I found one permission bypass: create-only permission now allows overwriting existing files through writable handles supplied by trusted test code. Please restrict that exemption to handles whose creation Ares actually authorised. Core Integration Tests, Enforcement Integration Tests (WALA + instrumentation), Windows Unit Tests, Windows Core Integration Tests, and Windows Enforcement Integration Tests (WALA + instrumentation) are still running.
…e code created it A write through a file that is already open, such as FileChannel.write, transferFrom or the target of transferTo, was accepted wherever the overwrite or the create rule covered the file, because its opening was checked. A channel the test class opened on an existing file was never checked as an opening, so under a create-only rule the supervised code could replace that file's content through it. Both runtime backends now remember each file that a checked and allowed opening of the supervised code created. For a write through an open file they accept the create rule only for those files; every other file needs the overwrite rule. New tests refuse transferFrom, transferTo and, under AspectJ, FileChannel.write into an existing create-only file through a channel the test class opened, and allow transferFrom into a new file the code opened itself. The redirect tests that build a ProcessBuilder for cat now use its full path from the search path and are skipped where there is none.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen The new regression covers the originally reported supplied-handle case, but creation tracking still grants overwrite access after failed opens and across policy resets. I also confirmed a dangling-symlink escape that I missed earlier. Enforcement Integration Tests (WALA + instrumentation) failed with only exit code 1 and no test report, so I couldn't attribute that failure; eight other checks are still running.
…e the code opened The create rule for a write through a file that is already open was granted by pathname, recorded when the opening was checked. The record outlived the policy that allowed it, and it was written even when the opening then failed, for example new PrintWriter(file, charset) with an unknown charset. A later handle on the same pathname, opened by the test class, then got the create allowance. Both runtime backends now note the new file when they allow an opening that creates it, and remember the handle the opening returns once it has succeeded: instrumentation in exit advice on the read, create and overwrite advice, AspectJ in after returning advice. A failed opening only drops the note. Handles are held weakly and forgotten when another policy is armed or the settings are reset. Only a remembered handle, or the channel of a remembered stream, gets the create rule for a write through it; any other handle needs the overwrite rule. A path that exists but cannot be resolved, such as a link to a missing file, is now refused for every action. Before, a write through such a link was checked at the link's own location while the JDK created the file the link points to. New tests cover a failed opening, a created file replaced at the same pathname, a policy armed again and a write through a link to a missing file, and keep a plain new file through FileOutputStream allowed.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen The earlier reported cases are fixed. I found two new issues: handle tracking can execute student code while enforcement is suppressed, and the link-resolution change blocks permitted deletion of dangling links. Build, Analyse Java, the documentation build and four example jobs are still running.
…link where it lies Looking up a handle in the record of created handles called its hashCode. The target of a transfer can be a channel the supervised code wrote, so that lookup ran the code's own hashCode while the check was in progress. Both backends now put and look up only objects of classes the boot loader defined, whose hashCode and equals are the JDK's own. Refusing a path that exists but cannot be resolved also refused deleting a link to a missing file, although a deletion removes the link and nothing else. A deletion is now checked at the link's own place, in both backends; opening a file through such a link stays refused. New tests transfer to a channel of the supervised code and check that its hashCode was not called, and delete a link to a missing file in a folder the policy lets the code delete in.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen The latest fixes address the handle-hashing and dangling-link deletion cases. I found a link-replacement regression that I missed earlier, plus an overstatement in the new permission documentation. Build, CodeQL, Analyse Java, Analyse Actions, the documentation build and four example jobs remain queued or running.
Files.copy and Files.move with REPLACE_EXISTING onto a link to a missing file were refused, because the destination could not be resolved. The JDK replaces the link itself and does not follow it. Both backends now treat such a destination as an existing file, needing the overwrite rule, and check it at the link's own place. Opening a file through such a link stays refused. The file system reference and the contributor page state that with instrumentation a write or truncate through an open channel is checked where the channel is opened and in transfers, not at each call. New tests replace a link to a missing file by copy and by move in a folder with the overwrite rule, and refuse both in a read-only folder.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen The reported dangling-link replacement cases and instrumentation documentation are fixed. I found an AspectJ overwrite bypass that I missed in the earlier review. Build, both CodeQL analyses, the documentation build and all four example jobs are still running.
…ter its check Under AspectJ the check of Files.writeString runs at the call site of the supervised code, and the JDK then turns the code's text into a string before it opens the file. That text could put a link to an existing file where the new file was to go, and the opening then followed the link. Where the policy lets the code create a missing file but not overwrite it, AspectJ now adds CREATE_NEW to the options of the opening before the check, for the Files, channel and provider methods that take open options. The JDK then refuses a file that is there by the time it opens, and Ares reports that as an overwrite refusal. Instrumentation checks inside the JDK right before the opening and refuses the same call already. New tests write text that puts such a link in place and refuse it in all four modes, and keep a plain new file through Files.writeString allowed.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen The new CREATE_NEW advice fixes the reported link-swap case, and I found no further issues in the current diff. Looks good to me. Unit, core and enforcement test jobs, the Windows Gradle example and Analyse Java are still running.
Summary
Ares now decides each file access by what the code does to each file, the same way in both runtime modes. Correct code was refused: reading text with
ScannerorStringReader, writing a new file under a policy that allows creating files, console stream wrappers, thread getters and plain logging. Process redirects, links, provider streams, moves and channel transfers were decided by another permission than the one the policy names.Linked issues
Split from #461
1. Problem
Correct submissions failed, in all four modes unless named:
new Scanner("4 5")andnew StringReader("a\nb")were refused as reads of a file called like the text.createAllFilesrefusedFiles.writeStringto a new file as an overwrite.System.in,Properties.loadfrom text,Thread.currentThread()andLogger.getLogger.Other accesses were not decided by the permission the policy names for them:
ProcessBuilder.redirectOutput(file)was not checked against the file entry of the policy.ProcessBuilder.environment()was not treated likeSystem.getenv; provider links and streams,SecureDirectoryStream, the read side ofFiles.moveandRandomAccessFile, and channel transfers were checked by another flag or not at all.2. Improvement from the user's perspective
Correct student code that Ares refused before now passes: text scanning, console stream wrappers, plain logging, thread getters, and writes the policy allows by one flag. An instructor's file entry now means the same for every way of using a file:
createAllFilesfor a new file,overwriteAllFilesfor an existing one, read permission for every read. A process redirect needs the file permission for the file it names, andProcessBuilder.environment()gets the same answer asSystem.getenv. UnderReflectionTestUtils, an Ares refusal now reaches the test unchanged.3. Improvement from the maintainer's perspective
New tests cover what nothing covered: Scanner and reader text, write flags per writer, the role of each file in moves, copies, links, transfers and redirects, provider streams, secure directory streams, wrappers and getters under the static rules, and
ReflectionTestUtilspassing a refusal on. Both runtime backends now derive the open mode of a file the way the JDK does, with one shared rule instead of per-method special cases, so AspectJ and instrumentation agree on each case. The contributor pages describe that rule as it now works.4. Testing manual
Prerequisites
echo), and a clone of this repository in a folder without spaces.mainand this branch once each and keep both JARs, from the repository root:git switch mainthenmvn -q install -DskipTests -Pwithout-quality-gates, then copy~/.m2/repository/de/tum/cit/ase/ares/2.2.2to a folderares-mainnext to the clone.git switch fix/enforcement/ares-222-file-system-rolesthen the samemvncommand.~/.m2now holds the branch build as 2.2.2.ares-mainback over~/.m2/repository/de/tum/cit/ase/ares/2.2.2; to run it on the branch, run themvn installcommand of the branch again.examples/ares-exercise-maven. You are the instructor:PenguinTest.javaandsrc/test/resources/SecurityPolicy.yamlare yours,Penguin.javais what a student hands in. Rungit checkout -- examplesandgit clean -fdx examplesafter each step. The change is build-tool independent; the Gradle example behaves the same.Steps
Penguin.java:PenguinTest.java:SecurityPolicy.yaml, add a second entry underregardingFileSystemInteractionswithonThisPathAndAllPathsBelow: "new.txt",createAllFiles: trueand the other four flagsfalse. Runmvn testonce per value oftheFollowingProgrammingLanguageConfigurationIsUsed:JAVA_USING_MAVEN_ARCHUNIT_AND_ASPECTJ,JAVA_USING_MAVEN_ARCHUNIT_AND_INSTRUMENTATION,JAVA_USING_MAVEN_WALA_AND_ASPECTJ,JAVA_USING_MAVEN_WALA_AND_INSTRUMENTATION. Do it on main, then on the branch.notes.txtwith one line in the example folder; the policy has no entry for it. Addpublic static void redirect() throws Exception { new ProcessBuilder("echo", "hello").redirectOutput(new java.io.File("notes.txt")).start().waitFor(); }toPenguin.javaand@PublicTest void refusesARedirectToAnUnlistedFile() { assertThrows(SecurityException.class, Penguin::redirect); }toPenguinTest.java. Runmvn testwithJAVA_USING_MAVEN_ARCHUNIT_AND_ASPECTJon main, then opennotes.txt. Repeat on the branch.regardingCommandExecutionsentry of step 2,public static int env() { return new ProcessBuilder().environment().size(); }toPenguin.javaand@PublicTest void readsTheEnvironment() { assertTrue(Penguin.env() > 0); }toPenguinTest.java. Runmvn testwithJAVA_USING_MAVEN_ARCHUNIT_AND_ASPECTJon main, then on the branch with it and withJAVA_USING_MAVEN_WALA_AND_ASPECTJ.Expected result
scansText,readsTextandwritesANewFilefail in all four modes, with "tried to illegally read the file /4 5 via java.util.Scanner.(java.lang.String)", the same foraandbviajava.io.StringReader.<init>, and "tried to illegally overwrite the file /new.txt via java.nio.file.Files.writeString", althoughnew.txtdid not exist. On the branch all six tests pass in all four modes andnew.txtholdshello.refusesARedirectToAnUnlistedFilefails with "Expected java.lang.SecurityException to be thrown, but nothing was thrown", andnotes.txtnow holdshello: the redirect was not checked against the file entries. On the branch the test passes andnotes.txtkeeps its line. With instrumentation, main already refused this on macOS and Linux.environment()was not checked likeSystem.getenv. On the branch every test fails, in both engines, with "org.example.Penguin.env() tried to illegally access the environment via java.lang.ProcessBuilder.environment()", the refusalSystem.getenvgets.Negative case (what must still be rejected)
rejectsTheForbiddenFilestill passes in every mode, so a read of a file the policy does not list is still refused.@PublicTest void refusesOverwritingAnExistingFile() throws Exception { java.nio.file.Files.writeString(java.nio.file.Path.of("new.txt"), "old"); assertThrows(SecurityException.class, Penguin::writeNew); }. It passes in all four modes:createAllFilesalone does not let the code replace an existing file.static String scanNotes() throws Exception { return new java.util.Scanner(java.nio.file.Path.of("notes.txt")).nextLine(); }and the same withnew java.io.File("notes.txt"), each tested withassertThrows(SecurityException.class, ...). Both pass in all four modes: a Scanner on a file is still checked as a read of that file.mvn test -Dtest='FileOpeningRolesTest,FileWriteFlagsTest,ResourceReadTest,FileSystemAccessReadTest,FileSystemAccessOverwriteTest,StaticRuleNarrowingTest,CommandSystemAccessTest'runs, in all four modes, the refusals and permissions for write flags, the role of each file in moves, copies, links, transfers and redirects, provider streams, secure directory streams, class-path resources, and the static narrowing of wrappers, getters and logging.FileOpeningRolesTestalso refuses a transfer into or out of a channel the test class opened on an existing file undercreateAllFilesonly, after a failed opening, into a replaced file and through a link to a missing file, and allows a transfer into a new file the code opened itself.mvn test -Dtest=ReflectionTestUtilsSecurityExceptionTestshows a refusal reaching the test unchanged.Modes exercised
Steps 1 and 2 were run together in all four modes on main and on the branch (only AspectJ leaves the redirect unchecked on main), and negative case 2 with them; step 3 in ArchUnit and WALA with AspectJ, since the static check decides it. A class of a second package under ArchUnit with instrumentation did not fail on main from either example on this machine, so that fix has no step here. The Windows redirect check runs only on the Windows CI jobs. Under instrumentation a write through an open file channel is checked at its opening and in transfers, not on each
write. Reading an allowed class-path resource under instrumentation also needs the network fix split from #461, which stops the network check from refusing thefile:URL the JDK opens; until thenResourceReadTestcovers the allowed read with AspectJ only.5. Test case coverage regarding this PR
JavaInstrumentationAdviceFileSystemToolboxJavaInstrumentationAdviceAbstractToolboxJavaInstrumentationPointcutDefinitionsReflectionTestUtilsBreaking changes and migration
RandomAccessFiles on existing files,Files.moveandFiles.newInputStreamalso need read permission.createAllFilesfor a new file andoverwriteAllFilesfor an existing one, for every way of writing.target/classes/data.txt.ProcessBuilder.environment()is refused likeSystem.getenv, and a process redirect needs the file permission for the file it names.FileChannel.writeor a transfer, needsoverwriteAllFiles;createAllFilesis enough only through the handle that a checked opening of the code returned when it created the file. Writing through a link to a missing file is refused;REPLACE_EXISTINGonto a link replaces the link and needsoverwriteAllFilesthere.Checklist
documentation/,README.md, Javadoc) was updated where the change is user-facing.Review progress