Skip to content

Commit

Permalink
update scripts/lint.py to validate rule metadata using pydantic
Browse files Browse the repository at this point in the history
  • Loading branch information
mike-hunhoff committed Aug 12, 2022
1 parent 81cb4b3 commit 70090d7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
-

### Bug Fixes
- linter: use pydantic to validate rule metadata #1141 @mike-hunhoff

### capa explorer IDA Pro plugin

Expand Down
23 changes: 10 additions & 13 deletions scripts/lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from dataclasses import field, dataclass

import tqdm
import pydantic
import termcolor
import ruamel.yaml
import tqdm.contrib.logging
Expand All @@ -45,6 +46,7 @@
import capa.features.insn
from capa.rules import Rule, RuleSet
from capa.features.common import FORMAT_PE, FORMAT_DOTNET, String, Feature, Substring
from capa.render.result_document import RuleMetadata

logger = logging.getLogger("lint")

Expand Down Expand Up @@ -226,19 +228,13 @@ def check_rule(self, ctx: Context, rule: Rule):
class IncorrectValueType(Lint):
name = "incorrect value type"
recommendation = "Change value type"
recommendation_template = 'Change type of "{:s}" from "{:s}" to "{:s}'
types = {
"references": list,
"authors": list,
}

def check_rule(self, ctx: Context, rule: Rule):
for k, expected in self.types.items():
value = rule.meta.get(k)
found = type(value)
if value and found != expected:
self.recommendation = self.recommendation_template.format(k, str(found), str(expected))
return True
try:
_ = RuleMetadata.from_capa(rule)
except pydantic.ValidationError as e:
self.recommendation = str(e).strip()
return True
return False


Expand Down Expand Up @@ -722,11 +718,11 @@ def lint_scope(ctx: Context, rule: Rule):
MissingExamples(),
MissingExampleOffset(),
ExampleFileDNE(),
IncorrectValueType(),
UnusualMetaField(),
LibRuleNotInLibDirectory(),
LibRuleHasNamespace(),
InvalidAttckOrMbcTechnique(),
IncorrectValueType(),
)


Expand Down Expand Up @@ -1003,8 +999,9 @@ def main(argv=None):

try:
rules = capa.main.get_rules(args.rules, disable_progress=True)
rule_count = len(rules)
rules = capa.rules.RuleSet(rules)
logger.info("successfully loaded %s rules", len(rules))
logger.info("successfully loaded %s rules", rule_count)
if args.tag:
rules = rules.filter_rules_by_meta(args.tag)
logger.debug("selected %s rules", len(rules))
Expand Down

0 comments on commit 70090d7

Please sign in to comment.