3

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?

mat
  • 1,645
  • 15
  • 36

1 Answers1

0

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

Yaron Avital
  • 588
  • 1
  • 4
  • 11