From 571cc210b5e48aa959ba6c16e6b325abaf0a12de Mon Sep 17 00:00:00 2001
From: Thomas Woerner <twoerner@redhat.com>
Date: Wed, 6 May 2020 13:22:45 +0200
Subject: [PATCH] ansible_freeipa_module: New function load_cert_from_str

For certmapdata processing in ipauser it is needed to be able to load a cert
from a string given in the task to be able to get the issuer and subject of
the certificate. The format of the certifiacte here is lacking the markers
for the begin and end of the certificate. Therefore load_pem_x509_certificate
can not be used directly. Also in IPA < 4.5 it is needed to load the
certificate with load_certificate instead of load_pem_x509_certificate. The
function is implementing this properly.
---
 .../module_utils/ansible_freeipa_module.py    | 21 +++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/plugins/module_utils/ansible_freeipa_module.py b/plugins/module_utils/ansible_freeipa_module.py
index af45a6cb..37e1fdfd 100644
--- a/plugins/module_utils/ansible_freeipa_module.py
+++ b/plugins/module_utils/ansible_freeipa_module.py
@@ -48,6 +48,13 @@ try:
     from ipalib.x509 import Encoding
 except ImportError:
     from cryptography.hazmat.primitives.serialization import Encoding
+
+try:
+    from ipalib.x509 import load_pem_x509_certificate
+except ImportError:
+    from ipalib.x509 import load_certificate
+    load_pem_x509_certificate = None
+
 import socket
 import base64
 import six
@@ -323,6 +330,20 @@ def encode_certificate(cert):
     return encoded
 
 
+def load_cert_from_str(cert):
+    cert = cert.strip()
+    if not cert.startswith("-----BEGIN CERTIFICATE-----"):
+        cert = "-----BEGIN CERTIFICATE-----\n" + cert
+    if not cert.endswith("-----END CERTIFICATE-----"):
+        cert += "\n-----END CERTIFICATE-----"
+
+    if load_pem_x509_certificate is not None:
+        cert = load_pem_x509_certificate(cert.encode('utf-8'))
+    else:
+        cert = load_certificate(cert.encode('utf-8'))
+    return cert
+
+
 def is_valid_port(port):
     if not isinstance(port, int):
         return False
-- 
GitLab