File size: 12,345 Bytes
5980447
1
2
{"repo": "apache/libcloud", "pull_number": 1280, "instance_id": "apache__libcloud-1280", "issue_numbers": "", "base_commit": "e8735a71023a46c24b715830358ee59039b45704", "patch": "diff --git a/libcloud/common/google.py b/libcloud/common/google.py\n--- a/libcloud/common/google.py\n+++ b/libcloud/common/google.py\n@@ -24,7 +24,7 @@\n Both are initially set up from the Cloud Console Console -\n https://cloud.google.com/console\n \n-Setting up Service Account authentication (note that you need the PyCrypto\n+Setting up Service Account authentication (note that you need the cryptography\n package installed to use this):\n \n - Go to the Console\n@@ -89,16 +89,13 @@\n                                    LibcloudError)\n \n try:\n-    from Crypto.Hash import SHA256\n-    from Crypto.PublicKey import RSA\n-    from Crypto.Signature import PKCS1_v1_5\n-    import Crypto.Random\n-    Crypto.Random.atfork()\n+    from cryptography.hazmat.backends import default_backend\n+    from cryptography.hazmat.primitives import serialization\n+    from cryptography.hazmat.primitives.hashes import SHA256\n+    from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15\n except ImportError:\n-    # The pycrypto library is unavailable\n+    # The cryptography library is unavailable\n     SHA256 = None\n-    RSA = None\n-    PKCS1_v1_5 = None\n \n UTC_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%SZ'\n \n@@ -472,8 +469,8 @@ class GoogleServiceAcctAuthConnection(GoogleBaseAuthConnection):\n     \"\"\"Authentication class for \"Service Account\" authentication.\"\"\"\n     def __init__(self, user_id, key, *args, **kwargs):\n         \"\"\"\n-        Check to see if PyCrypto is available, and convert key file path into a\n-        key string if the key is in a file.\n+        Check to see if cryptography is available, and convert key file path\n+        into a key string if the key is in a file.\n \n         :param  user_id: Email address to be used for Service Account\n                 authentication.\n@@ -483,7 +480,7 @@ def __init__(self, user_id, key, *args, **kwargs):\n         :type   key: ``str``\n         \"\"\"\n         if SHA256 is None:\n-            raise GoogleAuthError('PyCrypto library required for '\n+            raise GoogleAuthError('cryptography library required for '\n                                   'Service Account Authentication.')\n         # Check to see if 'key' is a file and read the file if it is.\n         if key.find(\"PRIVATE KEY---\") == -1:\n@@ -526,10 +523,17 @@ def get_new_token(self):\n         # The message contains both the header and claim set\n         message = b'.'.join((header_enc, claim_set_enc))\n         # Then the message is signed using the key supplied\n-        key = RSA.importKey(self.key)\n-        hash_func = SHA256.new(message)\n-        signer = PKCS1_v1_5.new(key)\n-        signature = base64.urlsafe_b64encode(signer.sign(hash_func))\n+        key = serialization.load_pem_private_key(\n+            b(self.key),\n+            password=None,\n+            backend=default_backend()\n+        )\n+        signature = key.sign(\n+            data=b(message),\n+            padding=PKCS1v15(),\n+            algorithm=SHA256()\n+        )\n+        signature = base64.urlsafe_b64encode(signature)\n \n         # Finally the message and signature are sent to get a token\n         jwt = b'.'.join((message, signature))\ndiff --git a/libcloud/compute/drivers/softlayer.py b/libcloud/compute/drivers/softlayer.py\n--- a/libcloud/compute/drivers/softlayer.py\n+++ b/libcloud/compute/drivers/softlayer.py\n@@ -18,7 +18,9 @@\n \n import time\n try:\n-    from Crypto.PublicKey import RSA\n+    from cryptography.hazmat.primitives.asymmetric import rsa\n+    from cryptography.hazmat.backends import default_backend\n+    from cryptography.hazmat.primitives import serialization\n     crypto = True\n except ImportError:\n     crypto = False\n@@ -386,17 +388,29 @@ def get_key_pair(self, name):\n     def create_key_pair(self, name, ex_size=4096):\n         if crypto is False:\n             raise NotImplementedError('create_key_pair needs'\n-                                      'the pycrypto library')\n-        key = RSA.generate(ex_size)\n+                                      'the cryptography library')\n+        key = rsa.generate_private_key(\n+            public_exponent=65537,\n+            key_size=4096,\n+            backend=default_backend()\n+        )\n+        public_key = key.public_key().public_bytes(\n+            encoding=serialization.Encoding.OpenSSH,\n+            format=serialization.PublicFormat.OpenSSH\n+        )\n         new_key = {\n-            'key': key.publickey().exportKey('OpenSSH'),\n+            'key': public_key,\n             'label': name,\n             'notes': '',\n         }\n         result = self.connection.request(\n             'SoftLayer_Security_Ssh_Key', 'createObject', new_key\n         ).object\n-        result['private'] = key.exportKey('PEM')\n+        result['private'] = key.private_bytes(\n+            encoding=serialization.Encoding.PEM,\n+            format=serialization.PrivateFormat.TraditionalOpenSSL,\n+            encryption_algorithm=serialization.NoEncryption()\n+        )\n         return self._to_key_pair(result)\n \n     def import_key_pair_from_string(self, name, key_material):\ndiff --git a/libcloud/utils/publickey.py b/libcloud/utils/publickey.py\n--- a/libcloud/utils/publickey.py\n+++ b/libcloud/utils/publickey.py\n@@ -17,7 +17,7 @@\n import hashlib\n \n from libcloud.utils.py3 import hexadigits\n-from libcloud.utils.py3 import bchr\n+from libcloud.utils.py3 import b\n \n __all__ = [\n     'get_pubkey_openssh_fingerprint',\n@@ -26,11 +26,11 @@\n ]\n \n try:\n-    from Crypto.Util.asn1 import DerSequence, DerObject\n-    from Crypto.PublicKey.RSA import algorithmIdentifier, importKey\n-    pycrypto_available = True\n+    from cryptography.hazmat.backends import default_backend\n+    from cryptography.hazmat.primitives import serialization\n+    cryptography_available = True\n except ImportError:\n-    pycrypto_available = False\n+    cryptography_available = False\n \n \n def _to_md5_fingerprint(data):\n@@ -40,25 +40,33 @@ def _to_md5_fingerprint(data):\n \n def get_pubkey_openssh_fingerprint(pubkey):\n     # We import and export the key to make sure it is in OpenSSH format\n-    if not pycrypto_available:\n-        raise RuntimeError('pycrypto is not available')\n-    k = importKey(pubkey)\n-    pubkey = k.exportKey('OpenSSH')[7:]\n-    decoded = base64.decodestring(pubkey)\n-    return _to_md5_fingerprint(decoded)\n+    if not cryptography_available:\n+        raise RuntimeError('cryptography is not available')\n+    public_key = serialization.load_ssh_public_key(\n+        b(pubkey),\n+        backend=default_backend()\n+    )\n+    pub_openssh = public_key.public_bytes(\n+        encoding=serialization.Encoding.OpenSSH,\n+        format=serialization.PublicFormat.OpenSSH,\n+    )[7:]  # strip ssh-rsa prefix\n+    return _to_md5_fingerprint(base64.decodestring(pub_openssh))\n \n \n def get_pubkey_ssh2_fingerprint(pubkey):\n     # This is the format that EC2 shows for public key fingerprints in its\n     # KeyPair mgmt API\n-    if not pycrypto_available:\n-        raise RuntimeError('pycrypto is not available')\n-    k = importKey(pubkey)\n-    derPK = DerSequence([k.n, k.e])\n-    bitmap = DerObject('BIT STRING')\n-    bitmap.payload = bchr(0x00) + derPK.encode()\n-    der = DerSequence([algorithmIdentifier, bitmap.encode()])\n-    return _to_md5_fingerprint(der.encode())\n+    if not cryptography_available:\n+        raise RuntimeError('cryptography is not available')\n+    public_key = serialization.load_ssh_public_key(\n+        b(pubkey),\n+        backend=default_backend()\n+    )\n+    pub_der = public_key.public_bytes(\n+        encoding=serialization.Encoding.DER,\n+        format=serialization.PublicFormat.SubjectPublicKeyInfo,\n+    )\n+    return _to_md5_fingerprint(pub_der)\n \n \n def get_pubkey_comment(pubkey, default=None):\ndiff --git a/libcloud/utils/py3.py b/libcloud/utils/py3.py\n--- a/libcloud/utils/py3.py\n+++ b/libcloud/utils/py3.py\n@@ -126,7 +126,7 @@ def tostring(node):\n \n     def hexadigits(s):\n         # s needs to be a byte string.\n-        return [format(x, \"x\") for x in s]\n+        return [format(x, \"02x\") for x in s]\n \n else:\n     import httplib  # NOQA\n", "test_patch": "diff --git a/libcloud/test/common/test_google.py b/libcloud/test/common/test_google.py\n--- a/libcloud/test/common/test_google.py\n+++ b/libcloud/test/common/test_google.py\n@@ -40,9 +40,9 @@\n from libcloud.utils.py3 import httplib\n \n \n-# Skip some tests if PyCrypto is unavailable\n+# Skip some tests if cryptography is unavailable\n try:\n-    from Crypto.Hash import SHA256\n+    from cryptography.hazmat.primitives.hashes import SHA256\n except ImportError:\n     SHA256 = None\n \ndiff --git a/libcloud/test/compute/test_softlayer.py b/libcloud/test/compute/test_softlayer.py\n--- a/libcloud/test/compute/test_softlayer.py\n+++ b/libcloud/test/compute/test_softlayer.py\n@@ -16,12 +16,6 @@\n import unittest\n import sys\n import pytest\n-try:\n-    import Crypto\n-    Crypto\n-    crypto = True\n-except ImportError:\n-    crypto = False\n \n from libcloud.common.types import InvalidCredsError\n \n@@ -170,17 +164,13 @@ def test_get_key_pair_does_not_exist(self):\n \n     @pytest.mark.skip(reason=\"no way of currently testing this\")\n     def test_create_key_pair(self):\n-        if crypto:\n-            key_pair = self.driver.create_key_pair(name='my-key-pair')\n-            fingerprint = ('1f:51:ae:28:bf:89:e9:d8:1f:25:5d'\n-                           ':37:2d:7d:b8:ca:9f:f5:f1:6f')\n-\n-            self.assertEqual(key_pair.name, 'my-key-pair')\n-            self.assertEqual(key_pair.fingerprint, fingerprint)\n-            self.assertTrue(key_pair.private_key is not None)\n-        else:\n-            self.assertRaises(NotImplementedError, self.driver.create_key_pair,\n-                              name='my-key-pair')\n+        key_pair = self.driver.create_key_pair(name='my-key-pair')\n+        fingerprint = ('1f:51:ae:28:bf:89:e9:d8:1f:25:5d'\n+                       ':37:2d:7d:b8:ca:9f:f5:f1:6f')\n+\n+        self.assertEqual(key_pair.name, 'my-key-pair')\n+        self.assertEqual(key_pair.fingerprint, fingerprint)\n+        self.assertTrue(key_pair.private_key is not None)\n \n     def test_delete_key_pair(self):\n         success = self.driver.delete_key_pair('test1')\ndiff --git a/libcloud/test/test_utils.py b/libcloud/test/test_utils.py\n--- a/libcloud/test/test_utils.py\n+++ b/libcloud/test/test_utils.py\n@@ -47,6 +47,10 @@\n from libcloud.utils.networking import increment_ipv4_segments\n from libcloud.utils.decorators import wrap_non_libcloud_exceptions\n from libcloud.utils.connection import get_response_object\n+from libcloud.utils.publickey import (\n+    get_pubkey_openssh_fingerprint,\n+    get_pubkey_ssh2_fingerprint,\n+)\n from libcloud.common.types import LibcloudError\n from libcloud.storage.drivers.dummy import DummyIterator\n \n@@ -385,6 +389,26 @@ def test_increment_ipv4_segments(self):\n             self.assertEqual(result, incremented_ip)\n \n \n+class TestPublicKeyUtils(unittest.TestCase):\n+\n+    PUBKEY = (\n+        'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDOfbWSXOlqvYjZmRO84/lIoV4gvuX+'\n+        'P1lLg50MMg6jZjLZIlYY081XPRmuom0xY0+BO++J2KgLl7gxJ6xMsKK2VQ+TakdfAH20'\n+        'XfMcTohd/zVCeWsbqZQvEhVXBo4hPIktcfNz0u9Ez3EtInO+kb7raLcRhOVi9QmOkOrC'\n+        'WtQU9mS71AWJuqI9H0YAnTiI8Hs5bn2tpMIqmTXT3g2bwywC25x1Nx9Hy0/FP+KUL6Ag'\n+        'vDXv47l+TgSDfTBEkvq+IF1ITrnaOG+nRE02oZC6cwHYTifM/IOollkujxIQmi2Z+j66'\n+        'OHSrjnEQugr0FqGJF2ygKfIh/i2u3fVLM60qE2NN user@example'\n+    )\n+\n+    def test_pubkey_openssh_fingerprint(self):\n+        fp = get_pubkey_openssh_fingerprint(self.PUBKEY)\n+        self.assertEqual(fp, '35:22:13:5b:82:e2:5d:e1:90:8c:73:74:9f:ef:3b:d8')\n+\n+    def test_pubkey_ssh2_fingerprint(self):\n+        fp = get_pubkey_ssh2_fingerprint(self.PUBKEY)\n+        self.assertEqual(fp, '11:ad:5d:4c:5b:99:c9:80:7e:81:03:76:5a:25:9d:8c')\n+\n+\n def test_decorator():\n \n     @wrap_non_libcloud_exceptions\n", "problem_statement": "", "hints_text": "", "created_at": "2019-03-11T14:45:18Z"}