| 1 |
# (c) 2019 Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import (absolute_import, division, print_function) |
| 5 |
__metaclass__ = type |
| 6 |
|
| 7 |
DOCUMENTATION = ''' |
| 8 |
name: laps_password |
| 9 |
author: Jordan Borean (@jborean93) |
| 10 |
short_description: Retrieves the LAPS password for a server. |
| 11 |
description: |
| 12 |
- This lookup returns the LAPS password set for a server from the Active Directory database. |
| 13 |
- See U(https://github.com/jborean93/ansible-lookup-laps_password) for more information around installing |
| 14 |
pre-requisites and testing. |
| 15 |
deprecated: |
| 16 |
removed_in: '4.0.0' |
| 17 |
why: >- |
| 18 |
This plugin does not support the newer Windows LAPS implementation and using a lookup for a password is inefficient. The |
| 19 |
P(microsoft.ad.ldap#inventory) inventory plugin can be used to retrieve the LAPS password for multiple hosts in a more |
| 20 |
efficient manner and supports both the legacy and newer LAPS implementation. |
| 21 |
alternative: Use P(microsoft.ad.ldap#inventory) instead. |
| 22 |
options: |
| 23 |
_terms: |
| 24 |
description: |
| 25 |
- The host name to retrieve the LAPS password for. |
| 26 |
- This is the C(Common Name (CN)) of the host. |
| 27 |
required: True |
| 28 |
type: str |
| 29 |
allow_plaintext: |
| 30 |
description: |
| 31 |
- When set to C(yes), will allow traffic to be sent unencrypted. |
| 32 |
- It is highly recommended to not touch this to avoid any credentials being exposed over the network. |
| 33 |
- Use C(scheme=ldaps), C(auth=gssapi), or C(start_tls=yes) to ensure the traffic is encrypted. |
| 34 |
default: no |
| 35 |
type: bool |
| 36 |
auth: |
| 37 |
description: |
| 38 |
- The type of authentication to use when connecting to the Active Directory server |
| 39 |
- When using C(simple), the I(username) and I(password) options must be set. If not using C(scheme=ldaps) or |
| 40 |
C(start_tls=True) then these credentials are exposed in plaintext in the network traffic. |
| 41 |
- It is recommended ot use C(gssapi) as it will encrypt the traffic automatically. |
| 42 |
- When using C(gssapi), run C(kinit) before running Ansible to get a valid Kerberos ticket. |
| 43 |
- You cannot use C(gssapi) when either C(scheme=ldaps) or C(start_tls=True) is set. |
| 44 |
choices: |
| 45 |
- simple |
| 46 |
- gssapi |
| 47 |
default: gssapi |
| 48 |
type: str |
| 49 |
ca_cert: |
| 50 |
description: |
| 51 |
- The path to a CA certificate PEM file to use for certificate validation. |
| 52 |
- Certificate validation is used when C(scheme=ldaps) or C(start_tls=yes). |
| 53 |
- This may fail on hosts with an older OpenLDAP install like MacOS, this will have to be updated before |
| 54 |
reinstalling python-ldap to get working again. |
| 55 |
type: str |
| 56 |
aliases: [ cacert_file ] |
| 57 |
domain: |
| 58 |
description: |
| 59 |
- The domain to search in to retrieve the LAPS password. |
| 60 |
- This could either be a Windows domain name visible to the Ansible controller from DNS or a specific domain |
| 61 |
controller FQDN. |
| 62 |
- Supports either just the domain/host name or an explicit LDAP URI with the domain/host already filled in. |
| 63 |
- If the URI is set, I(port) and I(scheme) are ignored. |
| 64 |
required: True |
| 65 |
type: str |
| 66 |
password: |
| 67 |
description: |
| 68 |
- The password for C(username). |
| 69 |
- Required when C(username) is set. |
| 70 |
type: str |
| 71 |
port: |
| 72 |
description: |
| 73 |
- The LDAP port to communicate over. |
| 74 |
- If I(kdc) is already an LDAP URI then this is ignored. |
| 75 |
type: int |
| 76 |
scheme: |
| 77 |
description: |
| 78 |
- The LDAP scheme to use. |
| 79 |
- When using C(ldap), it is recommended to set C(auth=gssapi), or C(start_tls=yes), otherwise traffic will be in |
| 80 |
plaintext. |
| 81 |
- The Active Directory host must be configured for C(ldaps) with a certificate before it can be used. |
| 82 |
- If I(kdc) is already an LDAP URI then this is ignored. |
| 83 |
choices: |
| 84 |
- ldap |
| 85 |
- ldaps |
| 86 |
default: ldap |
| 87 |
search_base: |
| 88 |
description: |
| 89 |
- Changes the search base used when searching for the host in Active Directory. |
| 90 |
- Will default to search in the C(defaultNamingContext) of the Active Directory server. |
| 91 |
- If multiple matches are found then a more explicit search_base is required so only 1 host is found. |
| 92 |
- If searching a larger Active Directory database, it is recommended to narrow the search_base for performance |
| 93 |
reasons. |
| 94 |
type: str |
| 95 |
start_tls: |
| 96 |
description: |
| 97 |
- When C(scheme=ldap), will use the StartTLS extension to encrypt traffic sent over the wire. |
| 98 |
- This requires the Active Directory to be set up with a certificate that supports StartTLS. |
| 99 |
- This is ignored when C(scheme=ldaps) as the traffic is already encrypted. |
| 100 |
type: bool |
| 101 |
default: no |
| 102 |
username: |
| 103 |
description: |
| 104 |
- Required when using C(auth=simple). |
| 105 |
- The username to authenticate with. |
| 106 |
- Recommended to use the username in the UPN format, e.g. C([email protected]). |
| 107 |
- This is required when C(auth=simple) and is not supported when C(auth=gssapi). |
| 108 |
- Call C(kinit) outside of Ansible if C(auth=gssapi) is required. |
| 109 |
type: str |
| 110 |
validate_certs: |
| 111 |
description: |
| 112 |
- When using C(scheme=ldaps) or C(start_tls=yes), this controls the certificate validation behaviour. |
| 113 |
- C(demand) will fail if no certificate or an invalid certificate is provided. |
| 114 |
- C(try) will fail for invalid certificates but will continue if no certificate is provided. |
| 115 |
- C(allow) will request and check a certificate but will continue even if it is invalid. |
| 116 |
- C(never) will not request a certificate from the server so no validation occurs. |
| 117 |
default: demand |
| 118 |
choices: |
| 119 |
- never |
| 120 |
- allow |
| 121 |
- try |
| 122 |
- demand |
| 123 |
type: str |
| 124 |
requirements: |
| 125 |
- python-ldap |
| 126 |
notes: |
| 127 |
- If a host was found but had no LAPS password attribute C(ms-Mcs-AdmPwd), the lookup will fail. |
| 128 |
- Due to the sensitive nature of the data travelling across the network, it is highly recommended to run with either |
| 129 |
C(auth=gssapi), C(scheme=ldaps), or C(start_tls=yes). |
| 130 |
- Failing to run with one of the above settings will result in the account credentials as well as the LAPS password to |
| 131 |
be sent in plaintext. |
| 132 |
- Some scenarios may not work when running on a host with an older OpenLDAP install like MacOS. It is recommended to |
| 133 |
install the latest OpenLDAP version and build python-ldap against this, see |
| 134 |
U(https://keathmilligan.net/python-ldap-and-macos) for more information. |
| 135 |
''' |
| 136 |
|
| 137 |
EXAMPLES = """ |
| 138 |
# This isn't mandatory but it is a way to call kinit from within Ansible before calling the lookup |
| 139 |
- name: call kinit to retrieve Kerberos token |
| 140 |
expect: |
| 141 |
command: kinit [email protected] |
| 142 |
responses: |
| 143 |
(?i)password: SecretPass1 |
| 144 |
no_log: true |
| 145 |
|
| 146 |
- name: Get the LAPS password using Kerberos auth, relies on kinit already being called |
| 147 |
set_fact: |
| 148 |
ansible_password: "{{ lookup('community.windows.laps_password', 'SERVER', domain='dc01.ansible.com') }}" |
| 149 |
|
| 150 |
- name: Specific the domain host using an explicit LDAP URI |
| 151 |
set_fact: |
| 152 |
ansible_password: "{{ lookup('community.windows.laps_password', 'SERVER', domain='ldap://ansible.com:389') }}" |
| 153 |
|
| 154 |
- name: Use Simple auth over LDAPS |
| 155 |
set_fact: |
| 156 |
ansible_password: "{{ lookup('community.windows.laps_password', 'server', |
| 157 |
domain='dc01.ansible.com', |
| 158 |
auth='simple', |
| 159 |
scheme='ldaps', |
| 160 |
username='[email protected]', |
| 161 |
password='SuperSecret123') }}" |
| 162 |
|
| 163 |
- name: Use Simple auth with LDAP and StartTLS |
| 164 |
set_fact: |
| 165 |
ansible_password: "{{ lookup('community.windows.laps_password', 'app01', |
| 166 |
domain='dc01.ansible.com', |
| 167 |
auth='simple', |
| 168 |
start_tls=True, |
| 169 |
username='[email protected]', |
| 170 |
password='SuperSecret123') }}" |
| 171 |
|
| 172 |
- name: Narrow down the search base to a an OU |
| 173 |
set_fact: |
| 174 |
ansible_password: "{{ lookup('community.windows.laps_password', 'sql10', |
| 175 |
domain='dc01.ansible.com', |
| 176 |
search_base='OU=Databases,DC=ansible,DC=com') }}" |
| 177 |
|
| 178 |
- name: Set certificate file to use when validating the TLS certificate |
| 179 |
set_fact: |
| 180 |
ansible_password: "{{ lookup('community.windows.laps_password', 'windows-pc', |
| 181 |
domain='dc01.ansible.com', |
| 182 |
start_tls=True, |
| 183 |
ca_cert='/usr/local/share/certs/ad.pem') }}" |
| 184 |
""" |
| 185 |
|
| 186 |
RETURN = """ |
| 187 |
_raw: |
| 188 |
description: |
| 189 |
- The LAPS password(s) for the host(s) requested. |
| 190 |
type: str |
| 191 |
""" |
| 192 |
|
| 193 |
import os |
| 194 |
import traceback |
| 195 |
|
| 196 |
from ansible.errors import AnsibleLookupError |
| 197 |
from ansible.module_utils._text import to_bytes, to_native, to_text |
| 198 |
from ansible.module_utils.basic import missing_required_lib |
| 199 |
from ansible.plugins.lookup import LookupBase |
| 200 |
|
| 201 |
LDAP_IMP_ERR = None |
| 202 |
try: |
| 203 |
import ldap |
| 204 |
import ldapurl |
| 205 |
HAS_LDAP = True |
| 206 |
except ImportError: |
| 207 |
LDAP_IMP_ERR = traceback.format_exc() |
| 208 |
HAS_LDAP = False |
| 209 |
|
| 210 |
|
| 211 |
def get_laps_password(conn, cn, search_base): |
| 212 |
search_filter = u"(&(objectClass=computer)(CN=%s))" % to_text(cn) |
| 213 |
|
| 214 |
ldap_results = conn.search_s(to_text(search_base), ldap.SCOPE_SUBTREE, search_filter, |
| 215 |
attrlist=[u"distinguishedName", u"ms-Mcs-AdmPwd"]) |
| 216 |
|
| 217 |
# Filter out non server hosts, search_s seems to return 3 extra entries |
| 218 |
# that are not computer classes, they do not have a distinguished name |
| 219 |
# set in the returned results |
| 220 |
valid_results = [attr for dn, attr in ldap_results if dn] |
| 221 |
|
| 222 |
if len(valid_results) == 0: |
| 223 |
raise AnsibleLookupError("Failed to find the server '%s' in the base '%s'" % (cn, search_base)) |
| 224 |
elif len(valid_results) > 1: |
| 225 |
found_servers = [to_native(attr['distinguishedName'][0]) for attr in valid_results] |
| 226 |
raise AnsibleLookupError("Found too many results for the server '%s' in the base '%s'. Specify a more " |
| 227 |
"explicit search base for the server required. Found servers '%s'" |
| 228 |
% (cn, search_base, "', '".join(found_servers))) |
| 229 |
|
| 230 |
password = valid_results[0].get('ms-Mcs-AdmPwd', None) |
| 231 |
if not password: |
| 232 |
distinguished_name = to_native(valid_results[0]['distinguishedName'][0]) |
| 233 |
raise AnsibleLookupError("The server '%s' did not have the LAPS attribute 'ms-Mcs-AdmPwd'" % distinguished_name) |
| 234 |
|
| 235 |
return to_native(password[0]) |
| 236 |
|
| 237 |
|
| 238 |
class LookupModule(LookupBase): |
| 239 |
|
| 240 |
def run(self, terms, variables=None, **kwargs): |
| 241 |
if not HAS_LDAP: |
| 242 |
msg = missing_required_lib("python-ldap", url="https://pypi.org/project/python-ldap/") |
| 243 |
msg += ". Import Error: %s" % LDAP_IMP_ERR |
| 244 |
raise AnsibleLookupError(msg) |
| 245 |
|
| 246 |
# Load the variables and direct args into the lookup options |
| 247 |
self.set_options(var_options=variables, direct=kwargs) |
| 248 |
domain = self.get_option('domain') |
| 249 |
port = self.get_option('port') |
| 250 |
scheme = self.get_option('scheme') |
| 251 |
start_tls = self.get_option('start_tls') |
| 252 |
validate_certs = self.get_option('validate_certs') |
| 253 |
cacert_file = self.get_option('ca_cert') |
| 254 |
search_base = self.get_option('search_base') |
| 255 |
username = self.get_option('username') |
| 256 |
password = self.get_option('password') |
| 257 |
auth = self.get_option('auth') |
| 258 |
allow_plaintext = self.get_option('allow_plaintext') |
| 259 |
|
| 260 |
# Validate and set input values |
| 261 |
# https://www.openldap.org/lists/openldap-software/200202/msg00456.html |
| 262 |
validate_certs_map = { |
| 263 |
'never': ldap.OPT_X_TLS_NEVER, |
| 264 |
'allow': ldap.OPT_X_TLS_ALLOW, |
| 265 |
'try': ldap.OPT_X_TLS_TRY, |
| 266 |
'demand': ldap.OPT_X_TLS_DEMAND, # Same as OPT_X_TLS_HARD |
| 267 |
} |
| 268 |
validate_certs_value = validate_certs_map.get(validate_certs, None) |
| 269 |
if validate_certs_value is None: |
| 270 |
valid_keys = list(validate_certs_map.keys()) |
| 271 |
valid_keys.sort() |
| 272 |
raise AnsibleLookupError("Invalid validate_certs value '%s': valid values are '%s'" |
| 273 |
% (validate_certs, "', '".join(valid_keys))) |
| 274 |
|
| 275 |
if auth not in ['gssapi', 'simple']: |
| 276 |
raise AnsibleLookupError("Invalid auth value '%s': expecting either 'gssapi', or 'simple'" % auth) |
| 277 |
elif auth == 'gssapi': |
| 278 |
if not ldap.SASL_AVAIL: |
| 279 |
raise AnsibleLookupError("Cannot use auth=gssapi when SASL is not configured with the local LDAP " |
| 280 |
"install") |
| 281 |
if username or password: |
| 282 |
raise AnsibleLookupError("Explicit credentials are not supported when auth='gssapi'. Call kinit " |
| 283 |
"outside of Ansible") |
| 284 |
elif auth == 'simple' and not (username and password): |
| 285 |
raise AnsibleLookupError("The username and password values are required when auth=simple") |
| 286 |
|
| 287 |
if ldapurl.isLDAPUrl(domain): |
| 288 |
ldap_url = ldapurl.LDAPUrl(ldapUrl=domain) |
| 289 |
else: |
| 290 |
port = port if port else 389 if scheme == 'ldap' else 636 |
| 291 |
ldap_url = ldapurl.LDAPUrl(hostport="%s:%d" % (domain, port), urlscheme=scheme) |
| 292 |
|
| 293 |
# We have encryption if using LDAPS, or StartTLS is used, or we auth with SASL/GSSAPI |
| 294 |
encrypted = ldap_url.urlscheme == 'ldaps' or start_tls or auth == 'gssapi' |
| 295 |
if not encrypted and not allow_plaintext: |
| 296 |
raise AnsibleLookupError("Current configuration will result in plaintext traffic exposing credentials. " |
| 297 |
"Set auth=gssapi, scheme=ldaps, start_tls=True, or allow_plaintext=True to " |
| 298 |
"continue") |
| 299 |
|
| 300 |
if ldap_url.urlscheme == 'ldaps' or start_tls: |
| 301 |
# We cannot use conn.set_option as OPT_X_TLS_NEWCTX (required to use the new context) is not supported on |
| 302 |
# older distros like EL7. Setting it on the ldap object works instead |
| 303 |
if not ldap.TLS_AVAIL: |
| 304 |
raise AnsibleLookupError("Cannot use TLS as the local LDAP installed has not been configured to support it") |
| 305 |
|
| 306 |
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, validate_certs_value) |
| 307 |
if cacert_file: |
| 308 |
cacert_path = os.path.expanduser(os.path.expandvars(cacert_file)) |
| 309 |
if not os.path.exists(to_bytes(cacert_path)): |
| 310 |
raise AnsibleLookupError("The cacert_file specified '%s' does not exist" % to_native(cacert_path)) |
| 311 |
|
| 312 |
try: |
| 313 |
# While this is a path, python-ldap expects a str/unicode and not bytes |
| 314 |
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, to_text(cacert_path)) |
| 315 |
except ValueError: |
| 316 |
# https://keathmilligan.net/python-ldap-and-macos/ |
| 317 |
raise AnsibleLookupError("Failed to set path to cacert file, this is a known issue with older " |
| 318 |
"OpenLDAP libraries on the host. Update OpenLDAP and reinstall " |
| 319 |
"python-ldap to continue") |
| 320 |
|
| 321 |
conn_url = ldap_url.initializeUrl() |
| 322 |
conn = ldap.initialize(conn_url, bytes_mode=False) |
| 323 |
conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3) |
| 324 |
conn.set_option(ldap.OPT_REFERRALS, 0) # Allow us to search from the base |
| 325 |
|
| 326 |
# Make sure we run StartTLS before doing the bind to protect the credentials |
| 327 |
if start_tls: |
| 328 |
try: |
| 329 |
conn.start_tls_s() |
| 330 |
except ldap.LDAPError as err: |
| 331 |
raise AnsibleLookupError("Failed to send StartTLS to LDAP host '%s': %s" |
| 332 |
% (conn_url, to_native(err))) |
| 333 |
|
| 334 |
if auth == 'simple': |
| 335 |
try: |
| 336 |
conn.bind_s(to_text(username), to_text(password)) |
| 337 |
except ldap.LDAPError as err: |
| 338 |
raise AnsibleLookupError("Failed to simple bind against LDAP host '%s': %s" |
| 339 |
% (conn_url, to_native(err))) |
| 340 |
else: |
| 341 |
try: |
| 342 |
conn.sasl_gssapi_bind_s() |
| 343 |
except ldap.AUTH_UNKNOWN as err: |
| 344 |
# The SASL GSSAPI binding is not installed, e.g. cyrus-sasl-gssapi. Give a better error message than |
| 345 |
# what python-ldap provides |
| 346 |
raise AnsibleLookupError("Failed to do a sasl bind against LDAP host '%s', the GSSAPI mech is not " |
| 347 |
"installed: %s" % (conn_url, to_native(err))) |
| 348 |
except ldap.LDAPError as err: |
| 349 |
raise AnsibleLookupError("Failed to do a sasl bind against LDAP host '%s': %s" |
| 350 |
% (conn_url, to_native(err))) |
| 351 |
|
| 352 |
try: |
| 353 |
if not search_base: |
| 354 |
root_dse = conn.read_rootdse_s() |
| 355 |
search_base = root_dse['defaultNamingContext'][0] |
| 356 |
|
| 357 |
ret = [] |
| 358 |
# TODO: change method to search for all servers in 1 request instead of multiple requests |
| 359 |
for server in terms: |
| 360 |
ret.append(get_laps_password(conn, server, search_base)) |
| 361 |
finally: |
| 362 |
conn.unbind_s() |
| 363 |
|
| 364 |
return ret |