-
Notifications
You must be signed in to change notification settings - Fork 456
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement Custom UTF-8 Decoder #885
Open
Arker123
wants to merge
18
commits into
mandiant:master
Choose a base branch
from
Arker123:utf8_decoder
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
cfeb127
Implement UTF-8 Decoder
Arker123 e083376
Tweaks
Arker123 4a54532
Minor changes
Arker123 775f1ce
Discovered more i386 xrefs
Arker123 18e6080
Enhance percentage extraction to 91% 😄
Arker123 6d8e314
Merge branch 'master' into utf8_decoder
Arker123 8515899
Clean up
Arker123 51525ae
Added extract_utf8_strings_from_buffer
Arker123 1f5f3eb
Code style
Arker123 3d1093a
Merge branch 'master' of https://github.com/Arker123/flare-floss into…
Arker123 a5e46ae
Tweaks
Arker123 3105843
Minor bug
Arker123 7481274
Tweaks
Arker123 60b3ca6
Add tests
Arker123 272770d
Update floss/language/rust/decode_utf8.py
Arker123 770955c
Tweaks
Arker123 a354b30
Update tests/test_language_rust_coverage.py
Arker123 960f2c0
Several Refinements
Arker123 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved. | ||
import sys | ||
import pathlib | ||
import argparse | ||
from typing import Any, List, Tuple, Iterable, Optional | ||
from collections import namedtuple | ||
|
||
import pefile | ||
|
||
import floss.logging_ | ||
from floss.language.utils import get_rdata_section | ||
|
||
MIN_STR_LEN = 4 | ||
|
||
logger = floss.logging_.getLogger(__name__) | ||
|
||
|
||
def extract_utf8_strings_from_buffer(buf, min_length=MIN_STR_LEN) -> List[List[Tuple[str, int, int]]]: | ||
""" | ||
Extracts UTF-8 strings from a buffer. | ||
""" | ||
|
||
# Reference: https://en.wikipedia.org/wiki/UTF-8 | ||
|
||
character_info = namedtuple("character_info", ["character", "position", "length"]) | ||
character_and_index = [] | ||
|
||
for i in range(0, len(buf)): | ||
# for 1 byte | ||
if buf[i] & 0x80 == 0x00: | ||
# ignore is used below because decode function throws an exception | ||
# when there is an character where the if condition is satisfied but it is not a valid utf-8 character | ||
character = buf[i].to_bytes(1, "big").decode("utf-8", "ignore") | ||
character_and_index.append(character_info(character, i, 1)) | ||
|
||
# for 2 bytes | ||
elif buf[i] & 0xE0 == 0xC0: | ||
temp = buf[i] << 8 | buf[i + 1] | ||
character = temp.to_bytes(2, "big").decode("utf-8", "ignore") | ||
i += 1 | ||
character_and_index.append(character_info(character, i, 2)) | ||
|
||
# for 3 bytes | ||
elif buf[i] & 0xF0 == 0xE0: | ||
temp = buf[i] << 16 | buf[i + 1] << 8 | buf[i + 2] | ||
character = temp.to_bytes(3, "big").decode("utf-8", "ignore") | ||
i += 2 | ||
character_and_index.append(character_info(character, i, 3)) | ||
|
||
# for 4 bytes | ||
elif buf[i] & 0xF8 == 0xF0: | ||
temp = buf[i] << 24 | buf[i + 1] << 16 | buf[i + 2] << 8 | buf[i + 3] | ||
character = temp.to_bytes(4, "big").decode("utf-8", "ignore") | ||
i += 3 | ||
character_and_index.append(character_info(character, i, 4)) | ||
|
||
else: | ||
logger.trace("Invalid UTF-8 character at offset %d", i) | ||
|
||
prev = False | ||
strings = [] | ||
|
||
for i in range(0, len(character_and_index)): | ||
if character_and_index[i].character.isprintable(): | ||
if prev == False: | ||
strings.append( | ||
[character_and_index[i].character, character_and_index[i].position, character_and_index[i].position] | ||
) | ||
prev = True | ||
else: | ||
strings[-1][0] += character_and_index[i].character | ||
strings[-1][2] = character_and_index[i].position | ||
else: | ||
prev = False | ||
|
||
# filter strings less than min length | ||
strings = [string for string in strings if len(string[0]) >= min_length] | ||
|
||
return strings | ||
|
||
|
||
def extract_rdata_utf8_strings(pe: pefile.PE, min_length=MIN_STR_LEN) -> List[List[Tuple[str, int, int]]]: | ||
""" | ||
Extracts UTF-8 strings from the .rdata section of a PE file. | ||
""" | ||
try: | ||
rdata_section = get_rdata_section(pe) | ||
except ValueError as e: | ||
logger.error("cannot extract rust strings: %s", e) | ||
return [] | ||
|
||
buf = pe.get_memory_mapped_image()[ | ||
rdata_section.VirtualAddress : rdata_section.VirtualAddress + rdata_section.SizeOfRawData | ||
] | ||
strings = extract_utf8_strings_from_buffer(buf, min_length) | ||
return strings | ||
|
||
|
||
def extract_utf8_strings(pe: pefile.PE, min_length=MIN_STR_LEN) -> List[List[Tuple[str, int, int]]]: | ||
""" | ||
Extracts UTF-8 strings from a PE file. | ||
""" | ||
# Can be extended to extract strings from other sections | ||
return extract_rdata_utf8_strings(pe, min_length) | ||
|
||
|
||
def main(argv=None): | ||
parser = argparse.ArgumentParser(description="Get Rust strings") | ||
parser.add_argument("path", help="file or path to analyze") | ||
parser.add_argument( | ||
"-n", | ||
"--minimum-length", | ||
dest="min_length", | ||
type=int, | ||
default=MIN_STR_LEN, | ||
help="minimum string length", | ||
) | ||
args = parser.parse_args(args=argv) | ||
|
||
pe = pathlib.Path(args.path) | ||
buf = pe.read_bytes() | ||
pe = pefile.PE(data=buf, fast_load=True) | ||
|
||
strings = extract_utf8_strings(pe, args.min_length) | ||
print(strings) | ||
for string in strings: | ||
print(string[0]) | ||
|
||
|
||
if __name__ == "__main__": | ||
sys.exit(main()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import pathlib | ||
|
||
import pytest | ||
|
||
from floss.results import StaticString, StringEncoding | ||
from floss.language.rust.extract import extract_rust_strings | ||
|
||
|
||
@pytest.fixture(scope="module") | ||
def rust_strings64(): | ||
n = 1 | ||
path = pathlib.Path(__file__).parent / "data" / "language" / "rust" / "rust-hello" / "bin" / "rust-hello64.exe" | ||
return extract_rust_strings(path, n) | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"string,offset,encoding,rust_strings", | ||
[ | ||
# For 1 character strings | ||
pytest.param("Hello, world!", 0xBB030, StringEncoding.UTF8, "rust_strings64"), | ||
# For 2 character strings | ||
pytest.param("۶ж̶ƶ", 0xC73E3, StringEncoding.UTF8, "rust_strings64"), | ||
# For 3 character strings | ||
pytest.param("jd8n8n헧??", 0xD3CE2, StringEncoding.UTF8, "rust_strings64"), | ||
# For 4 character strings | ||
pytest.param("&ޓޓttt", 0xD41F8, StringEncoding.UTF8, "rust_strings64"), | ||
], | ||
) | ||
def test_utf8_decoder(request, string, offset, encoding, rust_strings): | ||
assert StaticString(string=string, offset=offset, encoding=encoding) in request.getfixturevalue(rust_strings) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why do you use
ignore
here? wouldn't we want to handle the case that invalid UTF-8 data is encountered (and not extract a string there)?I assume that your algorithm works pretty well, since you've opened the PR, but I can't quite follow how it works. Would you please add some comments explaining the design, and definitely a few test cases that exercise each of the branch arms?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi, the tests for each branch are in
tests/test_utf8_decoder.py
. Let me know if anything else is required.