483b06
From e8805e118446a1ad542d183e2f6bea0f87651795 Mon Sep 17 00:00:00 2001
483b06
From: Jan Cholasta <jcholast@redhat.com>
483b06
Date: Thu, 27 Apr 2017 09:37:38 +0200
483b06
Subject: [PATCH] certdb: use custom object for trust flags
483b06
483b06
Replace trust flag strings with `TrustFlags` objects. The `TrustFlags`
483b06
class encapsulates `certstore` key policy and has an additional flag
483b06
indicating the presence of a private key.
483b06
483b06
https://pagure.io/freeipa/issue/6831
483b06
483b06
Reviewed-By: Stanislav Laznicka <slaznick@redhat.com>
483b06
Reviewed-By: Martin Babinsky <mbabinsk@redhat.com>
483b06
---
483b06
 install/restart_scripts/renew_ca_cert       |   2 +-
483b06
 ipalib/install/certstore.py                 |  49 +------------
483b06
 ipapython/certdb.py                         | 109 ++++++++++++++++++++++++++--
483b06
 ipaserver/install/installutils.py           |   2 +-
483b06
 ipaserver/install/ipa_cacert_manage.py      |   6 +-
483b06
 ipaserver/install/ipa_server_certinstall.py |   4 +-
483b06
 ipaserver/install/plugins/upload_cacrt.py   |   2 +-
483b06
 ipaserver/install/server/upgrade.py         |   2 +-
483b06
 8 files changed, 117 insertions(+), 59 deletions(-)
483b06
483b06
diff --git a/install/restart_scripts/renew_ca_cert b/install/restart_scripts/renew_ca_cert
483b06
index 7a54b4c7e05a35b40b17e46b75ff8d47db1b2d23..bb31defc0e2bdca044e68ae067f42fb3bd41a57f 100644
483b06
--- a/install/restart_scripts/renew_ca_cert
483b06
+++ b/install/restart_scripts/renew_ca_cert
483b06
@@ -125,7 +125,7 @@ def _main():
483b06
 
483b06
             # Remove old external CA certificates
483b06
             for ca_nick, ca_flags in db.list_certs():
483b06
-                if 'u' in ca_flags:
483b06
+                if ca_flags.has_key:
483b06
                     continue
483b06
                 # Delete *all* certificates that use the nickname
483b06
                 while True:
483b06
diff --git a/ipalib/install/certstore.py b/ipalib/install/certstore.py
483b06
index 310e08ed2273badba6fde4ada0ee52501fddc72c..bc2079fb12873444cbe6796eebfdfcfebd0e284d 100644
483b06
--- a/ipalib/install/certstore.py
483b06
+++ b/ipalib/install/certstore.py
483b06
@@ -25,7 +25,7 @@ LDAP shared certificate store.
483b06
 from pyasn1.error import PyAsn1Error
483b06
 
483b06
 from ipapython.dn import DN
483b06
-from ipapython.certdb import get_ca_nickname
483b06
+from ipapython.certdb import get_ca_nickname, TrustFlags
483b06
 from ipalib import errors, x509
483b06
 
483b06
 def _parse_cert(dercert):
483b06
@@ -344,57 +344,14 @@ def trust_flags_to_key_policy(trust_flags):
483b06
     """
483b06
     Convert certutil trust flags to certificate store key policy.
483b06
     """
483b06
-    if 'p' in trust_flags:
483b06
-        if 'C' in trust_flags or 'P' in trust_flags or 'T' in trust_flags:
483b06
-            raise ValueError("cannot be both trusted and not trusted")
483b06
-        return False, None, None
483b06
-    elif 'C' in trust_flags or 'T' in trust_flags:
483b06
-        if 'P' in trust_flags:
483b06
-            raise ValueError("cannot be both CA and not CA")
483b06
-        ca = True
483b06
-    elif 'P' in trust_flags:
483b06
-        ca = False
483b06
-    else:
483b06
-        return None, None, set()
483b06
-
483b06
-    trust_flags = trust_flags.split(',')
483b06
-    ext_key_usage = set()
483b06
-    for i, kp in enumerate((x509.EKU_SERVER_AUTH,
483b06
-                            x509.EKU_EMAIL_PROTECTION,
483b06
-                            x509.EKU_CODE_SIGNING)):
483b06
-        if 'C' in trust_flags[i] or 'P' in trust_flags[i]:
483b06
-            ext_key_usage.add(kp)
483b06
-    if 'T' in trust_flags[0]:
483b06
-        ext_key_usage.add(x509.EKU_CLIENT_AUTH)
483b06
-
483b06
-    return True, ca, ext_key_usage
483b06
+    return trust_flags[1:]
483b06
 
483b06
 
483b06
 def key_policy_to_trust_flags(trusted, ca, ext_key_usage):
483b06
     """
483b06
     Convert certificate store key policy to certutil trust flags.
483b06
     """
483b06
-    if trusted is False:
483b06
-        return 'p,p,p'
483b06
-    elif trusted is None or ca is None:
483b06
-        return ',,'
483b06
-    elif ext_key_usage is None:
483b06
-        if ca:
483b06
-            return 'CT,C,C'
483b06
-        else:
483b06
-            return 'P,P,P'
483b06
-
483b06
-    trust_flags = ['', '', '']
483b06
-    for i, kp in enumerate((x509.EKU_SERVER_AUTH,
483b06
-                            x509.EKU_EMAIL_PROTECTION,
483b06
-                            x509.EKU_CODE_SIGNING)):
483b06
-        if kp in ext_key_usage:
483b06
-            trust_flags[i] += ('C' if ca else 'P')
483b06
-    if ca and x509.EKU_CLIENT_AUTH in ext_key_usage:
483b06
-        trust_flags[0] += 'T'
483b06
-
483b06
-    trust_flags = ','.join(trust_flags)
483b06
-    return trust_flags
483b06
+    return TrustFlags(False, trusted, ca, ext_key_usage)
483b06
 
483b06
 
483b06
 def put_ca_cert_nss(ldap, base_dn, dercert, nickname, trust_flags,
483b06
diff --git a/ipapython/certdb.py b/ipapython/certdb.py
483b06
index 88dcae750de5881ae7b4921ca1ae23daa9c5d4b0..af95eba3cbad1c354615457ed0501f97bff0e22d 100644
483b06
--- a/ipapython/certdb.py
483b06
+++ b/ipapython/certdb.py
483b06
@@ -17,6 +17,7 @@
483b06
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
483b06
 #
483b06
 
483b06
+import collections
483b06
 import os
483b06
 import io
483b06
 import pwd
483b06
@@ -52,10 +53,26 @@ CA_NICKNAME_FMT = "%s IPA CA"
483b06
 
483b06
 NSS_FILES = ("cert8.db", "key3.db", "secmod.db", "pwdfile.txt")
483b06
 
483b06
-EMPTY_TRUST_FLAGS = ',,'
483b06
-IPA_CA_TRUST_FLAGS = 'CT,C,C'
483b06
-EXTERNAL_CA_TRUST_FLAGS = 'C,,'
483b06
-TRUSTED_PEER_TRUST_FLAGS = 'P,,'
483b06
+TrustFlags = collections.namedtuple('TrustFlags', 'has_key trusted ca usages')
483b06
+
483b06
+EMPTY_TRUST_FLAGS = TrustFlags(False, None, None, None)
483b06
+
483b06
+IPA_CA_TRUST_FLAGS = TrustFlags(
483b06
+    False, True, True, frozenset({
483b06
+        x509.EKU_SERVER_AUTH,
483b06
+        x509.EKU_CLIENT_AUTH,
483b06
+        x509.EKU_CODE_SIGNING,
483b06
+        x509.EKU_EMAIL_PROTECTION,
483b06
+    }),
483b06
+)
483b06
+
483b06
+EXTERNAL_CA_TRUST_FLAGS = TrustFlags(
483b06
+    False, True, True, frozenset({x509.EKU_SERVER_AUTH}),
483b06
+)
483b06
+
483b06
+TRUSTED_PEER_TRUST_FLAGS = TrustFlags(
483b06
+    False, True, False, frozenset({x509.EKU_SERVER_AUTH}),
483b06
+)
483b06
 
483b06
 
483b06
 def get_ca_nickname(realm, format=CA_NICKNAME_FMT):
483b06
@@ -87,6 +104,82 @@ def get_file_cont(slot, token, filename):
483b06
         return f.read()
483b06
 
483b06
 
483b06
+def parse_trust_flags(trust_flags):
483b06
+    """
483b06
+    Convert certutil trust flags to TrustFlags object.
483b06
+    """
483b06
+    has_key = 'u' in trust_flags
483b06
+
483b06
+    if 'p' in trust_flags:
483b06
+        if 'C' in trust_flags or 'P' in trust_flags or 'T' in trust_flags:
483b06
+            raise ValueError("cannot be both trusted and not trusted")
483b06
+        return False, None, None
483b06
+    elif 'C' in trust_flags or 'T' in trust_flags:
483b06
+        if 'P' in trust_flags:
483b06
+            raise ValueError("cannot be both CA and not CA")
483b06
+        ca = True
483b06
+    elif 'P' in trust_flags:
483b06
+        ca = False
483b06
+    else:
483b06
+        return TrustFlags(has_key, None, None, frozenset())
483b06
+
483b06
+    trust_flags = trust_flags.split(',')
483b06
+    ext_key_usage = set()
483b06
+    for i, kp in enumerate((x509.EKU_SERVER_AUTH,
483b06
+                            x509.EKU_EMAIL_PROTECTION,
483b06
+                            x509.EKU_CODE_SIGNING)):
483b06
+        if 'C' in trust_flags[i] or 'P' in trust_flags[i]:
483b06
+            ext_key_usage.add(kp)
483b06
+    if 'T' in trust_flags[0]:
483b06
+        ext_key_usage.add(x509.EKU_CLIENT_AUTH)
483b06
+
483b06
+    return TrustFlags(has_key, True, ca, frozenset(ext_key_usage))
483b06
+
483b06
+
483b06
+def unparse_trust_flags(trust_flags):
483b06
+    """
483b06
+    Convert TrustFlags object to certutil trust flags.
483b06
+    """
483b06
+    has_key, trusted, ca, ext_key_usage = trust_flags
483b06
+
483b06
+    if trusted is False:
483b06
+        if has_key:
483b06
+            return 'pu,pu,pu'
483b06
+        else:
483b06
+            return 'p,p,p'
483b06
+    elif trusted is None or ca is None:
483b06
+        if has_key:
483b06
+            return 'u,u,u'
483b06
+        else:
483b06
+            return ',,'
483b06
+    elif ext_key_usage is None:
483b06
+        if ca:
483b06
+            if has_key:
483b06
+                return 'CTu,Cu,Cu'
483b06
+            else:
483b06
+                return 'CT,C,C'
483b06
+        else:
483b06
+            if has_key:
483b06
+                return 'Pu,Pu,Pu'
483b06
+            else:
483b06
+                return 'P,P,P'
483b06
+
483b06
+    trust_flags = ['', '', '']
483b06
+    for i, kp in enumerate((x509.EKU_SERVER_AUTH,
483b06
+                            x509.EKU_EMAIL_PROTECTION,
483b06
+                            x509.EKU_CODE_SIGNING)):
483b06
+        if kp in ext_key_usage:
483b06
+            trust_flags[i] += ('C' if ca else 'P')
483b06
+    if ca and x509.EKU_CLIENT_AUTH in ext_key_usage:
483b06
+        trust_flags[0] += 'T'
483b06
+    if has_key:
483b06
+        for i in range(3):
483b06
+            trust_flags[i] += 'u'
483b06
+
483b06
+    trust_flags = ','.join(trust_flags)
483b06
+    return trust_flags
483b06
+
483b06
+
483b06
 class NSSDatabase(object):
483b06
     """A general-purpose wrapper around a NSS cert database
483b06
 
483b06
@@ -205,7 +298,9 @@ class NSSDatabase(object):
483b06
         for cert in certs:
483b06
             match = re.match(r'^(.+?)\s+(\w*,\w*,\w*)\s*$', cert)
483b06
             if match:
483b06
-                certlist.append(match.groups())
483b06
+                nickname = match.group(1)
483b06
+                trust_flags = parse_trust_flags(match.group(2))
483b06
+                certlist.append((nickname, trust_flags))
483b06
 
483b06
         return tuple(certlist)
483b06
 
483b06
@@ -218,7 +313,7 @@ class NSSDatabase(object):
483b06
         """
483b06
         server_certs = []
483b06
         for name, flags in self.list_certs():
483b06
-            if 'u' in flags:
483b06
+            if flags.has_key:
483b06
                 server_certs.append((name, flags))
483b06
 
483b06
         return server_certs
483b06
@@ -477,6 +572,7 @@ class NSSDatabase(object):
483b06
                 "No need to add trust for built-in root CAs, skipping %s" %
483b06
                 root_nickname)
483b06
         else:
483b06
+            trust_flags = unparse_trust_flags(trust_flags)
483b06
             try:
483b06
                 self.run_certutil(["-M", "-n", root_nickname,
483b06
                                    "-t", trust_flags])
483b06
@@ -538,6 +634,7 @@ class NSSDatabase(object):
483b06
                              location)
483b06
 
483b06
     def add_cert(self, cert, nick, flags, pem=False):
483b06
+        flags = unparse_trust_flags(flags)
483b06
         args = ["-A", "-n", nick, "-t", flags]
483b06
         if pem:
483b06
             args.append("-a")
483b06
diff --git a/ipaserver/install/installutils.py b/ipaserver/install/installutils.py
483b06
index 0445a1d3c403fab690e5afb7c8801ed85773b1e0..5bce9894780bd920db11196b925492a7fe8f22d0 100644
483b06
--- a/ipaserver/install/installutils.py
483b06
+++ b/ipaserver/install/installutils.py
483b06
@@ -1034,7 +1034,7 @@ def load_pkcs12(cert_files, key_password, key_nickname, ca_cert_files,
483b06
                 raise ScriptError(str(e))
483b06
 
483b06
         for nickname, trust_flags in nssdb.list_certs():
483b06
-            if 'u' in trust_flags:
483b06
+            if trust_flags.has_key:
483b06
                 key_nickname = nickname
483b06
                 continue
483b06
             nssdb.trust_root_cert(nickname, EXTERNAL_CA_TRUST_FLAGS)
483b06
diff --git a/ipaserver/install/ipa_cacert_manage.py b/ipaserver/install/ipa_cacert_manage.py
483b06
index 88b40d45e10281d272882d21e06f5d53cf5a701d..d28a5966f054141819463cdb1dfef48ee1e46e92 100644
483b06
--- a/ipaserver/install/ipa_cacert_manage.py
483b06
+++ b/ipaserver/install/ipa_cacert_manage.py
483b06
@@ -26,7 +26,9 @@ import gssapi
483b06
 
483b06
 from ipalib.install import certmonger, certstore
483b06
 from ipapython import admintool, ipautil
483b06
-from ipapython.certdb import EMPTY_TRUST_FLAGS, EXTERNAL_CA_TRUST_FLAGS
483b06
+from ipapython.certdb import (EMPTY_TRUST_FLAGS,
483b06
+                              EXTERNAL_CA_TRUST_FLAGS,
483b06
+                              parse_trust_flags)
483b06
 from ipapython.dn import DN
483b06
 from ipaplatform.paths import paths
483b06
 from ipalib import api, errors, x509
483b06
@@ -366,6 +368,8 @@ class CACertManage(admintool.AdminTool):
483b06
             len(trust_flags.split(',')) != 3):
483b06
             raise admintool.ScriptError("Invalid trust flags")
483b06
 
483b06
+        trust_flags = parse_trust_flags(trust_flags)
483b06
+
483b06
         try:
483b06
             certstore.put_ca_cert_nss(
483b06
                 api.Backend.ldap2, api.env.basedn, cert, nickname, trust_flags)
483b06
diff --git a/ipaserver/install/ipa_server_certinstall.py b/ipaserver/install/ipa_server_certinstall.py
483b06
index ee93535edfd258fe71099881c54c413516b24d17..9f2cd9573a156949ae979e7b69fbd23adaf2feb8 100644
483b06
--- a/ipaserver/install/ipa_server_certinstall.py
483b06
+++ b/ipaserver/install/ipa_server_certinstall.py
483b06
@@ -170,13 +170,13 @@ class ServerCertInstall(admintool.AdminTool):
483b06
             # this leaves only the server certs in the temp db
483b06
             tempnssdb.import_pkcs12(pkcs12_filename, pkcs12_pin)
483b06
             for nickname, flags in tempnssdb.list_certs():
483b06
-                if 'u' not in flags:
483b06
+                if not flags.has_key:
483b06
                     while tempnssdb.has_nickname(nickname):
483b06
                         tempnssdb.delete_cert(nickname)
483b06
 
483b06
             # import all the CA certs from nssdb into the temp db
483b06
             for nickname, flags in nssdb.list_certs():
483b06
-                if 'u' not in flags:
483b06
+                if not flags.has_key:
483b06
                     cert = nssdb.get_cert_from_db(nickname)
483b06
                     tempnssdb.add_cert(cert, nickname, flags)
483b06
 
483b06
diff --git a/ipaserver/install/plugins/upload_cacrt.py b/ipaserver/install/plugins/upload_cacrt.py
483b06
index 7d294ff971bd109e5fbb3570bfff0198f24b68d3..73cc91d8f6dd5811ec74efecd6c885cd8937a0f2 100644
483b06
--- a/ipaserver/install/plugins/upload_cacrt.py
483b06
+++ b/ipaserver/install/plugins/upload_cacrt.py
483b06
@@ -52,7 +52,7 @@ class update_upload_cacrt(Updater):
483b06
         ldap = self.api.Backend.ldap2
483b06
 
483b06
         for nickname, trust_flags in db.list_certs():
483b06
-            if 'u' in trust_flags:
483b06
+            if trust_flags.has_key:
483b06
                 continue
483b06
             if nickname == ca_nickname and ca_enabled:
483b06
                 trust_flags = certdb.IPA_CA_TRUST_FLAGS
483b06
diff --git a/ipaserver/install/server/upgrade.py b/ipaserver/install/server/upgrade.py
483b06
index 73a4f1108a56a766cdbbcb93d7050482a8264a75..c244958f4cddba0d1edded5165a295b1e1ee2b8a 100644
483b06
--- a/ipaserver/install/server/upgrade.py
483b06
+++ b/ipaserver/install/server/upgrade.py
483b06
@@ -1547,7 +1547,7 @@ def disable_httpd_system_trust(http):
483b06
 
483b06
     db = certs.CertDB(api.env.realm, nssdir=paths.HTTPD_ALIAS_DIR)
483b06
     for nickname, trust_flags in db.list_certs():
483b06
-        if 'u' not in trust_flags:
483b06
+        if not trust_flags.has_key:
483b06
             cert = db.get_cert_from_db(nickname, pem=False)
483b06
             if cert:
483b06
                 ca_certs.append((cert, nickname, trust_flags))
483b06
-- 
483b06
2.9.4
483b06