diff --git a/oauth2client/_pure_python_crypt.py b/oauth2client/_pure_python_crypt.py new file mode 100644 index 0000000..af98477 --- /dev/null +++ b/oauth2client/_pure_python_crypt.py @@ -0,0 +1,185 @@ +# Copyright 2016 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Pure Python crypto-related routines for oauth2client. + +Uses the ``rsa``, ``pyasn1`` and ``pyasn1_modules`` packages +to parse PEM files storing PKCS#1 or PKCS#8 keys as well as +certificates. +""" + +from pyasn1.codec.der import decoder +from pyasn1_modules import pem +from pyasn1_modules.rfc2459 import Certificate +from pyasn1_modules.rfc5208 import PrivateKeyInfo +import rsa +import six + +from oauth2client._helpers import _from_bytes +from oauth2client._helpers import _to_bytes + + +_PKCS12_ERROR = r"""\ +PKCS12 format is not supported by the RSA library. +Either install PyOpenSSL, or please convert .p12 format +to .pem format: + $ cat key.p12 | \ + > openssl pkcs12 -nodes -nocerts -passin pass:notasecret | \ + > openssl rsa > key.pem +""" + +_POW2 = (128, 64, 32, 16, 8, 4, 2, 1) +_PKCS1_MARKER = ('-----BEGIN RSA PRIVATE KEY-----', + '-----END RSA PRIVATE KEY-----') +_PKCS8_MARKER = ('-----BEGIN PRIVATE KEY-----', + '-----END PRIVATE KEY-----') +_PKCS8_SPEC = PrivateKeyInfo() + + +def _bit_list_to_bytes(bit_list): + """Converts an iterable of 1's and 0's to bytes. + + Combines the list 8 at a time, treating each group of 8 bits + as a single byte. + """ + num_bits = len(bit_list) + byte_vals = bytearray() + for start in six.moves.xrange(0, num_bits, 8): + curr_bits = bit_list[start:start + 8] + char_val = sum(val * digit + for val, digit in zip(_POW2, curr_bits)) + byte_vals.append(char_val) + return bytes(byte_vals) + + +class RsaVerifier(object): + """Verifies the signature on a message. + + Args: + pubkey: rsa.key.PublicKey (or equiv), The public key to verify with. + """ + + def __init__(self, pubkey): + self._pubkey = pubkey + + def verify(self, message, signature): + """Verifies a message against a signature. + + Args: + message: string or bytes, The message to verify. If string, will be + encoded to bytes as utf-8. + signature: string or bytes, The signature on the message. If + string, will be encoded to bytes as utf-8. + + Returns: + True if message was signed by the private key associated with the + public key that this object was constructed with. + """ + message = _to_bytes(message, encoding='utf-8') + try: + return rsa.pkcs1.verify(message, signature, self._pubkey) + except (ValueError, rsa.pkcs1.VerificationError): + return False + + @classmethod + def from_string(cls, key_pem, is_x509_cert): + """Construct an RsaVerifier instance from a string. + + Args: + key_pem: string, public key in PEM format. + is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it + is expected to be an RSA key in PEM format. + + Returns: + RsaVerifier instance. + + Raises: + ValueError: if the key_pem can't be parsed. In either case, error + will begin with 'No PEM start marker'. If + ``is_x509_cert`` is True, will fail to find the + "-----BEGIN CERTIFICATE-----" error, otherwise fails + to find "-----BEGIN RSA PUBLIC KEY-----". + """ + key_pem = _to_bytes(key_pem) + if is_x509_cert: + der = rsa.pem.load_pem(key_pem, 'CERTIFICATE') + asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) + if remaining != b'': + raise ValueError('Unused bytes', remaining) + + cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo'] + key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey']) + pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER') + else: + pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM') + return cls(pubkey) + + +class RsaSigner(object): + """Signs messages with a private key. + + Args: + pkey: rsa.key.PrivateKey (or equiv), The private key to sign with. + """ + + def __init__(self, pkey): + self._key = pkey + + def sign(self, message): + """Signs a message. + + Args: + message: bytes, Message to be signed. + + Returns: + string, The signature of the message for the given key. + """ + message = _to_bytes(message, encoding='utf-8') + return rsa.pkcs1.sign(message, self._key, 'SHA-256') + + @classmethod + def from_string(cls, key, password='notasecret'): + """Construct an RsaSigner instance from a string. + + Args: + key: string, private key in PEM format. + password: string, password for private key file. Unused for PEM + files. + + Returns: + RsaSigner instance. + + Raises: + ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in + PEM format. + """ + key = _from_bytes(key) # pem expects str in Py3 + marker_id, key_bytes = pem.readPemBlocksFromFile( + six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER) + + if marker_id == 0: + pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes, + format='DER') + elif marker_id == 1: + key_info, remaining = decoder.decode( + key_bytes, asn1Spec=_PKCS8_SPEC) + if remaining != b'': + raise ValueError('Unused bytes', remaining) + pkey_info = key_info.getComponentByName('privateKey') + pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(), + format='DER') + else: + raise ValueError('No key could be detected.') + + return cls(pkey) diff --git a/oauth2client/crypt.py b/oauth2client/crypt.py index c450c5c..c871cbb 100644 --- a/oauth2client/crypt.py +++ b/oauth2client/crypt.py @@ -24,6 +24,8 @@ from oauth2client._helpers import _json_encode from oauth2client._helpers import _to_bytes from oauth2client._helpers import _urlsafe_b64decode from oauth2client._helpers import _urlsafe_b64encode +from oauth2client._pure_python_crypt import RsaSigner +from oauth2client._pure_python_crypt import RsaVerifier CLOCK_SKEW_SECS = 300 # 5 minutes in seconds @@ -65,8 +67,8 @@ elif PyCryptoSigner: # pragma: NO COVER Signer = PyCryptoSigner Verifier = PyCryptoVerifier else: # pragma: NO COVER - raise ImportError('No encryption library found. Please install either ' - 'PyOpenSSL, or PyCrypto 2.6 or later') + Signer = RsaSigner + Verifier = RsaVerifier def make_signed_jwt(signer, payload): diff --git a/tests/data/privatekey.pub b/tests/data/privatekey.pub new file mode 100644 index 0000000..11fdaa4 --- /dev/null +++ b/tests/data/privatekey.pub @@ -0,0 +1,8 @@ +-----BEGIN RSA PUBLIC KEY----- +MIIBCgKCAQEA4ej0p7bQ7L/r4rVGUz9RN4VQWoej1Bg1mYWIDYslvKrk1gpj7wZg +kdmM7oVK2OfgrSj/FCTkInKPqaCR0gD7K80q+mLBrN3PUkDrJQZpvRZIff3/xmVU +1WeruQLFJjnFb2dqu0s/FY/2kWiJtBCakXvXEOb7zfbINuayL+MSsCGSdVYsSliS +5qQpgyDap+8b5fpXZVJkq92hrcNtbkg7hCYUJczt8n9hcCTJCfUpApvaFQ18pe+z +pyl4+WzkP66I28hniMQyUlA1hBiskT7qiouq0m8IOodhv2fagSZKjOTTU2xkSBc/ +/fy3ZpsL7WqgsZS7Q+0VRK8gKfqkxg5OYQIDAQAB +-----END RSA PUBLIC KEY----- diff --git a/tests/data/publickey.pem b/tests/data/public_cert.pem similarity index 100% rename from tests/data/publickey.pem rename to tests/data/public_cert.pem diff --git a/tests/test__pure_python_crypt.py b/tests/test__pure_python_crypt.py new file mode 100644 index 0000000..da18fbf --- /dev/null +++ b/tests/test__pure_python_crypt.py @@ -0,0 +1,179 @@ +# Copyright 2016 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit tests for oauth2client._pure_python_crypt.""" + +import os + +import mock +from pyasn1_modules import pem +import rsa +import six +import unittest2 + +from oauth2client._helpers import _from_bytes +from oauth2client import _pure_python_crypt +from oauth2client.crypt import RsaSigner +from oauth2client.crypt import RsaVerifier + + +class TestRsaVerifier(unittest2.TestCase): + + PUBLIC_KEY_FILENAME = os.path.join(os.path.dirname(__file__), + 'data', 'privatekey.pub') + PUBLIC_CERT_FILENAME = os.path.join(os.path.dirname(__file__), + 'data', 'public_cert.pem') + PRIVATE_KEY_FILENAME = os.path.join(os.path.dirname(__file__), + 'data', 'privatekey.pem') + + def _load_public_key_bytes(self): + with open(self.PUBLIC_KEY_FILENAME, 'rb') as fh: + return fh.read() + + def _load_public_cert_bytes(self): + with open(self.PUBLIC_CERT_FILENAME, 'rb') as fh: + return fh.read() + + def _load_private_key_bytes(self): + with open(self.PRIVATE_KEY_FILENAME, 'rb') as fh: + return fh.read() + + def test_verify_success(self): + to_sign = b'foo' + signer = RsaSigner.from_string(self._load_private_key_bytes()) + actual_signature = signer.sign(to_sign) + + verifier = RsaVerifier.from_string(self._load_public_key_bytes(), + is_x509_cert=False) + self.assertTrue(verifier.verify(to_sign, actual_signature)) + + def test_verify_unicode_success(self): + to_sign = u'foo' + signer = RsaSigner.from_string(self._load_private_key_bytes()) + actual_signature = signer.sign(to_sign) + + verifier = RsaVerifier.from_string(self._load_public_key_bytes(), + is_x509_cert=False) + self.assertTrue(verifier.verify(to_sign, actual_signature)) + + def test_verify_failure(self): + verifier = RsaVerifier.from_string(self._load_public_key_bytes(), + is_x509_cert=False) + bad_signature1 = b'' + self.assertFalse(verifier.verify(b'foo', bad_signature1)) + bad_signature2 = b'a' + self.assertFalse(verifier.verify(b'foo', bad_signature2)) + + def test_from_string_pub_key(self): + public_key = self._load_public_key_bytes() + verifier = RsaVerifier.from_string(public_key, is_x509_cert=False) + self.assertIsInstance(verifier, RsaVerifier) + self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) + + def test_from_string_pub_key_unicode(self): + public_key = _from_bytes(self._load_public_key_bytes()) + verifier = RsaVerifier.from_string(public_key, is_x509_cert=False) + self.assertIsInstance(verifier, RsaVerifier) + self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) + + def test_from_string_pub_cert(self): + public_cert = self._load_public_cert_bytes() + verifier = RsaVerifier.from_string(public_cert, is_x509_cert=True) + self.assertIsInstance(verifier, RsaVerifier) + self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) + + def test_from_string_pub_cert_unicode(self): + public_cert = _from_bytes(self._load_public_cert_bytes()) + verifier = RsaVerifier.from_string(public_cert, is_x509_cert=True) + self.assertIsInstance(verifier, RsaVerifier) + self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) + + def test_from_string_pub_cert_failure(self): + cert_bytes = self._load_public_cert_bytes() + true_der = rsa.pem.load_pem(cert_bytes, 'CERTIFICATE') + with mock.patch('rsa.pem.load_pem', + return_value=true_der + b'extra') as load_pem: + with self.assertRaises(ValueError): + RsaVerifier.from_string(cert_bytes, is_x509_cert=True) + load_pem.assert_called_once_with(cert_bytes, 'CERTIFICATE') + + +class TestRsaSigner(unittest2.TestCase): + + PKCS1_KEY_FILENAME = os.path.join(os.path.dirname(__file__), + 'data', 'privatekey.pem') + PKCS8_KEY_FILENAME = os.path.join(os.path.dirname(__file__), + 'data', 'pem_from_pkcs12.pem') + PKCS12_KEY_FILENAME = os.path.join(os.path.dirname(__file__), + 'data', 'privatekey.p12') + + def _load_pkcs1_key_bytes(self): + with open(self.PKCS1_KEY_FILENAME, 'rb') as fh: + return fh.read() + + def _load_pkcs8_key_bytes(self): + with open(self.PKCS8_KEY_FILENAME, 'rb') as fh: + return fh.read() + + def _load_pkcs12_key_bytes(self): + with open(self.PKCS12_KEY_FILENAME, 'rb') as fh: + return fh.read() + + def test_from_string_pkcs1(self): + key_bytes = self._load_pkcs1_key_bytes() + signer = RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, RsaSigner) + self.assertIsInstance(signer._key, rsa.key.PrivateKey) + + def test_from_string_pkcs1_unicode(self): + key_bytes = _from_bytes(self._load_pkcs1_key_bytes()) + signer = RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, RsaSigner) + self.assertIsInstance(signer._key, rsa.key.PrivateKey) + + def test_from_string_pkcs8(self): + key_bytes = self._load_pkcs8_key_bytes() + signer = RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, RsaSigner) + self.assertIsInstance(signer._key, rsa.key.PrivateKey) + + def test_from_string_pkcs8_extra_bytes(self): + key_bytes = self._load_pkcs8_key_bytes() + _, pem_bytes = pem.readPemBlocksFromFile( + six.StringIO(_from_bytes(key_bytes)), + _pure_python_crypt._PKCS8_MARKER) + + with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode: + key_info, remaining = None, 'extra' + mock_decode.return_value = (key_info, remaining) + with self.assertRaises(ValueError): + RsaSigner.from_string(key_bytes) + # Verify mock was called. + mock_decode.assert_called_once_with( + pem_bytes, asn1Spec=_pure_python_crypt._PKCS8_SPEC) + + def test_from_string_pkcs8_unicode(self): + key_bytes = _from_bytes(self._load_pkcs8_key_bytes()) + signer = RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, RsaSigner) + self.assertIsInstance(signer._key, rsa.key.PrivateKey) + + def test_from_string_pkcs12(self): + key_bytes = self._load_pkcs12_key_bytes() + with self.assertRaises(ValueError): + RsaSigner.from_string(key_bytes) + + +if __name__ == '__main__': # pragma: NO COVER + unittest2.main() diff --git a/tests/test__pycrypto_crypt.py b/tests/test__pycrypto_crypt.py index 0e6f6c2..55dd677 100644 --- a/tests/test__pycrypto_crypt.py +++ b/tests/test__pycrypto_crypt.py @@ -22,13 +22,13 @@ from oauth2client.crypt import PyCryptoVerifier class TestPyCryptoVerifier(unittest.TestCase): - PUBLIC_KEY_FILENAME = os.path.join(os.path.dirname(__file__), - 'data', 'publickey.pem') + PUBLIC_CERT_FILENAME = os.path.join(os.path.dirname(__file__), + 'data', 'public_cert.pem') PRIVATE_KEY_FILENAME = os.path.join(os.path.dirname(__file__), 'data', 'privatekey.pem') def _load_public_key_bytes(self): - with open(self.PUBLIC_KEY_FILENAME, 'rb') as fh: + with open(self.PUBLIC_CERT_FILENAME, 'rb') as fh: return fh.read() def _load_private_key_bytes(self): diff --git a/tests/test_jwt.py b/tests/test_jwt.py index 94aba16..f4a3bdb 100644 --- a/tests/test_jwt.py +++ b/tests/test_jwt.py @@ -58,7 +58,7 @@ class CryptTests(unittest2.TestCase): def _check_sign_and_verify(self, private_key_file): private_key = datafile(private_key_file) - public_key = datafile('publickey.pem') + public_key = datafile('public_cert.pem') # We pass in a non-bytes password to make sure all branches # are traversed in tests. @@ -74,7 +74,7 @@ class CryptTests(unittest2.TestCase): self.assertFalse(verifier.verify(b'foo', u'bad signagure')) def _check_jwt_failure(self, jwt, expected_error): - public_key = datafile('publickey.pem') + public_key = datafile('public_cert.pem') certs = {'foo': public_key} audience = ('https://www.googleapis.com/auth/id?client_id=' 'external_public_key@testing.gserviceaccount.com') @@ -100,7 +100,7 @@ class CryptTests(unittest2.TestCase): def test_verify_id_token(self): jwt = self._create_signed_jwt() - public_key = datafile('publickey.pem') + public_key = datafile('public_cert.pem') certs = {'foo': public_key} audience = 'some_audience_address@testing.gserviceaccount.com' contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)