grootveil 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- grootveil/__init__.py +42 -0
- grootveil/actions/__init__.py +0 -0
- grootveil/actions/base.py +33 -0
- grootveil/actions/encrypt.py +32 -0
- grootveil/actions/hash.py +12 -0
- grootveil/actions/keep.py +6 -0
- grootveil/actions/mask.py +24 -0
- grootveil/actions/pseudonymize.py +23 -0
- grootveil/actions/redact.py +6 -0
- grootveil/actions/registry.py +27 -0
- grootveil/actions/replace.py +8 -0
- grootveil/core/__init__.py +0 -0
- grootveil/core/errors.py +2 -0
- grootveil/core/labels.py +40 -0
- grootveil/detectors/__init__.py +0 -0
- grootveil/detectors/base.py +11 -0
- grootveil/detectors/deny_list.py +27 -0
- grootveil/detectors/model.py +129 -0
- grootveil/detectors/rules/__init__.py +14 -0
- grootveil/detectors/rules/address.py +50 -0
- grootveil/detectors/rules/checks.py +18 -0
- grootveil/detectors/rules/contact.py +114 -0
- grootveil/detectors/rules/dates.py +127 -0
- grootveil/detectors/rules/detector.py +77 -0
- grootveil/detectors/rules/financial.py +96 -0
- grootveil/detectors/rules/ids/__init__.py +20 -0
- grootveil/detectors/rules/ids/americas.py +50 -0
- grootveil/detectors/rules/ids/asia_pacific.py +148 -0
- grootveil/detectors/rules/ids/documents.py +48 -0
- grootveil/detectors/rules/ids/europe.py +219 -0
- grootveil/detectors/rules/ids/germany.py +84 -0
- grootveil/detectors/rules/ids/middle_east_africa.py +85 -0
- grootveil/detectors/rules/rule.py +37 -0
- grootveil/detectors/rules/secrets.py +74 -0
- grootveil/models/__init__.py +0 -0
- grootveil/models/action_config.py +24 -0
- grootveil/models/finding.py +14 -0
- grootveil/models/item.py +14 -0
- grootveil/models/protected.py +21 -0
- grootveil/py.typed +0 -0
- grootveil/resolvers/__init__.py +0 -0
- grootveil/resolvers/address_prefix.py +64 -0
- grootveil/resolvers/join.py +30 -0
- grootveil/resolvers/overlaps.py +42 -0
- grootveil/resolvers/register.py +33 -0
- grootveil/resolvers/words.py +14 -0
- grootveil/services/__init__.py +0 -0
- grootveil/services/applier.py +26 -0
- grootveil/services/resolver.py +35 -0
- grootveil/services/vault.py +40 -0
- grootveil/shield.py +257 -0
- grootveil-2.0.0.dist-info/METADATA +198 -0
- grootveil-2.0.0.dist-info/RECORD +54 -0
- grootveil-2.0.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""ID numbers of European countries: the United Kingdom, Spain, Italy, Poland, Finland, Sweden, Turkey.
|
|
2
|
+
Germany has its own file (germany.py)."""
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from grootveil.detectors.rules.checks import date_ok, luhn_ok
|
|
7
|
+
from grootveil.detectors.rules.rule import Rule
|
|
8
|
+
|
|
9
|
+
SPAIN_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE" # the check letter of a DNI or NIE: its number mod 23
|
|
10
|
+
FINLAND_CHARS = "0123456789ABCDEFHJKLMNPRSTUVWXY" # the check character of a henkilötunnus: its 9 digits mod 31
|
|
11
|
+
# Italian codice fiscale: what a character counts at an odd position (1st, 3rd, ...); at an even one a digit counts
|
|
12
|
+
# as itself and a letter as its place in the alphabet (A = 0)
|
|
13
|
+
ITALY_ODD_DIGITS = (1, 0, 5, 7, 9, 13, 15, 17, 19, 21) # 0 to 9
|
|
14
|
+
ITALY_ODD_LETTERS = (
|
|
15
|
+
1,
|
|
16
|
+
0,
|
|
17
|
+
5,
|
|
18
|
+
7,
|
|
19
|
+
9,
|
|
20
|
+
13,
|
|
21
|
+
15,
|
|
22
|
+
17,
|
|
23
|
+
19,
|
|
24
|
+
21,
|
|
25
|
+
2,
|
|
26
|
+
4,
|
|
27
|
+
18,
|
|
28
|
+
20,
|
|
29
|
+
11,
|
|
30
|
+
3,
|
|
31
|
+
6,
|
|
32
|
+
8,
|
|
33
|
+
12,
|
|
34
|
+
14,
|
|
35
|
+
16,
|
|
36
|
+
10,
|
|
37
|
+
22,
|
|
38
|
+
25,
|
|
39
|
+
24,
|
|
40
|
+
23,
|
|
41
|
+
) # A to Z
|
|
42
|
+
ITALY_ODD = dict(zip("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", ITALY_ODD_DIGITS + ITALY_ODD_LETTERS, strict=True))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def uk_nino(value: str) -> bool:
|
|
46
|
+
"""A UK National Insurance number: two letters (not D, F, I, Q, U, V; the second not O; not BG, GB, NK, KN, TN, NT,
|
|
47
|
+
ZZ), six digits, then A, B, C or D."""
|
|
48
|
+
v = "".join(value.split()).upper()
|
|
49
|
+
return v[0] not in "DFIQUV" and v[1] not in "DFIQUVO" and v[:2] not in ("BG", "GB", "NK", "KN", "TN", "NT", "ZZ")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def uk_nhs(value: str) -> bool:
|
|
53
|
+
"""A UK NHS number: 10 digits, the last one a mod-11 check digit (weights 10 to 2; a check of 10 is never
|
|
54
|
+
issued)."""
|
|
55
|
+
d = [int(c) for c in value if c.isdigit()]
|
|
56
|
+
check = 11 - sum(n * w for n, w in zip(d[:9], range(10, 1, -1), strict=True)) % 11
|
|
57
|
+
return len(d) == 10 and (0 if check == 11 else check) == d[9]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def spain_dni(value: str) -> bool:
|
|
61
|
+
"""A Spanish DNI (its number is also the NIF of a person): 8 digits and a check letter."""
|
|
62
|
+
v = value.replace("-", "").replace(" ", "")
|
|
63
|
+
return SPAIN_LETTERS[int(v[:-1]) % 23] == v[-1]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def spain_nie(value: str) -> bool:
|
|
67
|
+
"""A Spanish NIE (foreigners): X, Y or Z, 7 digits and a check letter; the first letter counts as 0, 1 or 2."""
|
|
68
|
+
v = value.replace("-", "").replace(" ", "")
|
|
69
|
+
return SPAIN_LETTERS[int(str("XYZ".index(v[0])) + v[1:-1]) % 23] == v[-1]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def italy_fiscal_code(value: str) -> bool:
|
|
73
|
+
"""An Italian codice fiscale: 15 characters and a check letter (odd and even positions count differently)."""
|
|
74
|
+
total = sum(
|
|
75
|
+
ITALY_ODD[c] if i % 2 == 0 else (int(c) if c.isdigit() else ord(c) - 65) for i, c in enumerate(value[:15])
|
|
76
|
+
)
|
|
77
|
+
return chr(65 + total % 26) == value[15]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def poland_pesel(value: str) -> bool:
|
|
81
|
+
"""A Polish PESEL: 11 digits; the first six are the birth date (the month has 20, 40, 60 or 80 added for the
|
|
82
|
+
centuries after and before 1900-1999), the last one a check digit (weights 1 3 7 9)."""
|
|
83
|
+
d = [int(c) for c in value]
|
|
84
|
+
century, month = divmod(d[2] * 10 + d[3], 20)
|
|
85
|
+
year = (1900, 2000, 2100, 2200, 1800)[century] + d[0] * 10 + d[1]
|
|
86
|
+
check = (10 - sum(n * w for n, w in zip(d, (1, 3, 7, 9, 1, 3, 7, 9, 1, 3), strict=False)) % 10) % 10
|
|
87
|
+
return date_ok(year, month, d[4] * 10 + d[5]) and check == d[10]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def finland_hetu(value: str) -> bool:
|
|
91
|
+
"""A Finnish henkilötunnus: the birth date, a century sign (+ 1800s, - or U to Y 1900s, A to F 2000s), three
|
|
92
|
+
digits and a check character."""
|
|
93
|
+
v = value.upper()
|
|
94
|
+
year = (1800 if v[6] == "+" else 2000 if v[6] in "ABCDEF" else 1900) + int(v[4:6])
|
|
95
|
+
return date_ok(year, int(v[2:4]), int(v[:2])) and FINLAND_CHARS[int(v[:6] + v[7:10]) % 31] == v[10]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def sweden_personnummer(value: str) -> bool:
|
|
99
|
+
"""A Swedish personnummer: the birth date (a coordination number has 60 added to the day), four digits, the last
|
|
100
|
+
one a Luhn check digit over the ten digits without the century."""
|
|
101
|
+
d = [int(c) for c in value if c.isdigit()][-10:]
|
|
102
|
+
day = d[4] * 10 + d[5]
|
|
103
|
+
return date_ok(2000, d[2] * 10 + d[3], day - 60 if day > 60 else day) and luhn_ok(d)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def turkey_id(value: str) -> bool:
|
|
107
|
+
"""A Turkish identity number (T.C. Kimlik No): 11 digits, the last two are check digits."""
|
|
108
|
+
d = [int(c) for c in value]
|
|
109
|
+
tenth = ((d[0] + d[2] + d[4] + d[6] + d[8]) * 7 - (d[1] + d[3] + d[5] + d[7])) % 10
|
|
110
|
+
return tenth == d[9] and sum(d[:10]) % 10 == d[10]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
UK_NINO_WORDS = ("national insurance", "national insurance number", "ni number", "ni no", "nino")
|
|
114
|
+
UK_NHS_WORDS = ("nhs", "nhs number", "nhs no", "health service")
|
|
115
|
+
SPAIN_DNI_WORDS = ("dni", "nif", "documento nacional de identidad", "documento de identidad", "national id")
|
|
116
|
+
SPAIN_NIE_WORDS = ("nie", "número de identidad de extranjero", "numero de identidad de extranjero", "extranjero")
|
|
117
|
+
ITALY_FISCAL_WORDS = ("codice fiscale", "cod. fiscale", "c.f", "cf", "fiscal code", "tax code")
|
|
118
|
+
ITALY_ID_CARD_WORDS = (
|
|
119
|
+
"carta d'identità", "carta di identità", "carta d'identita", "carta di identita", "carta identità", "cie",
|
|
120
|
+
"identity card", "id card",
|
|
121
|
+
) # fmt: skip
|
|
122
|
+
SWEDEN_WORDS = ("personnummer", "personal identity number", "samordningsnummer", "pnr")
|
|
123
|
+
FINLAND_WORDS = ("henkilötunnus", "hetu", "personal identity code", "personbeteckning")
|
|
124
|
+
TURKEY_WORDS = ("tc kimlik", "t.c. kimlik", "kimlik no", "kimlik numarası", "kimlik numarasi", "tckn", "tc no")
|
|
125
|
+
|
|
126
|
+
RULES = [
|
|
127
|
+
Rule(
|
|
128
|
+
"uk_nino",
|
|
129
|
+
"NATIONAL_ID",
|
|
130
|
+
r"\b[A-Z]{2} ?\d{2} ?\d{2} ?\d{2} ?[A-D]\b", # AB 12 34 56 C, AB123456C, ab123456c (no check digit)
|
|
131
|
+
0.5,
|
|
132
|
+
UK_NINO_WORDS,
|
|
133
|
+
0.85,
|
|
134
|
+
validator=uk_nino,
|
|
135
|
+
flags=re.IGNORECASE,
|
|
136
|
+
),
|
|
137
|
+
Rule(
|
|
138
|
+
"uk_nhs",
|
|
139
|
+
"NATIONAL_ID",
|
|
140
|
+
r"(?<![\w+])\d{3}[ -]?\d{3}[ -]?\d{4}(?!\w)", # 943 476 5919; one 10-digit number in eleven passes by chance
|
|
141
|
+
0.3,
|
|
142
|
+
UK_NHS_WORDS,
|
|
143
|
+
0.85,
|
|
144
|
+
validator=uk_nhs,
|
|
145
|
+
),
|
|
146
|
+
Rule(
|
|
147
|
+
"spain_dni",
|
|
148
|
+
"NATIONAL_ID",
|
|
149
|
+
r"\b\d{8}[- ]?[A-HJ-NP-TV-Z]\b", # 54362315K; one code of this shape in 23 passes the check letter by chance
|
|
150
|
+
0.4,
|
|
151
|
+
SPAIN_DNI_WORDS,
|
|
152
|
+
0.9,
|
|
153
|
+
validator=spain_dni,
|
|
154
|
+
),
|
|
155
|
+
Rule(
|
|
156
|
+
"spain_nie",
|
|
157
|
+
"NATIONAL_ID",
|
|
158
|
+
r"\b[XYZ][- ]?\d{7}[- ]?[A-HJ-NP-TV-Z]\b", # Y3338121F
|
|
159
|
+
0.4,
|
|
160
|
+
SPAIN_NIE_WORDS,
|
|
161
|
+
0.9,
|
|
162
|
+
validator=spain_nie,
|
|
163
|
+
),
|
|
164
|
+
Rule(
|
|
165
|
+
"italy_fiscal_code",
|
|
166
|
+
"TAX_ID",
|
|
167
|
+
# 6 letters of the name, the birth year, a month letter, the day, a place code, a check letter; a digit can
|
|
168
|
+
# be written as a letter (L M N P Q R S T U V) when two people would share a code. Capitals only
|
|
169
|
+
r"\b[A-Z]{6}[0-9LMNP-V]{2}[ABCDEHLMPRST][0-9LMNP-V]{2}[A-Z][0-9LMNP-V]{3}[A-Z]\b",
|
|
170
|
+
0.7,
|
|
171
|
+
ITALY_FISCAL_WORDS,
|
|
172
|
+
0.95,
|
|
173
|
+
validator=italy_fiscal_code,
|
|
174
|
+
),
|
|
175
|
+
Rule(
|
|
176
|
+
"italy_id_card",
|
|
177
|
+
"NATIONAL_ID",
|
|
178
|
+
r"\bC[A-Z]\d{5}[A-Z]{2}\b|\b[A-Z]{2} ?\d{7}\b", # the card of today CA00000AA; the paper one AA 1234567
|
|
179
|
+
0.2,
|
|
180
|
+
ITALY_ID_CARD_WORDS,
|
|
181
|
+
0.6,
|
|
182
|
+
),
|
|
183
|
+
Rule(
|
|
184
|
+
"poland_pesel",
|
|
185
|
+
"NATIONAL_ID",
|
|
186
|
+
r"(?<![\w+])\d{11}(?!\w)", # one 11-digit number in thirty has a real date and passes the check by chance
|
|
187
|
+
0.3,
|
|
188
|
+
("pesel",),
|
|
189
|
+
0.85,
|
|
190
|
+
validator=poland_pesel,
|
|
191
|
+
),
|
|
192
|
+
Rule(
|
|
193
|
+
"finland_hetu",
|
|
194
|
+
"NATIONAL_ID",
|
|
195
|
+
r"\b\d{6}[-+A-FU-Y]\d{3}[0-9A-FHJ-NPR-Y]\b", # 120464-126J
|
|
196
|
+
0.6,
|
|
197
|
+
FINLAND_WORDS,
|
|
198
|
+
0.95,
|
|
199
|
+
validator=finland_hetu,
|
|
200
|
+
),
|
|
201
|
+
Rule(
|
|
202
|
+
"sweden_personnummer",
|
|
203
|
+
"NATIONAL_ID",
|
|
204
|
+
r"(?<![\w+])(?:\d{2})?\d{6}[-+]\d{4}(?!\w)", # 640823-3234, 19640823-3234; only with its dash
|
|
205
|
+
0.4,
|
|
206
|
+
SWEDEN_WORDS,
|
|
207
|
+
0.85,
|
|
208
|
+
validator=sweden_personnummer,
|
|
209
|
+
),
|
|
210
|
+
Rule(
|
|
211
|
+
"turkey_id",
|
|
212
|
+
"NATIONAL_ID",
|
|
213
|
+
r"(?<![\w+])[1-9]\d{10}(?!\w)", # two check digits: one 11-digit number in a hundred passes by chance
|
|
214
|
+
0.3,
|
|
215
|
+
TURKEY_WORDS,
|
|
216
|
+
0.85,
|
|
217
|
+
validator=turkey_id,
|
|
218
|
+
),
|
|
219
|
+
]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""German ID numbers: tax ID (Steuer-ID, Steuernummer), identity card, social security number."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
|
|
5
|
+
from grootveil.detectors.rules.checks import date_ok
|
|
6
|
+
from grootveil.detectors.rules.rule import Rule
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def german_tax_id(value: str) -> bool:
|
|
10
|
+
"""A Steuer-ID that passes its own tests: 11 digits; in the first ten, one digit is there twice or three times
|
|
11
|
+
and no other one more than once; the last one is a check digit (ISO 7064, mod 11,10)."""
|
|
12
|
+
d = [int(c) for c in value if c.isdigit()]
|
|
13
|
+
counts = sorted(Counter(d[:10]).values(), reverse=True)
|
|
14
|
+
if counts[0] not in (2, 3) or counts[1] != 1:
|
|
15
|
+
return False
|
|
16
|
+
product = 10
|
|
17
|
+
for n in d[:10]:
|
|
18
|
+
product = (2 * ((n + product) % 10 or 10)) % 11
|
|
19
|
+
return (11 - product) % 10 == d[10]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def german_social_security(value: str) -> bool:
|
|
23
|
+
"""A German social security number (Rentenversicherungsnummer): an area (2 digits), the birth date (DDMMYY), the
|
|
24
|
+
first letter of the birth name, a serial (2 digits) and a check digit. For the check the letter counts as its
|
|
25
|
+
place in the alphabet (A = 01); each digit times its weight, the digits of every product added up, mod 10."""
|
|
26
|
+
v = "".join(value.split())
|
|
27
|
+
body = v[:8] + f"{ord(v[8]) - 64:02d}" + v[9:11]
|
|
28
|
+
total = sum(sum(divmod(int(c) * w, 10)) for c, w in zip(body, (2, 1, 2, 5, 7, 1, 2, 1, 2, 1, 2, 1), strict=True))
|
|
29
|
+
return date_ok(2000, int(v[4:6]), int(v[2:4])) and total % 10 == int(v[11])
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
GERMAN_TAX_WORDS = (
|
|
33
|
+
"steueridentifikationsnummer", "steuer-id", "steuerid", "steuer-idnr", "idnr", "steuernummer", "steuer-nr",
|
|
34
|
+
"st.-nr", "st-nr", "st.nr",
|
|
35
|
+
"tax id", "tax identification number", "tin",
|
|
36
|
+
) # fmt: skip
|
|
37
|
+
GERMAN_ID_CARD_WORDS = (
|
|
38
|
+
"personalausweis", "personalausweisnummer", "personalausweis-nr", "ausweisnummer", "ausweis-nr",
|
|
39
|
+
"identitätskarte", "identity card", "id card",
|
|
40
|
+
) # fmt: skip
|
|
41
|
+
GERMAN_SOCIAL_SECURITY_WORDS = (
|
|
42
|
+
"sozialversicherungsnummer", "rentenversicherungsnummer", "versicherungsnummer", "sv-nummer", "sv-nr", "svnr",
|
|
43
|
+
"rvnr", "social security number",
|
|
44
|
+
) # fmt: skip
|
|
45
|
+
|
|
46
|
+
RULES = [
|
|
47
|
+
Rule(
|
|
48
|
+
"german_tax_id",
|
|
49
|
+
"TAX_ID",
|
|
50
|
+
# Steuer-ID: 11 digits, also written 45 123 678 910; Steuernummer: 27/563/15892. No check: a number written
|
|
51
|
+
# as someone's tax ID is masked, also one with a wrong check digit
|
|
52
|
+
# 13 digits (the ELSTER form: the state's 2 digits, 01 to 16, first)
|
|
53
|
+
r"\b[1-9]\d(?: ?\d{3}){3}\b|\b\d{2,3}/\d{3,4}/\d{4,5}\b|\b(?:0[1-9]|1[0-6])\d{11}\b",
|
|
54
|
+
0.2,
|
|
55
|
+
GERMAN_TAX_WORDS,
|
|
56
|
+
0.6,
|
|
57
|
+
),
|
|
58
|
+
Rule(
|
|
59
|
+
"german_tax_id_checked",
|
|
60
|
+
"TAX_ID",
|
|
61
|
+
r"\b[1-9]\d(?: ?\d{3}){3}\b", # the same 11 digits, when they pass the Steuer-ID's tests: a surer finding
|
|
62
|
+
0.4,
|
|
63
|
+
GERMAN_TAX_WORDS,
|
|
64
|
+
0.9,
|
|
65
|
+
validator=german_tax_id,
|
|
66
|
+
),
|
|
67
|
+
Rule(
|
|
68
|
+
"german_id_card",
|
|
69
|
+
"NATIONAL_ID",
|
|
70
|
+
r"\b(?=[A-Z0-9]*\d)[A-Z][A-Z0-9]{7,8}\b", # Personalausweis: L01X00T47, T22000129
|
|
71
|
+
0.2,
|
|
72
|
+
GERMAN_ID_CARD_WORDS,
|
|
73
|
+
0.6,
|
|
74
|
+
),
|
|
75
|
+
Rule(
|
|
76
|
+
"german_social_security",
|
|
77
|
+
"NATIONAL_ID",
|
|
78
|
+
r"\b\d{2} ?\d{6} ?[A-Z] ?\d{3}\b", # 65 170839 J 003; a capital letter at the ninth place
|
|
79
|
+
0.5,
|
|
80
|
+
GERMAN_SOCIAL_SECURITY_WORDS,
|
|
81
|
+
0.9,
|
|
82
|
+
validator=german_social_security,
|
|
83
|
+
),
|
|
84
|
+
]
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""ID numbers of the Middle East and Africa: Saudi Arabia, the United Arab Emirates, Nigeria, South Africa."""
|
|
2
|
+
|
|
3
|
+
from grootveil.detectors.rules.checks import date_ok, luhn_ok
|
|
4
|
+
from grootveil.detectors.rules.rule import Rule
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def saudi_id(value: str) -> bool:
|
|
8
|
+
"""A Saudi national ID (starts with 1) or Iqama (starts with 2): 10 digits, the last one a Luhn check digit.
|
|
9
|
+
Arabic-Indic digits count too (int() reads them)."""
|
|
10
|
+
return luhn_ok([int(c) for c in value])
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def emirates_id(value: str) -> bool:
|
|
14
|
+
"""A UAE Emirates ID: 784, the birth year, 7 digits and a Luhn check digit (15 digits)."""
|
|
15
|
+
return luhn_ok([int(c) for c in value if c.isdigit()])
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def south_africa_id(value: str) -> bool:
|
|
19
|
+
"""A South African ID number: the birth date (YYMMDD), four digits, 0 (citizen), 1 (permanent resident) or 2
|
|
20
|
+
(refugee), one digit and a Luhn check digit (13 digits)."""
|
|
21
|
+
d = [int(c) for c in value]
|
|
22
|
+
return date_ok(2000, d[2] * 10 + d[3], d[4] * 10 + d[5]) and d[10] in (0, 1, 2) and luhn_ok(d)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def south_africa_tax(value: str) -> bool:
|
|
26
|
+
"""A South African income tax reference number: 10 digits, the last one a Luhn check digit."""
|
|
27
|
+
return luhn_ok([int(c) for c in value])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
SAUDI_ID_WORDS = (
|
|
31
|
+
"national id", "saudi id", "iqama", "resident id", "id number",
|
|
32
|
+
"هوية", "الهوية", "هويتي", "هويته", "بالهوية", "إقامة", "الإقامة", "اقامة", "الاقامة", "إقامتي",
|
|
33
|
+
"السجل المدني", "سجل مدني",
|
|
34
|
+
) # fmt: skip
|
|
35
|
+
EMIRATES_ID_WORDS = ("emirates id", "eid", "هوية", "الهوية", "بطاقة الهوية", "الهوية الإماراتية")
|
|
36
|
+
NIGERIA_NIN_WORDS = ("nin", "national identification number", "national identity number", "nimc")
|
|
37
|
+
SOUTH_AFRICA_ID_WORDS = ("id number", "id no", "identity number", "south african id", "sa id", "rsa id")
|
|
38
|
+
SOUTH_AFRICA_TAX_WORDS = ("income tax number", "tax reference number", "tax reference", "tax number", "sars")
|
|
39
|
+
|
|
40
|
+
RULES = [
|
|
41
|
+
Rule(
|
|
42
|
+
"saudi_id",
|
|
43
|
+
"NATIONAL_ID",
|
|
44
|
+
r"(?<![\w+])[12١٢۱۲]\d{9}(?!\w)", # national ID 1..., Iqama 2...; one number in ten passes the check by chance
|
|
45
|
+
0.3,
|
|
46
|
+
SAUDI_ID_WORDS,
|
|
47
|
+
0.85,
|
|
48
|
+
validator=saudi_id,
|
|
49
|
+
),
|
|
50
|
+
Rule(
|
|
51
|
+
"emirates_id",
|
|
52
|
+
"NATIONAL_ID",
|
|
53
|
+
r"(?<![\w+])784-?\d{4}-?\d{7}-?\d(?!\w)", # 784-1990-1234567-1; above card (0.9): a Luhn-valid 15 digits
|
|
54
|
+
0.95,
|
|
55
|
+
EMIRATES_ID_WORDS,
|
|
56
|
+
1.0,
|
|
57
|
+
validator=emirates_id,
|
|
58
|
+
),
|
|
59
|
+
Rule(
|
|
60
|
+
"nigeria_nin",
|
|
61
|
+
"NATIONAL_ID",
|
|
62
|
+
r"(?<![\w+])\d{11}(?!\w)", # 11 digits with no check digit: only with a context word
|
|
63
|
+
0.1,
|
|
64
|
+
NIGERIA_NIN_WORDS,
|
|
65
|
+
0.6,
|
|
66
|
+
),
|
|
67
|
+
Rule(
|
|
68
|
+
"south_africa_id",
|
|
69
|
+
"NATIONAL_ID",
|
|
70
|
+
r"(?<![\w+])\d{13}(?!\w)", # a real date, 0 or 1 at the eleventh place and the check digit: rare by chance
|
|
71
|
+
0.6,
|
|
72
|
+
SOUTH_AFRICA_ID_WORDS,
|
|
73
|
+
0.95, # above card (0.9): every South African ID is 13 Luhn-valid digits, a card number's test too
|
|
74
|
+
validator=south_africa_id,
|
|
75
|
+
),
|
|
76
|
+
Rule(
|
|
77
|
+
"south_africa_tax",
|
|
78
|
+
"TAX_ID",
|
|
79
|
+
r"(?<![\w+])[01239]\d{9}(?!\w)", # starts with 0, 1, 2, 3 or 9; one in ten passes the check by chance
|
|
80
|
+
0.2,
|
|
81
|
+
SOUTH_AFRICA_TAX_WORDS,
|
|
82
|
+
0.75,
|
|
83
|
+
validator=south_africa_tax,
|
|
84
|
+
),
|
|
85
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""One rule: a regex, its label and score, and what makes a match stronger (context words) or drops it (a validator,
|
|
2
|
+
the text just before it)."""
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Rule:
|
|
11
|
+
name: str
|
|
12
|
+
label: str
|
|
13
|
+
regex: str
|
|
14
|
+
score: float
|
|
15
|
+
context: tuple[str, ...] = ()
|
|
16
|
+
context_score: float | None = None # None: min(1, max(score + 0.35, 0.4)), as Presidio
|
|
17
|
+
validator: Callable[[str], bool] | None = None
|
|
18
|
+
group: int = 0 # which regex group is the value (0 = the whole match)
|
|
19
|
+
flags: int = 0
|
|
20
|
+
not_after: str | None = None # regex (lower case) on the text just before the value: a hit there drops the match
|
|
21
|
+
compiled: re.Pattern = field(init=False, repr=False, compare=False)
|
|
22
|
+
context_re: re.Pattern | None = field(init=False, repr=False, compare=False)
|
|
23
|
+
not_after_re: re.Pattern | None = field(init=False, repr=False, compare=False)
|
|
24
|
+
|
|
25
|
+
def __post_init__(self):
|
|
26
|
+
for name, value in (("score", self.score), ("context_score", self.context_score)):
|
|
27
|
+
if value is not None and (
|
|
28
|
+
isinstance(value, bool) or not isinstance(value, int | float) or not 0 <= value <= 1
|
|
29
|
+
):
|
|
30
|
+
raise ValueError(f"rule {self.name}: {name} must be a number between 0 and 1")
|
|
31
|
+
try:
|
|
32
|
+
object.__setattr__(self, "compiled", re.compile(self.regex, self.flags))
|
|
33
|
+
except (re.error, TypeError) as e:
|
|
34
|
+
raise ValueError(f"rule {self.name}: its regex does not compile ({e})") from e
|
|
35
|
+
words = "|".join(re.escape(w) for w in self.context)
|
|
36
|
+
object.__setattr__(self, "context_re", re.compile(rf"\b(?:{words})\b") if words else None)
|
|
37
|
+
object.__setattr__(self, "not_after_re", re.compile(rf"(?:{self.not_after})$") if self.not_after else None)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""What opens an account or a system: password, PIN, API key."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from grootveil.detectors.rules.rule import Rule
|
|
6
|
+
|
|
7
|
+
PLACEHOLDER = re.compile(r"PASSWOR[DT]|KENNWORT|YOUR|IHR|DEIN|HIER|XXX")
|
|
8
|
+
VARIABLE = re.compile(r"\$\{?[A-Za-z_]+\}?|%[A-Za-z_]+%") # $PASSWORD, ${DB_PASS}, %PASSWORD%: code, not a password
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def password_value(value: str) -> bool:
|
|
12
|
+
"""Not a password: a template slot (YOUR_PASSWORD, IHR_PASSWORT; GEHEIM_ABC is a password), redacted text,
|
|
13
|
+
markup or code ([geschwärzt], </label>, (see vault), os.environ[), a shell or template variable ($PASSWORD,
|
|
14
|
+
${DB_PASS}, %PASSWORD%; "$ecret123" has a digit: a password), words joined by - or . (strong-ish, sehr-sicher), or
|
|
15
|
+
under 4 characters ("PIN is 4 digits long")."""
|
|
16
|
+
core = value.strip("[]<>{}()/") # real passwords have edge brackets too ((bQcgKRd5f): judge the rest
|
|
17
|
+
return (
|
|
18
|
+
len(value) >= 4
|
|
19
|
+
and not (re.fullmatch(r"[A-ZÄÖÜ_]+", value) and PLACEHOLDER.search(value))
|
|
20
|
+
and not VARIABLE.fullmatch(value)
|
|
21
|
+
and not re.fullmatch(r"[^\W\d_]+(?:[-.][^\W\d_]+)*", core)
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
NO_VALUE = {
|
|
26
|
+
"siehe", "keins", "keine", "kein", "leer", "none", "hidden", "redacted", "geschwärzt", "vergessen", "unbekannt",
|
|
27
|
+
"unknown", "folgt", "intern", "privat", "beispiel", "example", "muster", "optional", "required", "pflichtfeld",
|
|
28
|
+
"erforderlich", "ändern", "change", "reset", "empty", "null",
|
|
29
|
+
} # fmt: skip
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def field_value(value: str) -> bool:
|
|
33
|
+
"""A one-word field value is a password, unless it is a note that there is none (siehe, leer, n/a, redacted)."""
|
|
34
|
+
return value.rstrip("!").lower() not in NO_VALUE
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
RULES = [
|
|
38
|
+
Rule(
|
|
39
|
+
"password",
|
|
40
|
+
"PASSWORD",
|
|
41
|
+
# markdown or quotes after the colon are skipped; the value needs a digit or a symbol inside it ("password is
|
|
42
|
+
# essential" is not a password); a full stop or comma at the end is not part of it. German keywords
|
|
43
|
+
# (Passwort, Kennwort, Zugangscode) and connectors (ist, lautet) too: "PASSWORT: Hund#2023",
|
|
44
|
+
# "Kennwort lautet X1"
|
|
45
|
+
r"\b(?:password|passwort|passwd|pwd|pw|passcode|pin|kennwort|zugangscode)\b[*_]*\s*"
|
|
46
|
+
r"(?:(?:is|ist|lautet)\b\s*[:=]?|[:=])"
|
|
47
|
+
r"[\s*_\"'`]*(?=[^\s*\"'`]*\d|[^\s*\"'`]*[^\sA-Za-z\d*\"'`][^\s*\"'`])([^\s*\"'`]*[^\s*\"'`.,;:!?)])",
|
|
48
|
+
0.7,
|
|
49
|
+
group=1,
|
|
50
|
+
flags=re.IGNORECASE,
|
|
51
|
+
validator=password_value,
|
|
52
|
+
),
|
|
53
|
+
Rule(
|
|
54
|
+
"password_field",
|
|
55
|
+
"PASSWORD",
|
|
56
|
+
# a field with one plain word and nothing after it ("Password: Secure!", "PASSWORT: SICHER"): could be the
|
|
57
|
+
# password, could be a note. Below the default threshold: masked only when the model agrees, or when a user
|
|
58
|
+
# sets a lower PASSWORD threshold. Prose without a colon ("password secure") never matches
|
|
59
|
+
r"\b(?:password|passwort|passwd|pwd|pw|passcode|pin|kennwort|zugangscode)\b[*_]*\s*[:=][\s*_\"'`]*"
|
|
60
|
+
r"([^\W\d_]{2,}!?)[*_\"'`]*[.,;]?[ \t]*$",
|
|
61
|
+
0.45,
|
|
62
|
+
group=1,
|
|
63
|
+
flags=re.IGNORECASE | re.MULTILINE,
|
|
64
|
+
validator=field_value,
|
|
65
|
+
),
|
|
66
|
+
Rule(
|
|
67
|
+
"api_key",
|
|
68
|
+
"API_KEY",
|
|
69
|
+
r"\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}|\bgh[pousr]_[A-Za-z0-9]{36,}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b"
|
|
70
|
+
r"|\bAKIA[0-9A-Z]{16}\b|\bxox[abprs]-[A-Za-z0-9-]{10,}|\bAIza[0-9A-Za-z_-]{35}\b|\bhf_[A-Za-z0-9]{30,}\b"
|
|
71
|
+
r"|\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}",
|
|
72
|
+
0.9,
|
|
73
|
+
),
|
|
74
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True)
|
|
5
|
+
class ActionConfig:
|
|
6
|
+
"""ActionConfig("mask", {"keep_last": 4}): which action, with which params."""
|
|
7
|
+
|
|
8
|
+
name: str
|
|
9
|
+
params: dict = field(default_factory=dict)
|
|
10
|
+
|
|
11
|
+
@classmethod
|
|
12
|
+
def from_dict(cls, d: dict | str) -> "ActionConfig":
|
|
13
|
+
"""{"type": "mask", "keep_last": 4} or "mask" (the policy file and REST form)."""
|
|
14
|
+
if isinstance(d, str):
|
|
15
|
+
return cls(d)
|
|
16
|
+
if not isinstance(d, dict):
|
|
17
|
+
raise TypeError(f'an action is a name ("mask") or a dict with "type", not {type(d).__name__}')
|
|
18
|
+
d = dict(d)
|
|
19
|
+
if "type" not in d:
|
|
20
|
+
raise ValueError(f'an action needs "type"; it has only {sorted(map(str, d))}') # names, never values
|
|
21
|
+
return cls(d.pop("type"), d)
|
|
22
|
+
|
|
23
|
+
def to_dict(self) -> dict:
|
|
24
|
+
return {"type": self.name, **self.params}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True)
|
|
5
|
+
class Finding:
|
|
6
|
+
"""One piece of PII: text[start:end], our label, a score in [0, 1], who found it (model, rule:<name>, register)
|
|
7
|
+
and why, in words ("rule card, Luhn check passed, context word near it")."""
|
|
8
|
+
|
|
9
|
+
label: str
|
|
10
|
+
start: int
|
|
11
|
+
end: int
|
|
12
|
+
score: float
|
|
13
|
+
source: str = "model"
|
|
14
|
+
why: str = field(default="", compare=False)
|
grootveil/models/item.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True)
|
|
5
|
+
class Item:
|
|
6
|
+
"""What protect did to one finding. start/end point into the NEW text."""
|
|
7
|
+
|
|
8
|
+
label: str
|
|
9
|
+
start: int
|
|
10
|
+
end: int
|
|
11
|
+
text: str
|
|
12
|
+
action: str
|
|
13
|
+
score: float
|
|
14
|
+
source: str = "model"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
from grootveil.core.labels import DIRECT
|
|
4
|
+
from grootveil.models.item import Item
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Protected:
|
|
9
|
+
"""protect()'s answer: the new text, what changed, and a ref for restore() (None when no action can be undone)."""
|
|
10
|
+
|
|
11
|
+
text: str
|
|
12
|
+
items: list[Item]
|
|
13
|
+
ref: str | None = None
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def has_pii(self) -> bool:
|
|
17
|
+
return bool(self.items)
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def has_direct(self) -> bool:
|
|
21
|
+
return any(i.label in DIRECT for i in self.items)
|
grootveil/py.typed
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
|
|
4
|
+
from grootveil.models.finding import Finding
|
|
5
|
+
|
|
6
|
+
# The unit part of an address written in front of the rest: a floor, a flat, a door or plot number. Our training data
|
|
7
|
+
# has almost no floor inside an address (2 of 94 floor phrases), so a model often starts the address after it.
|
|
8
|
+
NUM = r"[A-Za-z/-]*\d[\w/-]*" # 3B, G-2, 7/A, 45/2
|
|
9
|
+
UNIT = (
|
|
10
|
+
# floors: "1st Floor", "Ground Floor", "G Floor", "3rd Fl.", "Floor 3", "Level 5"
|
|
11
|
+
r"(?:\d+(?:st|nd|rd|th)|ground|g|first|second|third|fourth|fifth|top|upper|lower|mezzanine)\s+(?:floor|fl\.?)"
|
|
12
|
+
r"|(?:floor|level)\s*(?:no\.?\s*)?\d+"
|
|
13
|
+
# numbered parts: "Flat 3B", "Door No. 22", "Plot 7/A", "No. 87", "Old No. 12", "#12", "S-4"
|
|
14
|
+
r"|(?:flat|apt\.?|apartment|suite|unit|door|plot|house|block|wing|tower|shop)\s*(?:no\.?|number|#)?\s*"
|
|
15
|
+
+ NUM
|
|
16
|
+
# bare numbers: "No. 87", "Old No. 12", "#12", "S-4" (one letter: "AB-1234" is a code, not a unit)
|
|
17
|
+
+ r"|(?:(?:old|new)\s+)?no\.?\s*\d[\w/-]*|#\s*\d[\w/-]*|[A-Za-z]-\d{1,4}[A-Za-z]?"
|
|
18
|
+
# lettered blocks and wings: "Block A", "B-Block", "A Wing"
|
|
19
|
+
r"|(?:block|wing|tower)\s+[A-Za-z]\b|[A-Za-z]\s*-?\s*(?:block|wing)"
|
|
20
|
+
# German: "2. OG", "3. Stock", "EG", "Wohnung 7", "Whg. 7"
|
|
21
|
+
r"|\d+\.\s*(?:OG|Obergeschoss|Stock|Etage)|EG|Erdgeschoss|DG|Dachgeschoss|(?:wohnung|whg\.?)\s*"
|
|
22
|
+
+ NUM
|
|
23
|
+
# Arabic: "الطابق الأول" (floor + its number word), "شقة 5" (flat 5)
|
|
24
|
+
+ r"|الطابق\s+\S+?|شقة\s*\d+"
|
|
25
|
+
)
|
|
26
|
+
# a unit part starts after a non-word character (so "#12" works too) and ends with spaces or commas (Arabic ، too)
|
|
27
|
+
PREFIX = re.compile(rf"(?:(?<!\w)(?:{UNIT})[\s,،]+)+$", re.IGNORECASE)
|
|
28
|
+
LOOK_BACK = 80 # characters before an address where its unit part can start
|
|
29
|
+
# A bare number right after a word that names another kind of number belongs to that word, not to the address:
|
|
30
|
+
# "Invoice No. 87, 14 Gandhi Road", "Version V-2, 14 Gandhi Road". After any other word it is the house number:
|
|
31
|
+
# "Ship to No. 87, 1st Floor, ..." (leaving it out would leave the door number visible).
|
|
32
|
+
BARE = re.compile(r"(?:(?:old|new)\s+)?no\.?\s*\d[\w/-]*|#\s*\d[\w/-]*|[A-Za-z]-\d{1,4}[A-Za-z]?", re.IGNORECASE)
|
|
33
|
+
OTHER_NUMBER = re.compile(
|
|
34
|
+
r"\b(?:invoice|order|ref|reference|ticket|account|acct|policy|case|customer|client|item|serial|receipt|bill|"
|
|
35
|
+
r"booking|claim|application|file|registration|reg|member|membership|employee|staff|roll|id|phone|mobile|tel|"
|
|
36
|
+
r"fax|version|ver|model|batch|lot|part|sku|po|challan|transaction|txn|card|passport|licence|license|vehicle)"
|
|
37
|
+
r"\.?\s*(?:no\.?|number|#)?\s*$",
|
|
38
|
+
re.IGNORECASE,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def address_prefix(text: str, findings: list[Finding]) -> list[Finding]:
|
|
43
|
+
"""An ADDRESS directly after its unit part ("1st Floor, Flat 3B, " in front, with only spaces or commas between)
|
|
44
|
+
grows to the left to cover it. Only an address that was found grows: a floor or flat on its own ("the meeting is
|
|
45
|
+
on the 1st floor") is never marked."""
|
|
46
|
+
return [grow(text, f) if f.label == "ADDRESS" else f for f in findings]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def grow(text: str, f: Finding) -> Finding:
|
|
50
|
+
first = max(0, f.start - LOOK_BACK)
|
|
51
|
+
m = PREFIX.search(text[first : f.start])
|
|
52
|
+
if not m:
|
|
53
|
+
return f
|
|
54
|
+
start = first + m.start()
|
|
55
|
+
if start > 0 and text[start - 1].isalnum(): # the look-back window cut a word: not a whole unit part
|
|
56
|
+
return f
|
|
57
|
+
bare = BARE.match(text, start)
|
|
58
|
+
if bare and OTHER_NUMBER.search(text[max(0, start - 30) : start]):
|
|
59
|
+
start = bare.end() # the rest of the unit parts still joins
|
|
60
|
+
while start < f.start and (text[start].isspace() or text[start] in ",،"):
|
|
61
|
+
start += 1
|
|
62
|
+
if start >= f.start:
|
|
63
|
+
return f
|
|
64
|
+
return replace(f, start=start, why=f"{f.why}; its unit part in front joined" if f.why else "")
|