| 1 |
# This code is part of Ansible, but is an independent component. |
| 2 |
# This particular file snippet, and this file snippet only, is BSD licensed. |
| 3 |
# Modules you write using this snippet, which is embedded dynamically by Ansible |
| 4 |
# still belong to the author of the module, and may assign their own license |
| 5 |
# to the complete work. |
| 6 |
# |
| 7 |
# Copyright (c) 2016 Thomas Krahn (@Nosmoht) |
| 8 |
# |
| 9 |
# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 10 |
# SPDX-License-Identifier: BSD-2-Clause |
| 11 |
|
| 12 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 13 |
# Do not use this from other collections or standalone plugins/modules! |
| 14 |
|
| 15 |
from __future__ import annotations |
| 16 |
|
| 17 |
import json |
| 18 |
import os |
| 19 |
import re |
| 20 |
import socket |
| 21 |
import typing as t |
| 22 |
import uuid |
| 23 |
from http import HTTPStatus |
| 24 |
from urllib.parse import quote |
| 25 |
|
| 26 |
from ansible.module_utils.basic import AnsibleFallbackNotFound, env_fallback |
| 27 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 28 |
from ansible.module_utils.urls import HAS_GSSAPI, fetch_url |
| 29 |
|
| 30 |
if t.TYPE_CHECKING: |
| 31 |
from ansible.module_utils.basic import AnsibleModule |
| 32 |
|
| 33 |
|
| 34 |
def _env_then_dns_fallback(*args, **kwargs) -> str: |
| 35 |
"""Load value from environment or DNS in that order""" |
| 36 |
try: |
| 37 |
result = env_fallback(*args, **kwargs) |
| 38 |
if result == "": |
| 39 |
raise AnsibleFallbackNotFound |
| 40 |
return result |
| 41 |
except AnsibleFallbackNotFound: |
| 42 |
# If no host was given, we try to guess it from IPA. |
| 43 |
# The ipa-ca entry is a standard entry that IPA will have set for |
| 44 |
# the CA. |
| 45 |
try: |
| 46 |
return socket.gethostbyaddr(socket.gethostbyname("ipa-ca"))[0] |
| 47 |
except Exception: |
| 48 |
raise AnsibleFallbackNotFound from None # no need to pass the original exception's context since this is basically a special return value |
| 49 |
|
| 50 |
|
| 51 |
class IPAClient: |
| 52 |
def __init__(self, module: AnsibleModule, host, port, protocol): |
| 53 |
self.host = host |
| 54 |
self.port = port |
| 55 |
self.protocol = protocol |
| 56 |
self.module = module |
| 57 |
self.headers = None |
| 58 |
self.timeout = module.params.get("ipa_timeout") |
| 59 |
self.use_gssapi = False |
| 60 |
|
| 61 |
def get_base_url(self) -> str: |
| 62 |
return f"{self.protocol}://{self.host}/ipa" |
| 63 |
|
| 64 |
def get_json_url(self) -> str: |
| 65 |
return f"{self.get_base_url()}/session/json" |
| 66 |
|
| 67 |
def login(self, username, password): |
| 68 |
if "KRB5CCNAME" in os.environ and HAS_GSSAPI: |
| 69 |
self.use_gssapi = True |
| 70 |
elif "KRB5_CLIENT_KTNAME" in os.environ and HAS_GSSAPI: |
| 71 |
ccache = f"MEMORY:{uuid.uuid4()!s}" |
| 72 |
os.environ["KRB5CCNAME"] = ccache |
| 73 |
self.use_gssapi = True |
| 74 |
else: |
| 75 |
if not password: |
| 76 |
if "KRB5CCNAME" in os.environ or "KRB5_CLIENT_KTNAME" in os.environ: |
| 77 |
self.module.warn("In order to use GSSAPI, you need to install 'urllib_gssapi'") |
| 78 |
self._fail( |
| 79 |
"login", |
| 80 |
"Password is required if not using " |
| 81 |
"GSSAPI. To use GSSAPI, please set the " |
| 82 |
"KRB5_CLIENT_KTNAME or KRB5CCNAME (or both) " |
| 83 |
" environment variables.", |
| 84 |
) |
| 85 |
url = f"{self.get_base_url()}/session/login_password" |
| 86 |
data = f"user={quote(username, safe='')}&password={quote(password, safe='')}" |
| 87 |
headers = { |
| 88 |
"referer": self.get_base_url(), |
| 89 |
"Content-Type": "application/x-www-form-urlencoded", |
| 90 |
"Accept": "text/plain", |
| 91 |
} |
| 92 |
try: |
| 93 |
resp, info = fetch_url( |
| 94 |
module=self.module, url=url, data=to_bytes(data), headers=headers, timeout=self.timeout |
| 95 |
) |
| 96 |
status_code = info["status"] |
| 97 |
if status_code not in (HTTPStatus.OK, HTTPStatus.CREATED, HTTPStatus.NO_CONTENT): |
| 98 |
self._fail("login", info["msg"]) |
| 99 |
|
| 100 |
self.headers = {"Cookie": info.get("set-cookie")} |
| 101 |
except Exception as e: |
| 102 |
self._fail("login", f"{e}") |
| 103 |
if not self.headers: |
| 104 |
self.headers = dict() |
| 105 |
self.headers.update( |
| 106 |
{"referer": self.get_base_url(), "Content-Type": "application/json", "Accept": "application/json"} |
| 107 |
) |
| 108 |
|
| 109 |
def _fail(self, msg: str, e) -> t.NoReturn: |
| 110 |
if "message" in e: |
| 111 |
err_string = e.get("message") |
| 112 |
else: |
| 113 |
err_string = e |
| 114 |
self.module.fail_json(msg=f"{msg}: {err_string}") |
| 115 |
|
| 116 |
def get_ipa_version(self): |
| 117 |
response = self.ping()["summary"] |
| 118 |
ipa_ver_regex = re.compile(r"IPA server version (\d+\.\d+\.\d+).*") |
| 119 |
version_match = ipa_ver_regex.match(response) |
| 120 |
ipa_version = None |
| 121 |
if version_match: |
| 122 |
ipa_version = version_match.groups()[0] |
| 123 |
return ipa_version |
| 124 |
|
| 125 |
def ping(self): |
| 126 |
return self._post_json(method="ping", name=None) |
| 127 |
|
| 128 |
def _post_json(self, method, name, item=None): |
| 129 |
if item is None: |
| 130 |
item = {} |
| 131 |
url = f"{self.get_base_url()}/session/json" |
| 132 |
data = dict(method=method) |
| 133 |
|
| 134 |
# TODO: We should probably handle this a little better. |
| 135 |
if method in ("ping", "config_show", "otpconfig_show"): |
| 136 |
data["params"] = [[], {}] |
| 137 |
elif method in ("config_mod", "otpconfig_mod"): |
| 138 |
data["params"] = [[], item] |
| 139 |
else: |
| 140 |
data["params"] = [[name], item] |
| 141 |
|
| 142 |
try: |
| 143 |
resp, info = fetch_url( |
| 144 |
module=self.module, |
| 145 |
url=url, |
| 146 |
data=to_bytes(json.dumps(data)), |
| 147 |
headers=self.headers, |
| 148 |
timeout=self.timeout, |
| 149 |
use_gssapi=self.use_gssapi, |
| 150 |
) |
| 151 |
status_code = info["status"] |
| 152 |
if status_code not in (HTTPStatus.OK, HTTPStatus.CREATED, HTTPStatus.NO_CONTENT): |
| 153 |
self._fail(method, info["msg"]) |
| 154 |
except Exception as e: |
| 155 |
self._fail(f"post {method}", f"{e}") |
| 156 |
|
| 157 |
charset = resp.headers.get_content_charset("latin-1") |
| 158 |
resp = json.loads(to_text(resp.read(), encoding=charset)) |
| 159 |
err = resp.get("error") |
| 160 |
if err is not None: |
| 161 |
self._fail(f"response {method}", err) |
| 162 |
|
| 163 |
if "result" in resp: |
| 164 |
result = resp.get("result") |
| 165 |
failed = result.get("failed") |
| 166 |
if failed: |
| 167 |
self._fail(f"response {method}", failed) |
| 168 |
if "result" in result: |
| 169 |
result = result.get("result") |
| 170 |
if isinstance(result, list): |
| 171 |
if len(result) > 0: |
| 172 |
return result[0] |
| 173 |
else: |
| 174 |
return {} |
| 175 |
return result |
| 176 |
return None |
| 177 |
|
| 178 |
def get_diff(self, ipa_data, module_data): |
| 179 |
result = [] |
| 180 |
for key in module_data.keys(): |
| 181 |
mod_value = module_data.get(key, None) |
| 182 |
if isinstance(mod_value, list): |
| 183 |
default = [] |
| 184 |
else: |
| 185 |
default = None |
| 186 |
ipa_value = ipa_data.get(key, default) |
| 187 |
if isinstance(ipa_value, list) and not isinstance(mod_value, list): |
| 188 |
mod_value = [mod_value] |
| 189 |
if isinstance(ipa_value, list) and isinstance(mod_value, list): |
| 190 |
mod_value = sorted(mod_value) |
| 191 |
ipa_value = sorted(ipa_value) |
| 192 |
if mod_value != ipa_value: |
| 193 |
result.append(key) |
| 194 |
return result |
| 195 |
|
| 196 |
def modify_if_diff(self, name, ipa_list, module_list, add_method, remove_method, item=None, append=None): |
| 197 |
changed = False |
| 198 |
diff = list(set(ipa_list) - set(module_list)) |
| 199 |
if append is not True and len(diff) > 0: |
| 200 |
changed = True |
| 201 |
if not self.module.check_mode: |
| 202 |
if item: |
| 203 |
remove_method(name=name, item={item: diff}) |
| 204 |
else: |
| 205 |
remove_method(name=name, item=diff) |
| 206 |
|
| 207 |
diff = list(set(module_list) - set(ipa_list)) |
| 208 |
if len(diff) > 0: |
| 209 |
changed = True |
| 210 |
if not self.module.check_mode: |
| 211 |
if item: |
| 212 |
add_method(name=name, item={item: diff}) |
| 213 |
else: |
| 214 |
add_method(name=name, item=diff) |
| 215 |
|
| 216 |
return changed |
| 217 |
|
| 218 |
|
| 219 |
def ipa_argument_spec() -> dict[str, t.Any]: |
| 220 |
return dict( |
| 221 |
ipa_prot=dict(type="str", default="https", choices=["http", "https"], fallback=(env_fallback, ["IPA_PROT"])), |
| 222 |
ipa_host=dict(type="str", default="ipa.example.com", fallback=(_env_then_dns_fallback, ["IPA_HOST"])), |
| 223 |
ipa_port=dict(type="int", default=443, fallback=(env_fallback, ["IPA_PORT"])), |
| 224 |
ipa_user=dict(type="str", default="admin", fallback=(env_fallback, ["IPA_USER"])), |
| 225 |
ipa_pass=dict(type="str", no_log=True, fallback=(env_fallback, ["IPA_PASS"])), |
| 226 |
ipa_timeout=dict(type="int", default=10, fallback=(env_fallback, ["IPA_TIMEOUT"])), |
| 227 |
validate_certs=dict(type="bool", default=True), |
| 228 |
) |