Debian Codegraph @

ansible_collections/community/general/plugins/modules/krb_ticket.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2024 Alexander Bakanovskii <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: krb_ticket
10 short_description: Kerberos utils for managing tickets
11 version_added: 10.0.0
12 description:
13 - Manage Kerberos tickets with C(kinit), C(klist) and C(kdestroy) base utilities.
14 - See U(https://web.mit.edu/kerberos/krb5-1.12/doc/user/user_commands/index.html) for reference.
15 author: "Alexander Bakanovskii (@abakanovskii)"
16 attributes:
17 check_mode:
18 support: full
19 diff_mode:
20 support: none
21 options:
22 password:
23 description:
24 - Principal password.
25 - It is required to specify O(password) or O(keytab_path).
26 type: str
27 principal:
28 description:
29 - The principal name.
30 - If not set, the user running this module is used.
31 type: str
32 state:
33 description:
34 - The state of the Kerberos ticket.
35 - V(present) is equivalent of C(kinit) command.
36 - V(absent) is equivalent of C(kdestroy) command.
37 type: str
38 default: present
39 choices: ["present", "absent"]
40 kdestroy_all:
41 description:
42 - When O(state=absent) destroys all credential caches in collection.
43 - Equivalent of running C(kdestroy -A).
44 type: bool
45 cache_name:
46 description:
47 - Use O(cache_name) as the ticket cache name and location.
48 - If this option is not used, the default cache name and location are used.
49 - The default credentials cache may vary between systems.
50 - If not set the value of E(KRB5CCNAME) environment variable is used instead, its value is used to name the default
51 ticket cache.
52 type: str
53 lifetime:
54 description:
55 - Requests a ticket with the lifetime, if the O(lifetime) is not specified, the default ticket lifetime is used.
56 - Specifying a ticket lifetime longer than the maximum ticket lifetime (configured by each site) does not override the
57 configured maximum ticket lifetime.
58 - 'The value for O(lifetime) must be followed by one of the following suffixes: V(s) - seconds, V(m) - minutes, V(h)
59 - hours, V(d) - days.'
60 - You cannot mix units; a value of V(3h30m) results in an error.
61 - See U(https://web.mit.edu/kerberos/krb5-1.12/doc/basic/date_format.html) for reference.
62 type: str
63 start_time:
64 description:
65 - Requests a postdated ticket.
66 - Postdated tickets are issued with the invalid flag set, and need to be resubmitted to the KDC for validation before
67 use.
68 - O(start_time) specifies the duration of the delay before the ticket can become valid.
69 - You can use absolute time formats, for example V(July 27, 2012 at 20:30) you would neet to set O(start_time=20120727203000).
70 - You can also use time duration format similar to O(lifetime) or O(renewable).
71 - See U(https://web.mit.edu/kerberos/krb5-1.12/doc/basic/date_format.html) for reference.
72 type: str
73 renewable:
74 description:
75 - Requests renewable tickets, with a total lifetime equal to O(renewable).
76 - 'The value for O(renewable) must be followed by one of the following delimiters: V(s) - seconds, V(m) - minutes, V(h)
77 - hours, V(d) - days.'
78 - You cannot mix units; a value of V(3h30m) results in an error.
79 - See U(https://web.mit.edu/kerberos/krb5-1.12/doc/basic/date_format.html) for reference.
80 type: str
81 forwardable:
82 description:
83 - Request forwardable or non-forwardable tickets.
84 type: bool
85 proxiable:
86 description:
87 - Request proxiable or non-proxiable tickets.
88 type: bool
89 address_restricted:
90 description:
91 - Request tickets restricted to the host's local address or non-restricted.
92 type: bool
93 anonymous:
94 description:
95 - Requests anonymous processing.
96 type: bool
97 canonicalization:
98 description:
99 - Requests canonicalization of the principal name, and allows the KDC to reply with a different client principal from
100 the one requested.
101 type: bool
102 enterprise:
103 description:
104 - Treats the principal name as an enterprise name (implies the O(canonicalization) option).
105 type: bool
106 renewal:
107 description:
108 - Requests renewal of the ticket-granting ticket.
109 - Note that an expired ticket cannot be renewed, even if the ticket is still within its renewable life.
110 type: bool
111 validate:
112 description:
113 - Requests that the ticket-granting ticket in the cache (with the invalid flag set) be passed to the KDC for validation.
114 - If the ticket is within its requested time range, the cache is replaced with the validated ticket.
115 type: bool
116 keytab:
117 description:
118 - Requests a ticket, obtained from a key in the local host's keytab.
119 - If O(keytab_path) is not specified it tries to use default client keytab path (C(-i) option).
120 type: bool
121 keytab_path:
122 description:
123 - Use when O(keytab=true) to specify path to a keytab file.
124 - It is required to specify O(password) or O(keytab_path).
125 type: path
126 requirements:
127 - krb5-user and krb5-config packages
128 extends_documentation_fragment:
129 - community.general._attributes
130 """
131
132 EXAMPLES = r"""
133 - name: Get Kerberos ticket using default principal
134 community.general.krb_ticket:
135 password: some_password
136
137 - name: Get Kerberos ticket using keytab
138 community.general.krb_ticket:
139 keytab: true
140 keytab_path: /etc/ipa/file.keytab
141
142 - name: Get Kerberos ticket with a lifetime of 7 days
143 community.general.krb_ticket:
144 password: some_password
145 lifetime: 7d
146
147 - name: Get Kerberos ticket with a starting time of July 2, 2024, 1:35:30 p.m.
148 community.general.krb_ticket:
149 password: some_password
150 start_time: "240702133530"
151
152 - name: Get Kerberos ticket using principal name
153 community.general.krb_ticket:
154 password: some_password
155 principal: admin
156
157 - name: Get Kerberos ticket using principal with realm
158 community.general.krb_ticket:
159 password: some_password
160 principal: [email protected]
161
162 - name: Check for existence by ticket cache
163 community.general.krb_ticket:
164 cache_name: KEYRING:persistent:0:0
165
166 - name: Make sure default ticket is destroyed
167 community.general.krb_ticket:
168 state: absent
169
170 - name: Make sure specific ticket destroyed by principal
171 community.general.krb_ticket:
172 state: absent
173 principal: [email protected]
174
175 - name: Make sure specific ticket destroyed by cache_name
176 community.general.krb_ticket:
177 state: absent
178 cache_name: KEYRING:persistent:0:0
179
180 - name: Make sure all tickets are destroyed
181 community.general.krb_ticket:
182 state: absent
183 kdestroy_all: true
184 """
185
186 from ansible.module_utils.basic import AnsibleModule, env_fallback
187
188 from ansible_collections.community.general.plugins.module_utils._cmd_runner import CmdRunner, cmd_runner_fmt
189
190
191 class IPAKeytab:
192 def __init__(self, module, **kwargs):
193 self.module = module
194 self.password = kwargs["password"]
195 self.principal = kwargs["principal"]
196 self.state = kwargs["state"]
197 self.kdestroy_all = kwargs["kdestroy_all"]
198 self.cache_name = kwargs["cache_name"]
199 self.start_time = kwargs["start_time"]
200 self.renewable = kwargs["renewable"]
201 self.forwardable = kwargs["forwardable"]
202 self.proxiable = kwargs["proxiable"]
203 self.address_restricted = kwargs["address_restricted"]
204 self.canonicalization = kwargs["canonicalization"]
205 self.enterprise = kwargs["enterprise"]
206 self.renewal = kwargs["renewal"]
207 self.validate = kwargs["validate"]
208 self.keytab = kwargs["keytab"]
209 self.keytab_path = kwargs["keytab_path"]
210
211 self.kinit = CmdRunner(
212 module,
213 command="kinit",
214 arg_formats=dict(
215 lifetime=cmd_runner_fmt.as_opt_val("-l"),
216 start_time=cmd_runner_fmt.as_opt_val("-s"),
217 renewable=cmd_runner_fmt.as_opt_val("-r"),
218 forwardable=cmd_runner_fmt.as_bool("-f", "-F", ignore_none=True),
219 proxiable=cmd_runner_fmt.as_bool("-p", "-P", ignore_none=True),
220 address_restricted=cmd_runner_fmt.as_bool("-a", "-A", ignore_none=True),
221 anonymous=cmd_runner_fmt.as_bool("-n"),
222 canonicalization=cmd_runner_fmt.as_bool("-C"),
223 enterprise=cmd_runner_fmt.as_bool("-E"),
224 renewal=cmd_runner_fmt.as_bool("-R"),
225 validate=cmd_runner_fmt.as_bool("-v"),
226 keytab=cmd_runner_fmt.as_bool("-k"),
227 keytab_path=cmd_runner_fmt.as_func(lambda v: ["-t", v] if v else ["-i"]),
228 cache_name=cmd_runner_fmt.as_opt_val("-c"),
229 principal=cmd_runner_fmt.as_list(),
230 ),
231 )
232
233 self.kdestroy = CmdRunner(
234 module,
235 command="kdestroy",
236 arg_formats=dict(
237 kdestroy_all=cmd_runner_fmt.as_bool("-A"),
238 cache_name=cmd_runner_fmt.as_opt_val("-c"),
239 principal=cmd_runner_fmt.as_opt_val("-p"),
240 ),
241 )
242
243 self.klist = CmdRunner(
244 module,
245 command="klist",
246 arg_formats=dict(
247 show_list=cmd_runner_fmt.as_bool("-l"),
248 ),
249 )
250
251 def exec_kinit(self):
252 params = dict(self.module.params)
253 with self.kinit(
254 "lifetime start_time renewable forwardable proxiable address_restricted anonymous "
255 "canonicalization enterprise renewal validate keytab keytab_path cache_name principal",
256 check_rc=True,
257 data=self.password,
258 ) as ctx:
259 rc, out, err = ctx.run(**params)
260 return out
261
262 def exec_kdestroy(self):
263 params = dict(self.module.params)
264 with self.kdestroy("kdestroy_all cache_name principal", check_rc=True) as ctx:
265 rc, out, err = ctx.run(**params)
266 return out
267
268 def exec_klist(self, show_list):
269 # Use chech_rc = False because
270 # If no tickets present, klist command will always return rc = 1
271 params = dict(show_list=show_list)
272 with self.klist("show_list", check_rc=False) as ctx:
273 rc, out, err = ctx.run(**params)
274 return rc, out, err
275
276 def check_ticket_present(self):
277 ticket_present = True
278 show_list = False
279
280 if not self.principal and not self.cache_name:
281 rc, out, err = self.exec_klist(show_list)
282 if rc != 0:
283 ticket_present = False
284 else:
285 show_list = True
286 rc, out, err = self.exec_klist(show_list)
287 if self.principal and self.principal not in str(out):
288 ticket_present = False
289 if self.cache_name and self.cache_name not in str(out):
290 ticket_present = False
291
292 return ticket_present
293
294
295 def main():
296 arg_spec = dict(
297 principal=dict(type="str"),
298 password=dict(type="str", no_log=True),
299 state=dict(default="present", choices=["present", "absent"]),
300 kdestroy_all=dict(type="bool"),
301 cache_name=dict(type="str", fallback=(env_fallback, ["KRB5CCNAME"])),
302 lifetime=dict(type="str"),
303 start_time=dict(type="str"),
304 renewable=dict(type="str"),
305 forwardable=dict(type="bool"),
306 proxiable=dict(type="bool"),
307 address_restricted=dict(type="bool"),
308 anonymous=dict(type="bool"),
309 canonicalization=dict(type="bool"),
310 enterprise=dict(type="bool"),
311 renewal=dict(type="bool"),
312 validate=dict(type="bool"),
313 keytab=dict(type="bool"),
314 keytab_path=dict(type="path"),
315 )
316 module = AnsibleModule(
317 argument_spec=arg_spec,
318 supports_check_mode=True,
319 required_by={"keytab_path": "keytab"},
320 required_if=[
321 ("state", "present", ("password", "keytab_path"), True),
322 ],
323 )
324
325 state = module.params["state"]
326 kdestroy_all = module.params["kdestroy_all"]
327
328 keytab = IPAKeytab(
329 module,
330 state=state,
331 kdestroy_all=kdestroy_all,
332 principal=module.params["principal"],
333 password=module.params["password"],
334 cache_name=module.params["cache_name"],
335 lifetime=module.params["lifetime"],
336 start_time=module.params["start_time"],
337 renewable=module.params["renewable"],
338 forwardable=module.params["forwardable"],
339 proxiable=module.params["proxiable"],
340 address_restricted=module.params["address_restricted"],
341 anonymous=module.params["anonymous"],
342 canonicalization=module.params["canonicalization"],
343 enterprise=module.params["enterprise"],
344 renewal=module.params["renewal"],
345 validate=module.params["validate"],
346 keytab=module.params["keytab"],
347 keytab_path=module.params["keytab_path"],
348 )
349
350 if module.params["keytab_path"] is not None and module.params["keytab"] is not True:
351 module.fail_json(msg="If keytab_path is specified then keytab parameter must be True")
352
353 changed = False
354 if state == "present":
355 if not keytab.check_ticket_present():
356 changed = True
357 if not module.check_mode:
358 keytab.exec_kinit()
359
360 if state == "absent":
361 if kdestroy_all:
362 changed = True
363 if not module.check_mode:
364 keytab.exec_kdestroy()
365 elif keytab.check_ticket_present():
366 changed = True
367 if not module.check_mode:
368 keytab.exec_kdestroy()
369
370 module.exit_json(changed=changed)
371
372
373 if __name__ == "__main__":
374 main()