|
9 | 9 | from typing import Optional, Callable, List |
10 | 10 | import math |
11 | 11 | import typing as t |
| 12 | +from tokenize import tokenize, NAME, TokenError |
| 13 | +from io import BytesIO |
12 | 14 |
|
13 | 15 | from construct_editor.helper import CallbackList |
14 | 16 |
|
@@ -606,6 +608,14 @@ class HexEditorGrid(Grid.Grid): |
606 | 608 | Grid for editing in hexidecimal notation. |
607 | 609 | """ |
608 | 610 |
|
| 611 | + safe_tokens = [ |
| 612 | + "bytes", "fromhex", "int", "False", "True", "len", "str", "strip", |
| 613 | + "not", "or", "and", "in", "for", "i", "range", "if", "else", "title", |
| 614 | + "lower", "upper", "count", "hex", "decode", "encode", "endswith", |
| 615 | + "startswith", "join", "lstrip", "replace", "rstrip", "split", "rsplit", |
| 616 | + "lsplit", "zfill", "n" |
| 617 | + ] |
| 618 | + |
609 | 619 | def __init__( |
610 | 620 | self, |
611 | 621 | editor: "HexEditor", |
@@ -919,17 +929,48 @@ def _paste(self, overwrite: bool = False, insert: bool = False) -> bool: |
919 | 929 | wx.TheClipboard.GetData(clipboard) |
920 | 930 | wx.TheClipboard.Close() |
921 | 931 | byts_str: str = clipboard.GetText() |
| 932 | + org_byts_str = byts_str |
922 | 933 |
|
923 | 934 | # convert string to bytes |
924 | 935 | try: |
925 | 936 | byts_str = byts_str.replace(" ", "") |
| 937 | + byts_str = byts_str.replace("'", "") |
| 938 | + byts_str = byts_str.replace('"', '') |
926 | 939 | byts = bytes.fromhex(byts_str) |
927 | 940 | except Exception as e: |
928 | | - wx.MessageBox( |
929 | | - f"Can't convert data from clipboard to bytes.\n\n{str(e)}\n\nClipboard Data:\n{byts_str}", |
930 | | - "Warning", |
931 | | - ) |
932 | | - return False |
| 941 | + try: |
| 942 | + g = tokenize(BytesIO(org_byts_str.encode('utf-8')).readline) |
| 943 | + for toknum, tokval, _, _, _ in g: |
| 944 | + if toknum == NAME and tokval not in self.safe_tokens: |
| 945 | + wx.MessageBox( |
| 946 | + f'Unauthorized token "{tokval}" included in ' |
| 947 | + f"input data.\n\nClipboard Data:\n{byts_str}", |
| 948 | + "Error", |
| 949 | + ) |
| 950 | + return False |
| 951 | + except TokenError as e: |
| 952 | + wx.MessageBox( |
| 953 | + f"Malformed input data.\n\n{str(e)}" |
| 954 | + f"\n\nClipboard Data:\n{byts_str}", |
| 955 | + "Error", |
| 956 | + ) |
| 957 | + return False |
| 958 | + try: |
| 959 | + byts = eval(org_byts_str.strip()) |
| 960 | + if not isinstance(byts, bytes): |
| 961 | + wx.MessageBox( |
| 962 | + f"Improper Python string in the clipboard.\n\n{str(e)}" |
| 963 | + f"\n\nClipboard Data:\n{byts_str}", |
| 964 | + "Error", |
| 965 | + ) |
| 966 | + return False |
| 967 | + except Exception as e: |
| 968 | + wx.MessageBox( |
| 969 | + f"Can't convert data from clipboard to bytes.\n\n{str(e)}" |
| 970 | + f"\n\nClipboard Data:\n{byts_str}", |
| 971 | + "Warning", |
| 972 | + ) |
| 973 | + return False |
933 | 974 |
|
934 | 975 | # copy new data to the binary data |
935 | 976 | if overwrite: |
|
0 commit comments