1# -*- coding: utf-8 -*- 2# 3# Copyright 2014 Google Inc. All rights reserved. 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16"""Crypto-related routines for oauth2client.""" 17 18import json 19import logging 20import time 21 22from oauth2client import _helpers 23 24 25CLOCK_SKEW_SECS = 300 # 5 minutes in seconds 26AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds 27MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds 28 29logger = logging.getLogger(__name__) 30 31 32class AppIdentityError(Exception): 33 """Error to indicate crypto failure.""" 34 35 36def _bad_pkcs12_key_as_pem(*args, **kwargs): 37 raise NotImplementedError('pkcs12_key_as_pem requires OpenSSL.') 38 39 40try: 41 from oauth2client import _openssl_crypt 42 OpenSSLSigner = _openssl_crypt.OpenSSLSigner 43 OpenSSLVerifier = _openssl_crypt.OpenSSLVerifier 44 pkcs12_key_as_pem = _openssl_crypt.pkcs12_key_as_pem 45except ImportError: # pragma: NO COVER 46 OpenSSLVerifier = None 47 OpenSSLSigner = None 48 pkcs12_key_as_pem = _bad_pkcs12_key_as_pem 49 50 51if OpenSSLSigner: 52 Signer = OpenSSLSigner 53 Verifier = OpenSSLVerifier 54else: # pragma: NO COVER 55 try: 56 from oauth2client import _pycrypto_crypt 57 Signer = _pycrypto_crypt.PyCryptoSigner 58 Verifier = _pycrypto_crypt.PyCryptoVerifier 59 except ImportError: # pragma: NO COVER 60 from oauth2client import _pure_python_crypt 61 Signer = _pure_python_crypt.RsaSigner 62 Verifier = _pure_python_crypt.RsaVerifier 63 64 65def make_signed_jwt(signer, payload, key_id=None): 66 """Make a signed JWT. 67 68 See http://self-issued.info/docs/draft-jones-json-web-token.html. 69 70 Args: 71 signer: crypt.Signer, Cryptographic signer. 72 payload: dict, Dictionary of data to convert to JSON and then sign. 73 key_id: string, (Optional) Key ID header. 74 75 Returns: 76 string, The JWT for the payload. 77 """ 78 header = {'typ': 'JWT', 'alg': 'RS256'} 79 if key_id is not None: 80 header['kid'] = key_id 81 82 segments = [ 83 _helpers._urlsafe_b64encode(_helpers._json_encode(header)), 84 _helpers._urlsafe_b64encode(_helpers._json_encode(payload)), 85 ] 86 signing_input = b'.'.join(segments) 87 88 signature = signer.sign(signing_input) 89 segments.append(_helpers._urlsafe_b64encode(signature)) 90 91 logger.debug(str(segments)) 92 93 return b'.'.join(segments) 94 95 96def _verify_signature(message, signature, certs): 97 """Verifies signed content using a list of certificates. 98 99 Args: 100 message: string or bytes, The message to verify. 101 signature: string or bytes, The signature on the message. 102 certs: iterable, certificates in PEM format. 103 104 Raises: 105 AppIdentityError: If none of the certificates can verify the message 106 against the signature. 107 """ 108 for pem in certs: 109 verifier = Verifier.from_string(pem, is_x509_cert=True) 110 if verifier.verify(message, signature): 111 return 112 113 # If we have not returned, no certificate confirms the signature. 114 raise AppIdentityError('Invalid token signature') 115 116 117def _check_audience(payload_dict, audience): 118 """Checks audience field from a JWT payload. 119 120 Does nothing if the passed in ``audience`` is null. 121 122 Args: 123 payload_dict: dict, A dictionary containing a JWT payload. 124 audience: string or NoneType, an audience to check for in 125 the JWT payload. 126 127 Raises: 128 AppIdentityError: If there is no ``'aud'`` field in the payload 129 dictionary but there is an ``audience`` to check. 130 AppIdentityError: If the ``'aud'`` field in the payload dictionary 131 does not match the ``audience``. 132 """ 133 if audience is None: 134 return 135 136 audience_in_payload = payload_dict.get('aud') 137 if audience_in_payload is None: 138 raise AppIdentityError( 139 'No aud field in token: {0}'.format(payload_dict)) 140 if audience_in_payload != audience: 141 raise AppIdentityError('Wrong recipient, {0} != {1}: {2}'.format( 142 audience_in_payload, audience, payload_dict)) 143 144 145def _verify_time_range(payload_dict): 146 """Verifies the issued at and expiration from a JWT payload. 147 148 Makes sure the current time (in UTC) falls between the issued at and 149 expiration for the JWT (with some skew allowed for via 150 ``CLOCK_SKEW_SECS``). 151 152 Args: 153 payload_dict: dict, A dictionary containing a JWT payload. 154 155 Raises: 156 AppIdentityError: If there is no ``'iat'`` field in the payload 157 dictionary. 158 AppIdentityError: If there is no ``'exp'`` field in the payload 159 dictionary. 160 AppIdentityError: If the JWT expiration is too far in the future (i.e. 161 if the expiration would imply a token lifetime 162 longer than what is allowed.) 163 AppIdentityError: If the token appears to have been issued in the 164 future (up to clock skew). 165 AppIdentityError: If the token appears to have expired in the past 166 (up to clock skew). 167 """ 168 # Get the current time to use throughout. 169 now = int(time.time()) 170 171 # Make sure issued at and expiration are in the payload. 172 issued_at = payload_dict.get('iat') 173 if issued_at is None: 174 raise AppIdentityError( 175 'No iat field in token: {0}'.format(payload_dict)) 176 expiration = payload_dict.get('exp') 177 if expiration is None: 178 raise AppIdentityError( 179 'No exp field in token: {0}'.format(payload_dict)) 180 181 # Make sure the expiration gives an acceptable token lifetime. 182 if expiration >= now + MAX_TOKEN_LIFETIME_SECS: 183 raise AppIdentityError( 184 'exp field too far in future: {0}'.format(payload_dict)) 185 186 # Make sure (up to clock skew) that the token wasn't issued in the future. 187 earliest = issued_at - CLOCK_SKEW_SECS 188 if now < earliest: 189 raise AppIdentityError('Token used too early, {0} < {1}: {2}'.format( 190 now, earliest, payload_dict)) 191 # Make sure (up to clock skew) that the token isn't already expired. 192 latest = expiration + CLOCK_SKEW_SECS 193 if now > latest: 194 raise AppIdentityError('Token used too late, {0} > {1}: {2}'.format( 195 now, latest, payload_dict)) 196 197 198def verify_signed_jwt_with_certs(jwt, certs, audience=None): 199 """Verify a JWT against public certs. 200 201 See http://self-issued.info/docs/draft-jones-json-web-token.html. 202 203 Args: 204 jwt: string, A JWT. 205 certs: dict, Dictionary where values of public keys in PEM format. 206 audience: string, The audience, 'aud', that this JWT should contain. If 207 None then the JWT's 'aud' parameter is not verified. 208 209 Returns: 210 dict, The deserialized JSON payload in the JWT. 211 212 Raises: 213 AppIdentityError: if any checks are failed. 214 """ 215 jwt = _helpers._to_bytes(jwt) 216 217 if jwt.count(b'.') != 2: 218 raise AppIdentityError( 219 'Wrong number of segments in token: {0}'.format(jwt)) 220 221 header, payload, signature = jwt.split(b'.') 222 message_to_sign = header + b'.' + payload 223 signature = _helpers._urlsafe_b64decode(signature) 224 225 # Parse token. 226 payload_bytes = _helpers._urlsafe_b64decode(payload) 227 try: 228 payload_dict = json.loads(_helpers._from_bytes(payload_bytes)) 229 except: 230 raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes)) 231 232 # Verify that the signature matches the message. 233 _verify_signature(message_to_sign, signature, certs.values()) 234 235 # Verify the issued at and created times in the payload. 236 _verify_time_range(payload_dict) 237 238 # Check audience. 239 _check_audience(payload_dict, audience) 240 241 return payload_dict 242