VirusTotal / yara-python

The Python interface for YARA
http://virustotal.github.io/yara/
Apache License 2.0
646 stars 179 forks source link

yara.Error returned for incorrect error types (e.g. yara.TimeoutError) #206

Closed BitsOfBinary closed 2 years ago

BitsOfBinary commented 2 years ago

The documentation says that if a match times out, a yara.TimeoutError should be returned: https://yara.readthedocs.io/en/latest/yarapython.html#yara.Rules.match

However, when testing this and trying to handle yara.Error exceptions separately, these would also catch yara.TimeoutError exceptions. It looks like this is the case because in the code the following exceptions are all just treated as yara.Error exceptions instead of the specific error types they should be: https://github.com/VirusTotal/yara-python/blob/4379581cd67b7ae1e5bd83c4a91bfd648277efc1/yara-python.c#L2683-L2685

Example code:

rule.match(data=file_data, timeout=1)

except yara.Error as e:
    print(str(e))

except yara.TimeoutError as e:
    print(str(e))

If any rule that takes more than 1 second to run times out, a yara.Error will be raised instead of a yara.TimeoutError.

This can be fixed by swapping the except statements around, but I'm not sure if this is expected behaviour?

wxsBSD commented 2 years ago

This is because TimeoutError extends Error, and python checks exceptions in the order you list them. This explains why it works as you expect if you swap the order around in your code. You always want to list most specific to least specific exceptions.

BitsOfBinary commented 2 years ago

Thanks @wxsBSD, that makes sense!