Skip to content

Commit 88f3cec

Browse files
committed
Python expressions from the clipboard
1 parent 0f7c8ce commit 88f3cec

File tree

1 file changed

+46
-5
lines changed

1 file changed

+46
-5
lines changed

construct_editor/widgets/hex_editor.py

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
from typing import Optional, Callable, List
1010
import math
1111
import typing as t
12+
from tokenize import tokenize, NAME, TokenError
13+
from io import BytesIO
1214

1315
from construct_editor.helper import CallbackList
1416

@@ -606,6 +608,14 @@ class HexEditorGrid(Grid.Grid):
606608
Grid for editing in hexidecimal notation.
607609
"""
608610

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+
609619
def __init__(
610620
self,
611621
editor: "HexEditor",
@@ -919,17 +929,48 @@ def _paste(self, overwrite: bool = False, insert: bool = False) -> bool:
919929
wx.TheClipboard.GetData(clipboard)
920930
wx.TheClipboard.Close()
921931
byts_str: str = clipboard.GetText()
932+
org_byts_str = byts_str
922933

923934
# convert string to bytes
924935
try:
925936
byts_str = byts_str.replace(" ", "")
937+
byts_str = byts_str.replace("'", "")
938+
byts_str = byts_str.replace('"', '')
926939
byts = bytes.fromhex(byts_str)
927940
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
933974

934975
# copy new data to the binary data
935976
if overwrite:

0 commit comments

Comments
 (0)