Semgrep rule for a try/catch block

259 Views Asked by At

I recently tried to create a Semgrep rule for Java code which detects if for a database connection happening in a try/catch block a proper rollback is done.

So what it needs to do is:

  • A Connection object is created using getConnection(...) either before the try or in the try(...) initializer statement
  • A catch block contains a call to connection.rollback()

How would I write such a rule in semgrep which matches a pattern before the try and in the catch block?

1

There are 1 best solutions below

0
On

If I understand you correctly this should work for you:

rules:
  - id: detect-connection-rollback
    patterns:
    - pattern:
        try{$V = getConnection(...);...}  
        catch(Exception e){... $V.rollback(...);...}
    message: Match found
    languages:
      - java
    severity: WARNING