-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathpacking-box
executable file
·165 lines (156 loc) · 8.13 KB
/
packing-box
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from pbox import *
from tinyscript import *
__script__ = "Packing-Box administration tool"
__version__ = "1.3.1"
__doc__ = """
This utility aims to facilitate detectors|packers|unpackers' setup|test according to the related YAML data file.
"""
__description__ = "Setup/test detectors/packers/unpackers (based on the related YAML config)"
__examples__ = [
"config --workspace /home/user/my-workspace --packers path/to/packers.yml",
"list config",
"list packers --name",
"list detectors --all",
"setup packer",
"setup detector peid",
"setup analyzer gettyp",
"show alterations",
"test packer upx ezuri midgetpack",
"test -b unpacker upx",
"workspace view",
"workspace edit MyDataset/data.csv",
]
_call = lambda cmd: subprocess.call(cmd, stderr=subprocess.PIPE)
def _set_subparsers(parent, *items):
sparsers = parent.add_subparsers(dest="type", help="select the type of item")
for i in items:
p = sparsers.add_parser(i)
if i in ["alterations", "features"]:
if parent._name == "test":
p.add_argument("-c", "--config", metavar="YAML", default=str(config[i]), type=yaml_config,
help="%s set's YAML definition" % i)
else:
p.add_argument(i, default=[], action="extend", nargs="*", help="specific %s to %s" % (i, parent._name))
if parent._name == "test":
p.add_argument("-b", "--benchmark", action="store_true", help="enable benchmarking")
if parent._name == "test":
p.add_argument("-f", "--file", default=[], action="extend", nargs="*", help="file to test the %s on" % i)
p.add_argument("-k", "--keep", action="store_true", help="keep test files")
if i not in ["alterations", "features"]:
p.add_argument("--boolean", action="store_true", help="only consider packed or not packed labels")
if __name__ == '__main__':
items = ["alterations", "analyzer", "detector", "features", "packer", "scenarios", "unpacker"]
sparsers = parser.add_subparsers(dest="command", metavar="CMD", title="positional argument",
help="command to be executed")
# level 1 subparsers for cleaning up leftovers and configuring options of pbox
sparsers.add_parser("clean", help="cleanup temporary folders")
p = sparsers.add_parser("config", help="set a config option")
for section in config.sections():
grp = p.add_argument_group("%s options" % section.rstrip("s"))
for opt, func, val, metavar, help in config.iteroptions(section):
# this decorator is required to pass 'func' by reference to the inner scope of '_wrapper' ;
# otherwise, 'func' points to the latest parsed type function, that is the function of the last option
def func2(opt, func):
def _wrapper(v):
f = config.func(opt)
return f(config, v)
_wrapper.__name__ = func.__name__
return _wrapper
grp.add_argument("--" + opt.replace("_", "-"), type=func2(opt, func), default=str(val), metavar=metavar,
help=help)
# level 1 subparser for listing items
p = sparsers.add_parser("list", help="list something")
p.add_argument("type", type=ts.str_matches(r"^(%s)$" % "|".join(sorted([[f"{i}s?", i][i in \
["alterations", "features"]] for i in items] + ["config"]))), help="list items of the selected type")
p.add_argument("-a", "--all", action="store_true", help="show all items, even those that are disabled")
p.add_argument("-c", "--config", metavar="YAML", type=ts.file_exists, help="YAML definition")
p.add_argument("-n", "--name", action="store_true", help="display console name")
# level 1 subparsers for setting and testing items
for n in ["setup", "test"]:
p = sparsers.add_parser(n, help="%s something" % n)
p._name = n
_set_subparsers(p, *items)
# level 1 subparsers for inspecting the workspace
p = sparsers.add_parser("workspace", help="inspect the workspace")
# level 2 subparsers for actions against the workspace
sp = p.add_subparsers(dest="subcommand", help="subcommand to be executed")
sp.add_parser("edit", help="edit something from the workspace") \
.add_argument("item", type=item_exists, help="item to be edited")
sp.add_parser("view", help="view the folders and subfolders tree of the workspace")
# now, initialize arguments
initialize(noargs_action="usage", ext_logging=True, autocomplete=True)
configure_logging(args.verbose)
if args.command == "clean":
for d in ts.TempPath().listdir(filter_func=lambda d: d.is_dir()):
if d.basename.startswith("tmp") or any(d.basename.startswith("%s-%s-" % pair) for pair in \
itertools.product(items, ["setup", "tests"])):
d.remove()
elif args.command == "config":
change = False
for opt, func, val, m, h in config.iteroptions():
v = getattr(args, opt) # func is already applied as 'type' keyword-argument of .parse_argument(...)
if v != func(config, val):
config[opt] = v
logger.debug("set %s to '%s'" % (opt, v))
change = True
if change:
config.save()
logger.debug("Saved config to %s" % str(config._path))
elif args.command == "list":
if args.type == "config":
config.overview()
elif args.type in ["alterations", "features"]:
for name, _ in sorted(load_yaml_config(ts.Path(args.config or str(config[args.type]))), key=lambda x: x[0]):
print(name)
else:
args.type = args.type.rstrip("s")
cls = globals()[args.type.capitalize()]
cls.source = args.config or config['%ss' % args.type]
for x in cls.registry:
if args.all or x.status in x.__class__._enabled:
print(x.name if args.name else x.__class__.__name__)
elif args.command == "workspace":
if args.subcommand == "edit":
p = args.item
if p.is_file() and p.extension == ".csv":
_call(["vd", str(p), "--csv-delimiter", ";"])
elif p.is_file() and p.extension in [".json", ".py", ".txt", ".yaml", ".yml"]:
_call(["vim", str(p)])
elif p.is_dir() and any(p.is_under(x) for x in ["datasets", "models"]) and \
p.joinpath("metadata.json").exists():
_call(["vim", str(p.joinpath("metadata.json"))])
else:
logger.warning("unhandled workspace resource")
elif args.subcommand == "view":
_call(["tree", config['workspace']])
else:
if args.type is None:
logger.error("No item specified")
else:
cls = args.type.capitalize()
if args.type in ["alterations", "features"]:
cls = globals()[cls]
cls.source = args.config
getattr(cls, args.command)(**vars(args))
else:
reg = globals()[cls].registry
selected = list(map(lambda x: x.lower(), getattr(args, args.type))) or [x.name for x in reg \
if x.is_enabled]
for item in reg:
if item.name in selected:
if item.name in selected:
selected.remove(item.name)
try:
r = getattr(item, args.command)(**vars(args))
except Exception as e:
logger.critical("%s %s failed: %s" % (cls, args.command, item.__class__.__name__))
if args.verbose:
logger.exception(e)
continue
if ts.is_generator(r):
for i in r:
pass
for name in selected:
logger.warning("'%s' not found" % name)