Skip to content

Empty Finally Block Vulnerability

What does this mean ?

Finally blocks must be used to run the code that is required after the try and/or catch blocks have been completed. It is often used to code the release of resources utilised in the try block. When an exception handling block, such as Finally, is used but the block is empty, the software may not execute successfully. If an attacker can access the necessary code, this dependability issue may provide a vulnerability.

What can happen ?

An empty finally block is most likely an indication of possible "resource leaks" that will compromise the application's stability.

Recommendation

  • Add code to the finally block, especially the release of resources used in the try block, if any.

Sample Code

Vulnerable :

try
{
    text = File.ReadAllText(fileName);
}
catch (Exception exc)
{
    logger.Log(exc);
}
finally
{
    //doSomething(); // Vulnerable
}

Non Vulnerable :

try
{
    text = File.ReadAllText(fileName);
}
catch (Exception exc)
{
    logger.Log(exc);
}
finally
{
    doSomething(); // Non Vulnerable
}

Vulnerable :

try {
    rs = stmt.executeQuery(query);
}
catch(SQLException e) {
    log(e);
}
finally {
    //doSomething(); // vulnerable code
}

Non Vulnerable :

try {
  rs = stmt.executeQuery(query);
}
catch(SQLException e) {
  log(e);
}
finally {

    doSomething(); // Non vulnerable code
}

Vulnerable :

try {
  foo(); 
} catch (SomeCustomException $e) { 
  echo $e->getMessage(); 
} finally {
    //doSomthing(); // Vulnerable
}

Non Vulnerable :

try {
  foo(); 
} catch (SomeCustomException $e) { 
  echo $e->getMessage(); 
} finally {
    doSomthing(); // Non Vulnerable
}

Vulnerable :

try { 
  callback(); 
} catch (e) {
  console.log("Failed to run", e);
} finally {
    // doSomething(); // Vulnerable
}

Non Vulnerable :

try { 
  callback(); 
} catch (e) {
  console.log("Failed to run", e);
} finally {
    doSomething(); // Non Vulnerable
}

References