forked from Yelp/detect-secrets
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathjwt.py
More file actions
50 lines (43 loc) · 1.56 KB
/
jwt.py
File metadata and controls
50 lines (43 loc) · 1.56 KB
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
"""
This plugin finds JWT tokens
"""
import base64
import json
import re
from .base import classproperty
from .base import RegexBasedDetector
class JwtTokenDetector(RegexBasedDetector):
"""Scans for JWTs."""
secret_type = 'JSON Web Token'
denylist = [
re.compile(r'eyJ[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*?'),
]
@classproperty
def flag_text(cls):
return 'no-jwt-scan'
def secret_generator(self, string, *args, **kwargs):
return filter(
self.is_formally_valid,
super(JwtTokenDetector, self).secret_generator(string, *args, **kwargs),
)
@staticmethod
def is_formally_valid(token):
parts = token.split('.')
for idx, part in enumerate(parts):
try:
part = part.encode('ascii')
# https://github.com/magical/jwt-python/blob/2fd976b41111031313107792b40d5cfd1a8baf90/jwt.py#L49
# https://github.com/jpadilla/pyjwt/blob/3d47b0ea9e5d489f9c90ee6dde9e3d9d69244e3a/jwt/utils.py#L33
m = len(part) % 4
if m == 1:
raise TypeError('Incorrect padding')
elif m == 2:
part += '=='.encode('utf-8')
elif m == 3:
part += '==='.encode('utf-8')
b64_decoded = base64.urlsafe_b64decode(part)
if idx < 2:
_ = json.loads(b64_decoded.decode('utf-8'))
except (TypeError, ValueError, UnicodeDecodeError):
return False
return True