Blame roles/ipaclient/library/ipaclient_api.py

Packit 8cb997
# -*- coding: utf-8 -*-
Packit 8cb997
Packit 8cb997
# Authors:
Packit 8cb997
#   Thomas Woerner <twoerner@redhat.com>
Packit 8cb997
#
Packit 8cb997
# Based on ipa-client-install code
Packit 8cb997
#
Packit 8cb997
# Copyright (C) 2017  Red Hat
Packit 8cb997
# see file 'COPYING' for use and warranty information
Packit 8cb997
#
Packit 8cb997
# This program is free software; you can redistribute it and/or modify
Packit 8cb997
# it under the terms of the GNU General Public License as published by
Packit 8cb997
# the Free Software Foundation, either version 3 of the License, or
Packit 8cb997
# (at your option) any later version.
Packit 8cb997
#
Packit 8cb997
# This program is distributed in the hope that it will be useful,
Packit 8cb997
# but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 8cb997
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 8cb997
# GNU General Public License for more details.
Packit 8cb997
#
Packit 8cb997
# You should have received a copy of the GNU General Public License
Packit 8cb997
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
Packit 8cb997
Packit 8cb997
ANSIBLE_METADATA = {'metadata_version': '1.0',
Packit 8cb997
                    'status': ['preview'],
Packit 8cb997
                    'supported_by': 'community'}
Packit 8cb997
Packit 8cb997
DOCUMENTATION = '''
Packit 8cb997
---
Packit 8cb997
module: ipaclient_api
Packit 8cb997
short description:
Packit 8cb997
  Create temporary NSS database, call IPA API for remaining enrollment parts
Packit 8cb997
description:
Packit 8cb997
  Create temporary NSS database, call IPA API for remaining enrollment parts
Packit 8cb997
options:
Packit 8cb997
  servers:
Packit 8cb997
    description: Fully qualified name of IPA servers to enroll to
Packit 8cb997
    required: no
Packit 8cb997
  realm:
Packit 8cb997
    description: Kerberos realm name of the IPA deployment
Packit 8cb997
    required: no
Packit 8cb997
  hostname:
Packit 8cb997
    description: Fully qualified name of this host
Packit 8cb997
    required: no
Packit 8cb997
  debug:
Packit 8cb997
    description: Turn on extra debugging
Packit 8cb997
    required: yes
Packit 8cb997
author:
Packit 8cb997
    - Thomas Woerner
Packit 8cb997
'''
Packit 8cb997
Packit 8cb997
EXAMPLES = '''
Packit 8cb997
- name: IPA API calls for remaining enrollment parts
Packit 8cb997
  ipaclient_api:
Packit 8cb997
    servers: ["server1.example.com","server2.example.com"]
Packit 8cb997
    domain: example.com
Packit 8cb997
    hostname: client1.example.com
Packit 8cb997
  register: result_ipaclient_api
Packit 8cb997
'''
Packit 8cb997
Packit 8cb997
RETURN = '''
Packit 8cb997
ca_enabled:
Packit 8cb997
  description: Wheter the Certificate Authority is enabled or not.
Packit 8cb997
  returned: always
Packit 8cb997
  type: bool
Packit 8cb997
subject_base:
Packit 8cb997
  description: The subject base, needed for certmonger
Packit 8cb997
  returned: always
Packit 8cb997
  type: string
Packit 8cb997
  sample: O=EXAMPLE.COM
Packit 8cb997
'''
Packit 8cb997
Packit 8cb997
import os
Packit 8cb997
import inspect
Packit 8cb997
Packit 8cb997
from ansible.module_utils.basic import AnsibleModule
Packit 8cb997
from ansible.module_utils.ansible_ipa_client import (
Packit Service 0f71a7
    setup_logging,
Packit 8cb997
    paths, x509, NUM_VERSION, serialization, certdb, api,
Packit 8cb997
    delete_persistent_client_session_data, write_tmp_file,
Packit 8cb997
    ipa_generate_password, CalledProcessError, errors, disable_ra, DN,
Packit 8cb997
    CLIENT_INSTALL_ERROR, logger
Packit 8cb997
)
Packit 8cb997
Packit 8cb997
Packit 8cb997
def main():
Packit 8cb997
    module = AnsibleModule(
Packit 8cb997
        argument_spec=dict(
Packit 8cb997
            servers=dict(required=True, type='list'),
Packit 8cb997
            realm=dict(required=True),
Packit 8cb997
            hostname=dict(required=True),
Packit 8cb997
            debug=dict(required=False, type='bool', default="false"),
Packit 8cb997
        ),
Packit 8cb997
        supports_check_mode=True,
Packit 8cb997
    )
Packit 8cb997
Packit 8cb997
    module._ansible_debug = True
Packit Service 0f71a7
    setup_logging()
Packit Service 0f71a7
Packit 8cb997
    realm = module.params.get('realm')
Packit 8cb997
    hostname = module.params.get('hostname')
Packit 8cb997
    debug = module.params.get('debug')
Packit 8cb997
Packit 8cb997
    host_principal = 'host/%s@%s' % (hostname, realm)
Packit 8cb997
    os.environ['KRB5CCNAME'] = paths.IPA_DNS_CCACHE
Packit 8cb997
Packit 8cb997
    ca_certs = x509.load_certificate_list_from_file(paths.IPA_CA_CRT)
Packit 8cb997
    if 40500 <= NUM_VERSION < 40590:
Packit 8cb997
        ca_certs = [cert.public_bytes(serialization.Encoding.DER)
Packit 8cb997
                    for cert in ca_certs]
Packit 8cb997
    elif NUM_VERSION < 40500:
Packit 8cb997
        ca_certs = [cert.der_data for cert in ca_certs]
Packit 8cb997
Packit 8cb997
    with certdb.NSSDatabase() as tmp_db:
Packit 8cb997
        api.bootstrap(context='cli_installer',
Packit 8cb997
                      confdir=paths.ETC_IPA,
Packit 8cb997
                      debug=debug,
Packit 8cb997
                      delegate=False,
Packit 8cb997
                      nss_dir=tmp_db.secdir)
Packit 8cb997
Packit 8cb997
        if 'config_loaded' not in api.env:
Packit 8cb997
            module.fail_json(msg="Failed to initialize IPA API.")
Packit 8cb997
Packit 8cb997
        # Clear out any current session keyring information
Packit 8cb997
        try:
Packit 8cb997
            delete_persistent_client_session_data(host_principal)
Packit 8cb997
        except ValueError:
Packit 8cb997
            pass
Packit 8cb997
Packit 8cb997
        # Add CA certs to a temporary NSS database
Packit 8cb997
        try:
Packit 8cb997
            argspec = inspect.getargspec(tmp_db.create_db)
Packit 8cb997
            if "password_filename" not in argspec.args:
Packit 8cb997
                tmp_db.create_db()
Packit 8cb997
            else:
Packit 8cb997
                pwd_file = write_tmp_file(ipa_generate_password())
Packit 8cb997
                tmp_db.create_db(pwd_file.name)
Packit 8cb997
            for i, cert in enumerate(ca_certs):
Packit 8cb997
                if hasattr(certdb, "EXTERNAL_CA_TRUST_FLAGS"):
Packit 8cb997
                    tmp_db.add_cert(cert,
Packit 8cb997
                                    'CA certificate %d' % (i + 1),
Packit 8cb997
                                    certdb.EXTERNAL_CA_TRUST_FLAGS)
Packit 8cb997
                else:
Packit 8cb997
                    tmp_db.add_cert(cert, 'CA certificate %d' % (i + 1),
Packit 8cb997
                                    'C,,')
Packit 8cb997
        except CalledProcessError:
Packit 8cb997
            module.fail_json(msg="Failed to add CA to temporary NSS database.")
Packit 8cb997
Packit 8cb997
        api.finalize()
Packit 8cb997
Packit 8cb997
        # Now, let's try to connect to the server's RPC interface
Packit 8cb997
        connected = False
Packit 8cb997
        try:
Packit 8cb997
            api.Backend.rpcclient.connect()
Packit 8cb997
            connected = True
Packit 8cb997
            module.debug("Try RPC connection")
Packit 8cb997
            api.Backend.rpcclient.forward('ping')
Packit 8cb997
        except errors.KerberosError as e:
Packit 8cb997
            if connected:
Packit 8cb997
                api.Backend.rpcclient.disconnect()
Packit 8cb997
            module.log(
Packit 8cb997
                "Cannot connect to the server due to Kerberos error: %s. "
Packit 8cb997
                "Trying with delegate=True" % e)
Packit 8cb997
            try:
Packit 8cb997
                api.Backend.rpcclient.connect(delegate=True)
Packit 8cb997
                module.debug("Try RPC connection")
Packit 8cb997
                api.Backend.rpcclient.forward('ping')
Packit 8cb997
Packit 8cb997
                module.log("Connection with delegate=True successful")
Packit 8cb997
Packit 8cb997
                # The remote server is not capable of Kerberos S4U2Proxy
Packit 8cb997
                # delegation. This features is implemented in IPA server
Packit 8cb997
                # version 2.2 and higher
Packit 8cb997
                module.warn(
Packit 8cb997
                    "Target IPA server has a lower version than the enrolled "
Packit 8cb997
                    "client")
Packit 8cb997
                module.warn(
Packit 8cb997
                    "Some capabilities including the ipa command capability "
Packit 8cb997
                    "may not be available")
Packit 8cb997
            except errors.PublicError as e2:
Packit 8cb997
                module.fail_json(
Packit 8cb997
                    msg="Cannot connect to the IPA server RPC interface: "
Packit 8cb997
                    "%s" % e2)
Packit 8cb997
        except errors.PublicError as e:
Packit 8cb997
            module.fail_json(
Packit 8cb997
                msg="Cannot connect to the server due to generic error: "
Packit 8cb997
                "%s" % e)
Packit 8cb997
    # Use the RPC directly so older servers are supported
Packit 8cb997
    try:
Packit 8cb997
        result = api.Backend.rpcclient.forward(
Packit 8cb997
            'ca_is_enabled',
Packit 8cb997
            version=u'2.107',
Packit 8cb997
        )
Packit 8cb997
        ca_enabled = result['result']
Packit 8cb997
    except (errors.CommandError, errors.NetworkError):
Packit 8cb997
        result = api.Backend.rpcclient.forward(
Packit 8cb997
            'env',
Packit 8cb997
            server=True,
Packit 8cb997
            version=u'2.0',
Packit 8cb997
        )
Packit 8cb997
        ca_enabled = result['result']['enable_ra']
Packit 8cb997
    if not ca_enabled:
Packit 8cb997
        disable_ra()
Packit 8cb997
Packit 8cb997
    # Get subject base from ipa server
Packit 8cb997
    try:
Packit 8cb997
        config = api.Command['config_show']()['result']
Packit 8cb997
        subject_base = str(DN(config['ipacertificatesubjectbase'][0]))
Packit 8cb997
    except errors.PublicError:
Packit 8cb997
        try:
Packit 8cb997
            config = api.Backend.rpcclient.forward(
Packit 8cb997
                'config_show',
Packit 8cb997
                raw=True,  # so that servroles are not queried
Packit 8cb997
                version=u'2.0'
Packit 8cb997
            )['result']
Packit 8cb997
        except Exception as e:
Packit 8cb997
            logger.debug("config_show failed %s", e, exc_info=True)
Packit 8cb997
            module.fail_json(
Packit 8cb997
                "Failed to retrieve CA certificate subject base: {}".format(e),
Packit 8cb997
                rval=CLIENT_INSTALL_ERROR)
Packit 8cb997
        else:
Packit 8cb997
            subject_base = str(DN(config['ipacertificatesubjectbase'][0]))
Packit 8cb997
Packit 8cb997
    module.exit_json(changed=True,
Packit 8cb997
                     ca_enabled=ca_enabled,
Packit 8cb997
                     subject_base=subject_base)
Packit 8cb997
Packit 8cb997
Packit 8cb997
if __name__ == '__main__':
Packit 8cb997
    main()