Instantly share code, notes, and snippets.

Embed
What would you like to do?

Someone recently asked me if it is possible to test if a string is in a section or not in YARA. This is my attempt at an answer, and please note that some of the capabilities are still pending a merge to master.

// Make sure the string is in the .rsrc section.
rule test_in {
  strings:
    $a = { DE AD BE EF 00 00 DE AD BE EF }
  condition:
    $a in ((pe.sections[pe.section_index(".rsrc")].raw_data_offset)..(pe.sections[pe.section_index(".rsrc")].raw_data_offset + pe.sections[pe.section_index(".rsrc")].raw_data_size))
}

// Make sure the first occurrence of a string is not in the .rsrc section
rule test_not_in {
  strings:
    $b = "This program cannot be run in DOS mode"
  condition:
    @b[1] < pe.sections[pe.section_index(".rsrc")].raw_data_offset or
    @b[1] > (pe.sections[pe.section_index(".rsrc")].raw_data_offset + pe.sections[pe.section_index(".rsrc")].raw_data_size)
}

// If you don't care what section it is in.
// Note: This requires some changes I have up as a PR in YARA.
rule test_in_2 {
  strings:
    $a = { DE AD BE EF 00 00 DE AD BE EF }
  condition:
    pe.section_index(@a[1]) > 0
}

// If you only care that is not in _ANY_ section.
// Note: This is still open for debate as section_index() will return UNDEFINED instead of -1.
// I have an open question to Victor to see if this is the desired behavior or not.
rule test_not_in_2 {
  strings:
    $b = "This program cannot be run in DOS mode"
  condition:
    pe.section_index(@b[1]) < 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment