sam-amc / OBLIVION-REPO

0 stars 0 forks source link

Resources should be closed #7

Open armorcodegithubpreprod[bot] opened 2 years ago

armorcodegithubpreprod[bot] commented 2 years ago

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface,AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwisean exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using"try-with-resources" pattern and will be closed automatically.

Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box the applicationis on to their knees.

Noncompliant Code Example

private void readTheFile() throws IOException {  Path path = Paths.get(this.fileName);  BufferedReader reader = Files.newBufferedReader(path, this.charset);  // ...  reader.close();  // Noncompliant  // ...  Files.lines("input.txt").forEach(System.out::println); // Noncompliant: The stream needs to be closed}private void doSomething() {  OutputStream stream = null;  try {    for (String property : propertyList) {      stream = new FileOutputStream("myfile.txt");  // Noncompliant      // ...    }  } catch (Exception e) {    // ...  } finally {    stream.close();  // Multiple streams were opened. Only the last is closed.  }}

Compliant Solution

private void readTheFile(String fileName) throws IOException {    Path path = Paths.get(fileName);    try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {      reader.readLine();      // ...    }    // ..    try (Stream<String> input = Files.lines("input.txt"))  {      input.forEach(System.out::println);    }}private void doSomething() {  OutputStream stream = null;  try {    stream = new FileOutputStream("myfile.txt");    for (String property : propertyList) {      // ...    }  } catch (Exception e) {    // ...  } finally {    stream.close();  }}

Exceptions

Instances of the following classes are ignored by this rule because close has no effect:

Java 7 introduced the try-with-resources statement, which implicitly closes Closeables. All resources opened in a try-with-resourcesstatement are ignored by this rule.

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {  //...}catch ( ... ) {  //...}

See

File Path: webgoat-lessons/jwt/src/main/java/org/owasp/webgoat/jwt/JWTFinalEndpoint.java:167

Mitigation: Use try-with-resources or close this "Statement" in a "finally" clause.

https://preprod.armorcode.ai/#/findings/5407956