| 18 | |
| 19 | |
| 20 | class JsonWebToken: |
| 21 | SENSITIVE_NAMES = ("password", "token", "secret", "secret_key") |
| 22 | # Thanks to sentry SensitiveDataFilter |
| 23 | SENSITIVE_VALUES = re.compile( |
| 24 | r"|".join( |
| 25 | [ |
| 26 | # http://www.richardsramblings.com/regex/credit-card-numbers/ |
| 27 | r"\b(?:3[47]\d|(?:4\d|5[1-5]|65)\d{2}|6011)\d{12}\b", |
| 28 | # various private keys |
| 29 | r"-----BEGIN[A-Z ]+PRIVATE KEY-----.+-----END[A-Z ]+PRIVATE KEY-----", |
| 30 | # social security numbers (US) |
| 31 | r"^\b(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b", |
| 32 | ] |
| 33 | ), |
| 34 | re.DOTALL, |
| 35 | ) |
| 36 | |
| 37 | def __init__(self, algorithms, private_headers=None): |
| 38 | self._jws = JsonWebSignature(algorithms, private_headers=private_headers) |
| 39 | self._jwe = JsonWebEncryption(algorithms, private_headers=private_headers) |
| 40 | |
| 41 | def check_sensitive_data(self, payload): |
| 42 | """Check if payload contains sensitive information.""" |
| 43 | for k in payload: |
| 44 | # check claims key name |
| 45 | if k in self.SENSITIVE_NAMES: |
| 46 | raise InsecureClaimError(k) |
| 47 | |
| 48 | # check claims values |
| 49 | v = payload[k] |
| 50 | if isinstance(v, str) and self.SENSITIVE_VALUES.search(v): |
| 51 | raise InsecureClaimError(k) |
| 52 | |
| 53 | def encode(self, header, payload, key, check=True): |
| 54 | """Encode a JWT with the given header, payload and key. |
| 55 | |
| 56 | :param header: A dict of JWS header |
| 57 | :param payload: A dict to be encoded |
| 58 | :param key: key used to sign the signature |
| 59 | :param check: check if sensitive data in payload |
| 60 | :return: bytes |
| 61 | """ |
| 62 | header.setdefault("typ", "JWT") |
| 63 | |
| 64 | for k in ["exp", "iat", "nbf"]: |
| 65 | # convert datetime into timestamp |
| 66 | claim = payload.get(k) |
| 67 | if isinstance(claim, datetime.datetime): |
| 68 | payload[k] = calendar.timegm(claim.utctimetuple()) |
| 69 | |
| 70 | if check: |
| 71 | self.check_sensitive_data(payload) |
| 72 | |
| 73 | key = find_encode_key(key, header) |
| 74 | text = to_bytes(json_dumps(payload)) |
| 75 | if "enc" in header: |
| 76 | return self._jwe.serialize_compact(header, text, key) |
| 77 | else: |
no outgoing calls
searching dependent graphs…