-
Notifications
You must be signed in to change notification settings - Fork 29
/
mndb.py
executable file
·144 lines (118 loc) · 4.84 KB
/
mndb.py
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
#!/usr/bin/env python3
import os
import sys
import getopt
import configparser
import requests
from typing import Any
USAGE = '''Usage: mndb.py [-h] [-v] [-k <apikey>] [-n <items>] <queries>...
query Windows magic numbers from MagNumDB (https://www.magnumdb.com/).
-h, --help display this help and exit
-v, --verbose show verbose results (e.g. GUID formats)
-k, --apikey specify API key (default to read from config)
-n, --items maximum number of items per query (default to read from config)
config file (~/.config/mndb.conf) takes the form of:
[mndb]
apikey=<your API key here>
items=<default maximum>
to obtain an API key, please contact the maintainers of MagNumDB.
'''
def print_value_item(verbose: bool, item: dict[str, Any]) -> None:
if 'HexValue' in item and 'SignedValue' in item:
print(f'\thex {item["HexValue"]} / signed {item["SignedValue"]} / unsigned {item["Value"]}')
elif 'Value' in item:
print(f'\t{item["Value"]}')
else:
print(f'\t// no value available; enable verbose mode?')
# XXX: Certain GUID entries is of ValueItem
if verbose and 'GuidFormats' in item:
print('\n'.join('\t' + x for x in item['GuidFormats'].split('<br/>')))
def main(argv: list[str]) -> int:
try:
opts, args = getopt.getopt(argv[1 : ], 'hvk:n:', ['help', 'verbose', 'apikey=', 'items='])
except getopt.GetoptError as exc:
print(f'{argv[0]}: argument parse error: {exc}', file = sys.stderr)
return 1
if len(args) == 0:
print(USAGE, file = sys.stderr)
return 0
verbose = False
apikey: str = None
items = -1
try:
conf = configparser.ConfigParser()
conf.read(os.path.expanduser('~/.config/mndb.conf'))
except:
pass
else:
apikey = conf.get('mndb', 'apikey', fallback = None)
items = conf.getint('mndb', 'items', fallback = -1)
for opt, arg in opts:
if opt in ('-h', '--help'):
print(USAGE, file = sys.stderr)
return 0
elif opt in ('-v', '--verbose'):
verbose = True
elif opt in ('-k', '--apikey'):
apikey = arg
elif opt in ('-n', '--items'):
try:
items = int(arg)
except ValueError:
print(f'{argv[0]}: invalid max item value', file = sys.stderr)
return 1
else:
print(f'{argv[0]}: ignoring unknown option {opt}', file = sys.stderr)
if apikey is None:
print(f'{argv[0]}: API key not specified; provide mndb.conf or -k', file = sys.stderr)
return 2
session = requests.Session()
for arg in args:
try:
req = session.get('https://www.magnumdb.com/api.aspx', params = {
'q': arg,
'key': apikey
})
except Exception as exc:
print(f'{argv[0]}: unable to send query: {exc}', file = sys.stderr)
continue
if req.status_code != 200:
print(f'{argv[0]}: server response error {req.status_code}: {req.text}', file = sys.stderr)
continue
resp = req.json()
total = resp.get('TotalHits', len(resp['Items']))
print(f'// {total} match(es) found for "{resp["OriginalText"]}", {min(total, items) if items >= 0 else total} shown')
print()
for i, item in enumerate(resp['Items']):
if items >= 0 and i >= items:
break
print(f'{item["Title"]:<48}\t{item["FileName"]}')
item_type = item['Type']
if item_type == 'ValueItem':
print(f'\t{item["ValueType"]} value')
print_value_item(verbose, item)
elif item_type == 'EnumValueItem':
print(f'\t{item["ValueType"]} member of enum {item["Parent"]}')
print_value_item(verbose, item)
elif item_type == 'GuidItem':
guid_type = item['GuidType'] if 'GuidType' in item else 'Unknown'
print(f'\t{guid_type} GUID of type {item["ValueType"]}')
print_value_item(verbose, item)
elif item_type == 'EnumItem':
print(f'\tenum type')
if not verbose:
print(f'\t// enable verbose mode to get values from source')
else:
print(f'\t{item["Value"]}') # XXX: At least print the value out
if verbose:
print(f'// {item["DisplayFilePath"]}')
for condition in item['Conditions']:
print(f'// #{condition}')
print('\n'.join(item.get('Source', '// source not available').splitlines()))
print()
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv))
except KeyboardInterrupt:
sys.exit(130)