Debian Codegraph @

test/integration/targets/prepare_http_tests/library/httptester_kinit.py

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2020, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 ---
9 module: httptester_kinit
10 short_description: Get Kerberos ticket
11 description: Get Kerberos ticket using kinit non-interactively.
12 options:
13 username:
14 description: The username to get the ticket for.
15 required: true
16 type: str
17 password:
18 description: The password for I(username).
19 required; true
20 type: str
21 author:
22 - Ansible Project
23 """
24
25 EXAMPLES = r"""
26 #
27 """
28
29 RETURN = r"""
30 #
31 """
32
33 import contextlib
34 import os
35 import subprocess
36
37 from ansible.module_utils.basic import AnsibleModule
38 from ansible.module_utils.common.text.converters import to_bytes, to_text
39
40 try:
41 import configparser
42 except ImportError:
43 import ConfigParser as configparser
44
45
46 @contextlib.contextmanager
47 def env_path(name, value, default_value):
48 """ Adds a value to a PATH-like env var and preserve the existing value if present. """
49 orig_value = os.environ.get(name, None)
50 os.environ[name] = '%s:%s' % (value, orig_value or default_value)
51 try:
52 yield
53
54 finally:
55 if orig_value:
56 os.environ[name] = orig_value
57
58 else:
59 del os.environ[name]
60
61
62 @contextlib.contextmanager
63 def krb5_conf(module, config):
64 """ Runs with a custom krb5.conf file that extends the existing config if present. """
65 if config:
66 ini_config = configparser.ConfigParser()
67 for section, entries in config.items():
68 ini_config.add_section(section)
69 for key, value in entries.items():
70 ini_config.set(section, key, value)
71
72 config_path = os.path.join(module.tmpdir, 'krb5.conf')
73 with open(config_path, mode='wt') as config_fd:
74 ini_config.write(config_fd)
75
76 with env_path('KRB5_CONFIG', config_path, '/etc/krb5.conf'):
77 yield
78
79 else:
80 yield
81
82
83 def main():
84 module_args = dict(
85 username=dict(type='str', required=True),
86 password=dict(type='str', required=True, no_log=True),
87 )
88 module = AnsibleModule(
89 argument_spec=module_args,
90 required_together=[('username', 'password')],
91 )
92
93 # Heimdal has a few quirks that we want to paper over in this module
94 # 1. KRB5_TRACE does not work in any released version (<=7.7), we need to use a custom krb5.config to enable it
95 # 2. When reading the password it reads from the pty not stdin by default causing an issue with subprocess. We
96 # can control that behaviour with '--password-file=STDIN'
97 # Also need to set the custom path to krb5-config and kinit as FreeBSD relies on the newer Heimdal version in the
98 # port package.
99 sysname = os.uname()[0]
100 prefix = '/usr/local/bin/' if sysname == 'FreeBSD' else ''
101 is_heimdal = sysname in ['Darwin', 'FreeBSD']
102
103 # Debugging purposes, get the Kerberos version. On platforms like OpenSUSE this may not be on the PATH.
104 try:
105 process = subprocess.Popen(['%skrb5-config' % prefix, '--version'], stdout=subprocess.PIPE)
106 stdout, stderr = process.communicate()
107 version = to_text(stdout)
108 except FileNotFoundError:
109 version = 'Unknown (no krb5-config)'
110
111 kinit_args = ['%skinit' % prefix]
112 config = {}
113 if is_heimdal:
114 kinit_args.append('--password-file=STDIN')
115 config['logging'] = {'krb5': 'FILE:/dev/stdout'}
116 kinit_args.append(to_text(module.params['username'], errors='surrogate_or_strict'))
117
118 with krb5_conf(module, config):
119 # Weirdly setting KRB5_CONFIG in the modules environment block does not work unless we pass it in explicitly.
120 # Take a copy of the existing environment to make sure the process has the same env vars as ours. Also set
121 # KRB5_TRACE to output and debug logs helping to identify problems when calling kinit with MIT.
122 kinit_env = os.environ.copy()
123 kinit_env['KRB5_TRACE'] = '/dev/stdout'
124
125 process = subprocess.Popen(kinit_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
126 env=kinit_env)
127 stdout, stderr = process.communicate(to_bytes(module.params['password'], errors='surrogate_or_strict') + b'\n')
128 rc = process.returncode
129
130 module.exit_json(changed=True, stdout=to_text(stdout), stderr=to_text(stderr), rc=rc, version=version)
131
132
133 if __name__ == '__main__':
134 main()