-
Notifications
You must be signed in to change notification settings - Fork 482
/
Copy pathkeyword.py
331 lines (313 loc) · 11.8 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
"""
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 Any
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
from detect_secrets.util.code_snippet import CodeSnippet
# Note: All values here should be lowercase
DENYLIST = (
'api_?key',
'auth_?key',
'service_?key',
'account_?key',
'db_?key',
'database_?key',
'priv_?key',
'private_?key',
'client_?key',
'db_?pass',
'database_?pass',
'key_?pass',
'password',
'passwd',
'pwd',
'secret',
'contraseña',
'contrasena',
)
# Includes ], ', " as closing
CLOSING = r'[]\'"]{0,2}'
AFFIX_REGEX = r'\w*'
DENYLIST_REGEX = r'|'.join(DENYLIST)
# Support for suffix after keyword i.e. password_secure = "value"
DENYLIST_REGEX = r'({denylist}){suffix}'.format(
denylist=DENYLIST_REGEX,
suffix=AFFIX_REGEX,
)
# Support for prefix and suffix with keyword, needed for reverse comparisons
# i.e. if ("value" == my_password_secure) {}
DENYLIST_REGEX_WITH_PREFIX = r'{prefix}{denylist}'.format(
prefix=AFFIX_REGEX,
denylist=DENYLIST_REGEX,
)
# Non-greedy match
OPTIONAL_WHITESPACE = r'\s*'
OPTIONAL_NON_WHITESPACE = r'[^\s]{0,50}?'
QUOTE = r'[\'"`]'
# Secret regex details:
# (?=[^\v\'"]*) -> this section match with every character except line breaks and quotes. This
# allows to find secrets that starts with symbols or alphanumeric characters.
#
# (?=\w+) -> this section match only with words (letters, numbers or _ are allowed), and at
# least one character is required. This allows to reduce the false positives
# number.
#
# [^\v\'"]* -> this section match with every character except line breaks and quotes. This
# allows to find secrets with symbols at the end.
#
# [^\v,\'"`] -> this section match with the last secret character that can be everything except
# line breaks, comma, backticks or quotes. This allows to reduce the false
# positives number and to prevent errors in the code snippet highlighting.
SECRET = r'(?=[^\v\'\"]*)(?=\w+)[^\v\'\"]*[^\v,\'\"`]'
SQUARE_BRACKETS = r'(\[[0-9]*\])'
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,
),
flags=re.IGNORECASE,
)
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,
),
flags=re.IGNORECASE,
)
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,
),
flags=re.IGNORECASE,
)
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";
# e.g. char my_password[25] = "bar";
r'{denylist}({square_brackets})?{optional_whitespace}[!=]{{1,2}}{optional_whitespace}(@)?(")({secret})(\5)'.format( # noqa: E501
denylist=DENYLIST_REGEX,
square_brackets=SQUARE_BRACKETS,
optional_whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
flags=re.IGNORECASE,
)
FOLLOWED_BY_OPTIONAL_ASSIGN_QUOTES_REQUIRED_REGEX = re.compile(
# e.g. std::string secret("bar");
# e.g. secret.assign("bar",17);
r'{denylist}(.assign)?\((")({secret})(\3)'.format(
denylist=DENYLIST_REGEX,
secret=SECRET,
),
)
FOLLOWED_BY_EQUAL_SIGNS_REGEX = re.compile(
# e.g. my_password = bar
# e.g. my_password == "bar" or my_password != "bar" or my_password === "bar"
# or my_password !== "bar"
# e.g. my_password == 'bar' or my_password != 'bar' or my_password === 'bar'
# or my_password !== 'bar'
r'{denylist}({closing})?{whitespace}(={{1,3}}|!==?){whitespace}({quote}?)({secret})(\4)'.format( # noqa: E501
denylist=DENYLIST_REGEX,
closing=CLOSING,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
flags=re.IGNORECASE,
)
FOLLOWED_BY_EQUAL_SIGNS_QUOTES_REQUIRED_REGEX = re.compile(
# e.g. my_password = "bar"
# e.g. my_password == "bar" or my_password != "bar" or my_password === "bar"
# or my_password !== "bar"
# e.g. my_password == 'bar' or my_password != 'bar' or my_password === 'bar'
# or my_password !== 'bar'
r'{denylist}({closing})?{whitespace}(={{1,3}}|!==?){whitespace}({quote})({secret})(\4)'.format( # noqa: E501
denylist=DENYLIST_REGEX,
closing=CLOSING,
quote=QUOTE,
whitespace=OPTIONAL_WHITESPACE,
secret=SECRET,
),
flags=re.IGNORECASE,
)
PRECEDED_BY_EQUAL_COMPARISON_SIGNS_QUOTES_REQUIRED_REGEX = re.compile(
# e.g. "bar" == my_password or "bar" != my_password or "bar" === my_password
# or "bar" !== my_password
# e.g. 'bar' == my_password or 'bar' != my_password or 'bar' === my_password
# or 'bar' !== my_password
r'({quote})({secret})(\1){whitespace}[!=]{{2,3}}{whitespace}{denylist}'.format(
denylist=DENYLIST_REGEX_WITH_PREFIX,
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,
),
flags=re.IGNORECASE,
)
FOLLOWED_BY_ARROW_FUNCTION_SIGN_QUOTES_REQUIRED_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,
),
flags=re.IGNORECASE,
)
CONFIG_DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_COLON_REGEX: 4,
PRECEDED_BY_EQUAL_COMPARISON_SIGNS_QUOTES_REQUIRED_REGEX: 2,
FOLLOWED_BY_EQUAL_SIGNS_REGEX: 5,
FOLLOWED_BY_QUOTES_AND_SEMICOLON_REGEX: 3,
}
GOLANG_DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_COLON_EQUAL_SIGNS_REGEX: 4,
PRECEDED_BY_EQUAL_COMPARISON_SIGNS_QUOTES_REQUIRED_REGEX: 2,
FOLLOWED_BY_EQUAL_SIGNS_REGEX: 5,
FOLLOWED_BY_QUOTES_AND_SEMICOLON_REGEX: 3,
}
COMMON_C_DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_EQUAL_SIGNS_OPTIONAL_BRACKETS_OPTIONAL_AT_SIGN_QUOTES_REQUIRED_REGEX: 6,
}
C_PLUS_PLUS_REGEX_TO_GROUP = {
FOLLOWED_BY_OPTIONAL_ASSIGN_QUOTES_REQUIRED_REGEX: 4,
FOLLOWED_BY_EQUAL_SIGNS_QUOTES_REQUIRED_REGEX: 5,
}
QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP = {
FOLLOWED_BY_COLON_QUOTES_REQUIRED_REGEX: 5,
PRECEDED_BY_EQUAL_COMPARISON_SIGNS_QUOTES_REQUIRED_REGEX: 2,
FOLLOWED_BY_EQUAL_SIGNS_QUOTES_REQUIRED_REGEX: 5,
FOLLOWED_BY_QUOTES_AND_SEMICOLON_REGEX: 3,
FOLLOWED_BY_ARROW_FUNCTION_SIGN_QUOTES_REQUIRED_REGEX: 4,
}
REGEX_BY_FILETYPE = {
FileType.GO: GOLANG_DENYLIST_REGEX_TO_GROUP,
FileType.OBJECTIVE_C: COMMON_C_DENYLIST_REGEX_TO_GROUP,
FileType.C_SHARP: COMMON_C_DENYLIST_REGEX_TO_GROUP,
FileType.C: COMMON_C_DENYLIST_REGEX_TO_GROUP,
FileType.C_PLUS_PLUS: C_PLUS_PLUS_REGEX_TO_GROUP,
FileType.CLS: QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP,
FileType.JAVA: QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP,
FileType.JAVASCRIPT: QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP,
FileType.PYTHON: QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP,
FileType.SWIFT: QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP,
FileType.TERRAFORM: QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP,
FileType.YAML: CONFIG_DENYLIST_REGEX_TO_GROUP,
FileType.CONFIG: CONFIG_DENYLIST_REGEX_TO_GROUP,
FileType.INI: CONFIG_DENYLIST_REGEX_TO_GROUP,
FileType.PROPERTIES: CONFIG_DENYLIST_REGEX_TO_GROUP,
FileType.TOML: CONFIG_DENYLIST_REGEX_TO_GROUP,
}
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,
]
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,
context: CodeSnippet = None,
**kwargs: Any,
) -> Set[PotentialSecret]:
filetype = determine_file_type(filename)
denylist_regex_to_group = REGEX_BY_FILETYPE.get(filetype, QUOTES_REQUIRED_DENYLIST_REGEX_TO_GROUP) # noqa: E501
return super().analyze_line(
filename=filename,
line=line,
line_number=line_number,
context=context,
denylist_regex_to_group=denylist_regex_to_group,
)
def json(self) -> Dict[str, Any]:
return {
'keyword_exclude': (
self.keyword_exclude.pattern
if self.keyword_exclude
else ''
),
**super().json(),
}