Skip to content

Commit

Permalink
Adding a pure Python crypt sub-module.
Browse files Browse the repository at this point in the history
Resurrects googleapis#1.
  • Loading branch information
dhermes committed Feb 4, 2016
1 parent 9bd8522 commit e676a02
Show file tree
Hide file tree
Showing 7 changed files with 382 additions and 8 deletions.
185 changes: 185 additions & 0 deletions oauth2client/_pure_python_crypt.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 4 additions & 2 deletions oauth2client/crypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
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
Expand Down Expand Up @@ -65,8 +67,8 @@ def _bad_pkcs12_key_as_pem(*args, **kwargs):
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):
Expand Down
8 changes: 8 additions & 0 deletions tests/data/privatekey.pub
Original file line number Diff line number Diff line change
@@ -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-----
File renamed without changes.
179 changes: 179 additions & 0 deletions tests/test__pure_python_crypt.py
Original file line number Diff line number Diff line change
@@ -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()
Loading

0 comments on commit e676a02

Please sign in to comment.