-
Notifications
You must be signed in to change notification settings - Fork 115
/
confusables.py
executable file
·82 lines (61 loc) · 2.3 KB
/
confusables.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
#!/usr/bin/env python3
# Use the unicode.org "confusables" list to read or create
# strings using confusingly similar unicode characters.
import re
from collections import defaultdict
import json
import argparse
import sys, os
URL = "http://www.unicode.org/Public/security/latest/confusables.txt"
DATADIR = os.path.expanduser("~/Data/confusables")
linepat = "([0-9A-Fa-f]{4,8}).*;.*([0-9A-Fa-f]{4,8}).*;.*?# (.*) *#"
jsonfile = os.path.join(DATADIR, "confusetable.json")
def fetch_new_data():
import requests
r = requests.get(URL)
confusedata = r.text
with open(os.path.join(DATADIR, "confusables.txt"), 'w') as fp:
fp.write(confusedata)
confusetable = defaultdict(list)
for line in confusedata.splitlines():
if not line or line.startswith("#"):
continue
match = re.match(linepat, line)
if not match:
continue
similarchar, commonchar, desc = match.groups()
print("similarchar", similarchar, type(similarchar))
similarchar = chr(int(similarchar, 16))
commonchar = chr(int(commonchar, 16))
confusetable[commonchar].append((similarchar, desc))
# Write it as JSON
with open(jsonfile, "w") as fp:
json.dump(confusetable, fp)
print("Wrote to", jsonfile)
return confusetable
def read_json(filename):
with open(filename) as jsonfp:
confusetable = json.loads(jsonfp.read())
return confusetable
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Show or create strings with deceptive Unicode characters")
# parser.add_argument('-c', "--check", dest="check", default=False,
# action="store_true", help="Help string")
parser.add_argument('strings', nargs='?', help="Strings to analyze")
args = parser.parse_args(sys.argv[1:])
print(args)
if not os.path.exists(jsonfile):
fetch_new_data()
with open(jsonfile) as jsonfp:
confusetable = json.load(jsonfp)
for s in args.strings:
print(s, ":")
for c in s:
if c in confusetable:
print(" ", c)
else:
for k in confusetable:
for pair in confusetable[k]:
if c == pair[0]:
print(" ", c, pair[1])