From e1c53bdfed9240268474c4571686fc0f5be87dcd Mon Sep 17 00:00:00 2001 From: Felix Fontein Date: Fri, 22 Mar 2019 11:45:55 +0100 Subject: [PATCH] openssl_publickey: fix handling of OpenSSH private keys with passphrase (#54192) * Cleanup. * Make sure that OpenSSH passphrases are handled correctly. * Add changelog. (cherry picked from commit 1a94cf140cfec80c67b1d5ae1299d8bb9dfb184f) --- .../54192-openssl_publickey-openssh-passphrase.yml | 2 ++ lib/ansible/modules/crypto/openssl_publickey.py | 14 ++++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) create mode 100644 changelogs/fragments/54192-openssl_publickey-openssh-passphrase.yml diff --git a/changelogs/fragments/54192-openssl_publickey-openssh-passphrase.yml b/changelogs/fragments/54192-openssl_publickey-openssh-passphrase.yml new file mode 100644 index 0000000000..e60bb9c8f3 --- /dev/null +++ b/changelogs/fragments/54192-openssl_publickey-openssh-passphrase.yml @@ -0,0 +1,2 @@ +bugfixes: +- "openssl_publickey - fixed crash on Python 3 when OpenSSH private keys were used with passphrases." diff --git a/lib/ansible/modules/crypto/openssl_publickey.py b/lib/ansible/modules/crypto/openssl_publickey.py index 6ff923ffc9..c202fe9a04 100644 --- a/lib/ansible/modules/crypto/openssl_publickey.py +++ b/lib/ansible/modules/crypto/openssl_publickey.py @@ -123,7 +123,6 @@ fingerprint: sha512: "fd:ed:5e:39:48:5f:9f:fe:7f:25:06:3f:79:08:cd:ee:a5:e7:b3:3d:13:82:87:1f:84:e1:f5:c7:28:77:53:94:86:56:38:69:f0:d9:35:22:01:1e:a6:60:...:0f:9b" ''' -import hashlib import os try: @@ -136,7 +135,7 @@ else: pyopenssl_found = True from ansible.module_utils import crypto as crypto_utils -from ansible.module_utils._text import to_native +from ansible.module_utils._text import to_native, to_bytes from ansible.module_utils.basic import AnsibleModule @@ -170,10 +169,13 @@ class PublicKey(crypto_utils.OpenSSLObject): if not self.check(module, perms_required=False) or self.force: try: if self.format == 'OpenSSH': - privatekey_content = open(self.privatekey_path, 'rb').read() - key = crypto_serialization.load_pem_private_key(privatekey_content, - password=self.privatekey_passphrase, - backend=default_backend()) + with open(self.privatekey_path, 'rb') as private_key_fh: + privatekey_content = private_key_fh.read() + key = crypto_serialization.load_pem_private_key( + privatekey_content, + password=None if self.privatekey_passphrase is None else to_bytes(self.privatekey_passphrase), + backend=default_backend() + ) publickey_content = key.public_key().public_bytes( crypto_serialization.Encoding.OpenSSH, crypto_serialization.PublicFormat.OpenSSH