Skip to content

Commit

Permalink
Add load method for CA's
Browse files Browse the repository at this point in the history
  • Loading branch information
x00Pavel committed Jul 19, 2022
1 parent b272a1b commit c5218d9
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 50 deletions.
100 changes: 50 additions & 50 deletions SCAutolib/models/CA.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from pathlib import Path, PosixPath
from python_freeipa import exceptions
from python_freeipa.client_meta import ClientMeta
from shutil import rmtree, copy
from shutil import rmtree
from socket import gethostname

from SCAutolib import TEMPLATES_DIR, logger, run, LIB_DIR, LIB_DUMP_CAS
Expand Down Expand Up @@ -60,6 +60,28 @@ def revoke_cert(self, cert: Path):
"""
...

@staticmethod
def load(json_file):
"""
Load CA from JSON file.
:return: CA object
"""
with json_file.dump_file.open("r") as f:
cnt = json.load(f)

if "_ipa_server_ip" in cnt.keys():
ca = IPAServerCA(ip_addr=cnt["_ipa_server_ip"],
server_hostname=cnt["_ipa_server_hostname"],
root_passwd=cnt["_ipa_server_root_password"],
admin_passwd=cnt["_ipa_server_admin_password"],
client_hostname=cnt["_ipa_client_hostname"],
domain=cnt["_ipa_server_domain"],
realm=cnt["_ipa_server_realm"])
else:
ca = LocalCA(root_dir=cnt["root_dir"])
logger.debug(f"CA {type(ca)} is restored from file {json_file}")
return ca


class LocalCA(BaseCA):
template = Path(TEMPLATES_DIR, "ca.cnf")
Expand Down Expand Up @@ -217,29 +239,6 @@ def cleanup(self):
rmtree(self.root_dir, ignore_errors=True)
logger.info(f"Local CA from {self.root_dir} is removed")

def load(self):
"""
Load values of object from JSON file. Method set required type of
attributes.
:return: self
"""
to_path = ['root_dir', '_conf_dir', '_newcerts', '_certs', '_crl',
'_ca_pki_db', '_ca_cert', '_ca_key', '_serial', '_index']

with self.dump_file.open("r") as f:
cnt = json.load(f)
for k in to_path:
cnt[k] = Path(cnt[k])
# After CA is created, there is no need in CNF file. So, to simplify
# the loading, this attribute is set to None
cnt["_ca_cnf"] = None

for k, v in cnt.items():
setattr(self, k, v)

return self


class IPAServerCA(BaseCA):
"""
Expand Down Expand Up @@ -305,11 +304,19 @@ def __init__(self, ip_addr: str, server_hostname: str, domain: str,
@property
def is_installed(self):
"""
:return: True, if IPA client is installed on the system (ipa command
returns zero return code), otherwise False
:return: True, if IPA client is installed on the system (/etc/ipa
directory contains ca.crt file from IPA server), otherwise False
:rtype: bool
"""
return False
d = Path("/etc/ipa")
result = d.exists()
if result:
result = d.joinpath("ca.crt")
return result

@property
def domain(self):
return self._ipa_server_domain

@property
def __dict__(self):
Expand Down Expand Up @@ -337,14 +344,21 @@ def setup(self):
self._set_hostname()

logger.info("Installing IPA client")
run(["ipa-client-install", "-p", "admin",
"--password", self._ipa_server_admin_passwd,
"--server", self._ipa_server_hostname,
"--domain", self._ipa_server_domain,
"--realm", self._ipa_server_realm,
"--hostname", self._ipa_client_hostname,
"--all-ip-addresses", "--force", "--force-join", "--no-ntp", "-U"],
input="yes")
try:
run(["ipa-client-install", "-p", "admin",
"--password", self._ipa_server_admin_passwd,
"--server", self._ipa_server_hostname,
"--domain", self._ipa_server_domain,
"--realm", self._ipa_server_realm,
"--hostname", self._ipa_client_hostname,
"--force", "--force-join", "--no-ntp",
"--no-dns-sshfp", "--mkhomedir", "--unattended"],
input="yes")
except:
logger.critical("Installation of IPA client is failed")
rmtree("/etc/ipa/*")
logger.debug("Directory /etc/ipa is removed")
raise
logger.debug("IPA client is installed")

ipa_client_script = self._get_sc_setup_script()
Expand Down Expand Up @@ -563,23 +577,9 @@ def cleanup(self):
except exceptions.NotFound:
logger.error(f"Current hostname ({gethostname()}) is not found "
f"on the IPA server")
run(["ipa-client-install", "--uninstall", "-U"], check=True)
run(["ipa-client-install", "--uninstall", "-U"], return_code=[0, 2])
logger.info("IPA client is removed.")

def load(self):
"""
Load IPA from JSON file. Meta client will be connected. In case of any
error on client login, warning would
:return:
"""
with self.dump_file.open("r") as f:
cnt = json.load(f)

for k, v in cnt.items():
setattr(self, k, v)

self._meta_client_login()

class __PKeyChild(paramiko.PKey):
"""This child class is need to fix SSH connection with MD5 algorithm
in FIPS mode
Expand Down
11 changes: 11 additions & 0 deletions SCAutolib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
across the library. These functions are made based on library demands and are
not attended to cover some general use-cases or specific corner cases.
"""
import json

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from enum import Enum
Expand Down Expand Up @@ -109,3 +111,12 @@ def _check_packages(packages):
else:
logger.debug(f"Package {out.stdout.strip()} is present")
return missing


def dump_to_json(obj):
"""
Store serialised object to the JSON file.
"""
with obj.dump_file.open("w") as f:
json.dump(obj.__dict__, f)
logger.debug(f"Object {type(obj)} is stored to the {obj.dump_file} file")

0 comments on commit c5218d9

Please sign in to comment.