-
Notifications
You must be signed in to change notification settings - Fork 481
/
keyword.py
382 lines (356 loc) · 10.2 KB
/
keyword.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
"""
This code was extracted in part from
https://github.com/PyCQA/bandit. Using similar heuristic logic,
we adapted it to fit our plugin infrastructure, to create an organized,
concerted effort in detecting all type of secrets in code.
Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import re
from typing import Dict
from typing import Generator
from typing import Optional
from typing import Pattern
from typing import Set
from ..core.potential_secret import PotentialSecret
from ..util.filetype import determine_file_type
from ..util.filetype import FileType
from .base import BasePlugin
# Note: All values here should be lowercase
DENYLIST = (
'apikey',
'api_key',
'aws_secret_access_key',
'db_pass',
'password',
'passwd',
'private_key',
'secret',
'secrete',
)
FALSE_POSITIVES = {
'""',
'""):',
'"\'',
'")',
'"dummy',
'"replace',
'"this',
'#pass',
'#password',
'$(shell',
"'\"",
"''",
"''):",
"')",
"'dummy",
"'replace",
"'this",
'(nsstring',
'-default}',
'::',
'<%=',
'<?php',
'<a',
'<aws_secret_access_key>',
'<input',
'<password>',
'<redacted>',
'<secret',
'>',
'=',
'\\"$(shell',
'\\k.*"',
"\\k.*'",
'`cat',
'`grep',
'`sudo',
'account_password',
'api_key',
'disable',
'dummy_secret',
'dummy_value',
'false',
'false):',
'false,',
'false;',
'login_password',
'none',
'none,',
'none}',
'nopasswd',
'not',
'not_real_key',
'null',
'null,',
'null.*"',
"null.*'",
'null;',
'pass',
'pass)',
'password',
'password)',
'password))',
'password,',
'password},',
'prompt',
'redacted',
'secret',
'some_key',
'str',
'str_to_sign',
'string',
'string)',
'string,',
'string;',
'string?',
'string?)',
'string}',
'string}}',
'test',
'test-access-key',
'thisisnottherealsecret',
'todo',
'true',
'true):',
'true,',
'true;',
'undef',
'undef,',
'{',
'{{',
}
# Includes ], ', " as closing
CLOSING = r'[]\'"]{0,2}'
DENYLIST_REGEX = r'|'.join(DENYLIST)
# Non-greedy match
OPTIONAL_WHITESPACE = r'\s*?'
OPTIONAL_NON_WHITESPACE = r'[^\s]*?'
QUOTE = r'[\'"]'
SECRET = r'[^\s]+'
SQUARE_BRACKETS = r'(\[\])'
FOLLOWED_BY_COLON_EQUAL_SIGNS_REGEX = re.compile(
# e.g. my_password := "bar" or my_password := bar
r'({denylist})({closing})?{whitespace}:=?{whitespace}({quote}?)({secret})(\3)'.format(
denylist=DENYLIST_REGEX,
closing=CLOSING,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
)
FOLLOWED_BY_COLON_REGEX = re.compile(
# e.g. api_key: foo
r'({denylist})({closing})?:{whitespace}({quote}?)({secret})(\3)'.format(
denylist=DENYLIST_REGEX,
closing=CLOSING,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
)
FOLLOWED_BY_COLON_QUOTES_REQUIRED_REGEX = re.compile(
# e.g. api_key: "foo"
r'({denylist})({closing})?:({whitespace})({quote})({secret})(\4)'.format(
denylist=DENYLIST_REGEX,
closing=CLOSING,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
)
FOLLOWED_BY_EQUAL_SIGNS_OPTIONAL_BRACKETS_OPTIONAL_AT_SIGN_QUOTES_REQUIRED_REGEX = re.compile(
# e.g. my_password = "bar"
# e.g. my_password = @"bar"
# e.g. my_password[] = "bar";
r'({denylist})({square_brackets})?{optional_whitespace}={optional_whitespace}(@)?(")({secret})(\5)'.format( # noqa: E501
denylist=DENYLIST_REGEX,
square_brackets=SQUARE_BRACKETS,
optional_whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
)
FOLLOWED_BY_EQUAL_SIGNS_REGEX = re.compile(
# e.g. my_password = bar
r'({denylist})({closing})?{whitespace}={whitespace}({quote}?)({secret})(\3)'.format(
denylist=DENYLIST_REGEX,
closing=CLOSING,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
)
FOLLOWED_BY_EQUAL_SIGNS_QUOTES_REQUIRED_REGEX = re.compile(
# e.g. my_password = "bar"
r'({denylist})({closing})?{whitespace}={whitespace}({quote})({secret})(\3)'.format(
denylist=DENYLIST_REGEX,
closing=CLOSING,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
)
FOLLOWED_BY_QUOTES_AND_SEMICOLON_REGEX = re.compile(
# e.g. private_key "something";
r'({denylist}){nonWhitespace}{whitespace}({quote})({secret})(\2);'.format(
denylist=DENYLIST_REGEX,
nonWhitespace=OPTIONAL_NON_WHITESPACE,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
)
DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_COLON_REGEX: 4,
FOLLOWED_BY_EQUAL_SIGNS_REGEX: 4,
FOLLOWED_BY_QUOTES_AND_SEMICOLON_REGEX: 3,
}
GOLANG_DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_COLON_EQUAL_SIGNS_REGEX: 4,
FOLLOWED_BY_EQUAL_SIGNS_REGEX: 4,
FOLLOWED_BY_QUOTES_AND_SEMICOLON_REGEX: 3,
}
OBJECTIVE_C_DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_EQUAL_SIGNS_OPTIONAL_BRACKETS_OPTIONAL_AT_SIGN_QUOTES_REQUIRED_REGEX: 6,
}
QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_COLON_QUOTES_REQUIRED_REGEX: 5,
FOLLOWED_BY_EQUAL_SIGNS_QUOTES_REQUIRED_REGEX: 4,
FOLLOWED_BY_QUOTES_AND_SEMICOLON_REGEX: 3,
}
QUOTES_REQUIRED_FILETYPES = {
FileType.CLS,
FileType.JAVA,
FileType.JAVASCRIPT,
FileType.PYTHON,
FileType.SWIFT,
FileType.TERRAFORM,
}
class KeywordDetector(BasePlugin):
"""
Scans for secret-sounding variable names.
This checks if denylisted keywords are present in the analyzed string.
"""
secret_type = 'Secret Keyword'
def __init__(self, keyword_exclude: Optional[str] = None) -> None:
self.keyword_exclude = None
if keyword_exclude:
self.keyword_exclude = re.compile(
keyword_exclude,
re.IGNORECASE,
)
def analyze_string(
self,
string: str,
denylist_regex_to_group: Optional[Dict[Pattern, int]] = None,
) -> Generator[str, None, None]:
if self.keyword_exclude and self.keyword_exclude.search(string):
return
if denylist_regex_to_group is None:
attempts = [
QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP,
DENYLIST_REGEX_TO_GROUP,
]
else:
attempts = [denylist_regex_to_group]
has_results = False
for denylist_regex_to_group in attempts:
for denylist_regex, group_number in denylist_regex_to_group.items():
match = denylist_regex.search(string)
if match:
has_results = True
yield match.group(group_number)
if has_results:
break
def analyze_line(self, filename: str, line: str, line_number: int = 0) -> Set[PotentialSecret]:
filetype = determine_file_type(filename)
if filetype in QUOTES_REQUIRED_FILETYPES:
denylist_regex_to_group = QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP
elif filetype == FileType.GO:
denylist_regex_to_group = GOLANG_DENYLIST_REGEX_TO_GROUP
elif filetype == FileType.OBJECTIVE_C:
denylist_regex_to_group = OBJECTIVE_C_DENYLIST_REGEX_TO_GROUP
else:
denylist_regex_to_group = DENYLIST_REGEX_TO_GROUP
return super().analyze_line(
filename=filename,
line=line,
line_number=line_number,
denylist_regex_to_group=denylist_regex_to_group,
)
@property
def json(self):
return {
'keyword_exclude': (
self.keyword_exclude.pattern
if self.keyword_exclude
else '',
),
**super().json(),
}
def probably_false_positive(lowered_secret, filetype):
# TODO: Move this to filters/*
if (
any(
false_positive in lowered_secret
for false_positive in (
'/etc/',
'fake',
'forgot',
)
) or lowered_secret in FALSE_POSITIVES
# For e.g. private_key "some/dir/that/is/not/a/secret";
or lowered_secret.count('/') >= 3
# For e.g. "secret": "{secret}"
or (
lowered_secret[0] == '{'
and lowered_secret[-1] == '}'
) or (
filetype not in QUOTES_REQUIRED_FILETYPES
and lowered_secret[0] == '$'
) or (
filetype == FileType.EXAMPLE
and lowered_secret[0] == '<'
and lowered_secret[-1] == '>'
)
):
return True
# Heuristic for no function calls
try:
if (
lowered_secret.index('(') < lowered_secret.index(')')
):
return True
except ValueError:
pass
# Heuristic for e.g. request.json_body['hey']
try:
if (
lowered_secret.index('[') < lowered_secret.index(']')
):
return True
except ValueError:
pass
# Heuristic for e.g. ${link}
try:
if (
lowered_secret.index('${') < lowered_secret.index('}')
):
return True
except ValueError:
pass
return False