Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Kenneth D. Evensen <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: pamd
11 author:
12 - Kenneth D. Evensen (@kevensen)
13 short_description: Manage PAM Modules
14 description:
15 - Edit PAM service's type, control, module path and module arguments.
16 - In order for a PAM rule to be modified, the type, control and module_path must match an existing rule. See man(5) pam.d
17 for details.
18 notes:
19 - This module does not handle authselect profiles.
20 extends_documentation_fragment:
21 - community.general._attributes
22 attributes:
23 check_mode:
24 support: full
25 diff_mode:
26 support: none
27 options:
28 name:
29 description:
30 - The name generally refers to the PAM service file to change, for example system-auth.
31 type: str
32 required: true
33 type:
34 description:
35 - The type of the PAM rule being modified.
36 - The O(type), O(control), and O(module_path) options all must match a rule to be modified.
37 type: str
38 required: true
39 choices: [account, -account, auth, -auth, password, -password, session, -session]
40 control:
41 description:
42 - The control of the PAM rule being modified.
43 - This may be a complicated control with brackets. If this is the case, be sure to put "[bracketed controls]" in quotes.
44 - The O(type), O(control), and O(module_path) options all must match a rule to be modified.
45 type: str
46 required: true
47 module_path:
48 description:
49 - The module path of the PAM rule being modified.
50 - The O(type), O(control), and O(module_path) options all must match a rule to be modified.
51 type: str
52 required: true
53 new_type:
54 description:
55 - The new type to assign to the new rule.
56 type: str
57 choices: [account, -account, auth, -auth, password, -password, session, -session]
58 new_control:
59 description:
60 - The new control to assign to the new rule.
61 type: str
62 new_module_path:
63 description:
64 - The new module path to be assigned to the new rule.
65 type: str
66 module_arguments:
67 description:
68 - When O(state=updated), the O(module_arguments) replace existing module_arguments.
69 - When O(state=args_absent) args matching those listed in O(module_arguments) are removed.
70 - When O(state=args_present) any args listed in O(module_arguments) are added if missing from the existing rule.
71 - Furthermore, if the module argument takes a value denoted by C(=), the value changes to that specified in module_arguments.
72 type: list
73 elements: str
74 state:
75 description:
76 - The default of V(updated) modifies an existing rule if type, control and module_path all match an existing rule.
77 - With V(before), the new rule is inserted before a rule matching type, control and module_path.
78 - Similarly, with V(after), the new rule is inserted after an existing rulematching type, control and module_path.
79 - With either V(before) or V(after) O(new_type), O(new_control), and O(new_module_path) must all be specified.
80 - If state is V(args_absent) or V(args_present), O(new_type), O(new_control), and O(new_module_path) are ignored.
81 - State V(absent) removes the rule.
82 type: str
83 choices: [absent, before, after, args_absent, args_present, updated]
84 default: updated
85 path:
86 description:
87 - This is the path to the PAM service files.
88 type: path
89 default: /etc/pam.d
90 backup:
91 description:
92 - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered
93 it incorrectly.
94 type: bool
95 default: false
96 """
97
98 EXAMPLES = r"""
99 - name: Update pamd rule's control in /etc/pam.d/system-auth
100 community.general.pamd:
101 name: system-auth
102 type: auth
103 control: required
104 module_path: pam_faillock.so
105 new_control: sufficient
106
107 - name: Update pamd rule's complex control in /etc/pam.d/system-auth
108 community.general.pamd:
109 name: system-auth
110 type: session
111 control: '[success=1 default=ignore]'
112 module_path: pam_succeed_if.so
113 new_control: '[success=2 default=ignore]'
114
115 - name: Insert a new rule before an existing rule
116 community.general.pamd:
117 name: system-auth
118 type: auth
119 control: required
120 module_path: pam_faillock.so
121 new_type: auth
122 new_control: sufficient
123 new_module_path: pam_faillock.so
124 state: before
125
126 - name: Insert a new rule pam_wheel.so with argument 'use_uid' after an existing rule pam_rootok.so
127 community.general.pamd:
128 name: su
129 type: auth
130 control: sufficient
131 module_path: pam_rootok.so
132 new_type: auth
133 new_control: required
134 new_module_path: pam_wheel.so
135 module_arguments: 'use_uid'
136 state: after
137
138 - name: Remove module arguments from an existing rule
139 community.general.pamd:
140 name: system-auth
141 type: auth
142 control: required
143 module_path: pam_faillock.so
144 module_arguments: ''
145 state: updated
146
147 - name: Replace all module arguments in an existing rule
148 community.general.pamd:
149 name: system-auth
150 type: auth
151 control: required
152 module_path: pam_faillock.so
153 module_arguments: 'preauth silent deny=3 unlock_time=604800 fail_interval=900'
154 state: updated
155
156 - name: Remove specific arguments from a rule
157 community.general.pamd:
158 name: system-auth
159 type: session
160 control: '[success=1 default=ignore]'
161 module_path: pam_succeed_if.so
162 module_arguments: crond,quiet
163 state: args_absent
164
165 - name: Ensure specific arguments are present in a rule
166 community.general.pamd:
167 name: system-auth
168 type: session
169 control: '[success=1 default=ignore]'
170 module_path: pam_succeed_if.so
171 module_arguments: crond,quiet
172 state: args_present
173
174 - name: Ensure specific arguments are present in a rule (alternative)
175 community.general.pamd:
176 name: system-auth
177 type: session
178 control: '[success=1 default=ignore]'
179 module_path: pam_succeed_if.so
180 module_arguments:
181 - crond
182 - quiet
183 state: args_present
184
185 - name: Module arguments requiring commas must be listed as a Yaml list
186 community.general.pamd:
187 name: special-module
188 type: account
189 control: required
190 module_path: pam_access.so
191 module_arguments:
192 - listsep=,
193 state: args_present
194
195 - name: Update specific argument value in a rule
196 community.general.pamd:
197 name: system-auth
198 type: auth
199 control: required
200 module_path: pam_faillock.so
201 module_arguments: 'fail_interval=300'
202 state: args_present
203
204 - name: Add pam common-auth rule for duo
205 community.general.pamd:
206 name: common-auth
207 new_type: auth
208 new_control: '[success=1 default=ignore]'
209 new_module_path: '/lib64/security/pam_duo.so'
210 state: after
211 type: auth
212 module_path: pam_sss.so
213 control: 'requisite'
214 """
215
216 RETURN = r"""
217 change_count:
218 description: How many rules were changed.
219 type: int
220 sample: 1
221 returned: success
222 backupdest:
223 description:
224 - The file name of the backup file, if created.
225 returned: success
226 type: str
227 """
228
229
230 import os
231 import re
232 from datetime import datetime
233 from tempfile import NamedTemporaryFile
234
235 from ansible.module_utils.basic import AnsibleModule
236
237 RULE_REGEX = re.compile(
238 r"""(?P<rule_type>-?(?:auth|account|session|password))\s+
239 (?P<control>\[.*\]|\S*)\s+
240 (?P<path>\S*)\s*
241 (?P<args>.*)\s*""",
242 re.X,
243 )
244 RULE_ARG_REGEX = re.compile(r"(\[.*\]|\S*)")
245
246 VALID_TYPES = ["account", "-account", "auth", "-auth", "password", "-password", "session", "-session"]
247
248
249 class PamdLine:
250 def __init__(self, line):
251 self.line = line
252 self.prev = None
253 self.next = None
254
255 @property
256 def is_valid(self):
257 return self.line.strip() == ""
258
259 def validate(self):
260 if not self.is_valid:
261 return False, f"Rule is not valid {self.line}"
262 return True, f"Rule is valid {self.line}"
263
264 # Method to check if a rule matches the type, control and path.
265 def matches(self, rule_type, rule_control, rule_path, rule_args=None):
266 return False
267
268 def __str__(self):
269 return str(self.line)
270
271
272 class PamdEmptyLine(PamdLine):
273 pass
274
275
276 class PamdComment(PamdLine):
277 def __init__(self, line):
278 super().__init__(line)
279
280 @property
281 def is_valid(self):
282 return self.line.startswith("#")
283
284
285 class PamdInclude(PamdLine):
286 def __init__(self, line):
287 super().__init__(line)
288
289 @property
290 def is_valid(self):
291 return self.line.startswith("@include")
292
293
294 class PamdRule(PamdLine):
295 valid_simple_controls = ["required", "requisite", "sufficient", "optional", "include", "substack", "definitive"]
296 valid_control_values = [
297 "success",
298 "open_err",
299 "symbol_err",
300 "service_err",
301 "system_err",
302 "buf_err",
303 "perm_denied",
304 "auth_err",
305 "cred_insufficient",
306 "authinfo_unavail",
307 "user_unknown",
308 "maxtries",
309 "new_authtok_reqd",
310 "acct_expired",
311 "session_err",
312 "cred_unavail",
313 "cred_expired",
314 "cred_err",
315 "no_module_data",
316 "conv_err",
317 "authtok_err",
318 "authtok_recover_err",
319 "authtok_lock_busy",
320 "authtok_disable_aging",
321 "try_again",
322 "ignore",
323 "abort",
324 "authtok_expired",
325 "module_unknown",
326 "bad_item",
327 "conv_again",
328 "incomplete",
329 "default",
330 ]
331 valid_control_actions = ["ignore", "bad", "die", "ok", "done", "reset"]
332
333 def __init__(self, rule_type, rule_control, rule_path, rule_args=None):
334 self.prev = None
335 self.next = None
336 self._control = None
337 self._args = None
338 self.rule_type = rule_type
339 self.rule_control = rule_control
340
341 self.rule_path = rule_path
342 self.rule_args = rule_args
343
344 # Method to check if a rule matches the type, control and path.
345 def matches(self, rule_type, rule_control, rule_path, rule_args=None):
346 return rule_type == self.rule_type and rule_control == self.rule_control and rule_path == self.rule_path
347
348 @classmethod
349 def rule_from_string(cls, line):
350 rule_match = RULE_REGEX.search(line)
351 rule_args = parse_module_arguments(rule_match.group("args"))
352 return cls(rule_match.group("rule_type"), rule_match.group("control"), rule_match.group("path"), rule_args)
353
354 def __str__(self):
355 if self.rule_args:
356 return f"{self.rule_type: <11}{self.rule_control} {self.rule_path} {' '.join(self.rule_args)}"
357 return f"{self.rule_type: <11}{self.rule_control} {self.rule_path}"
358
359 @property
360 def rule_control(self):
361 if isinstance(self._control, list):
362 return f"[{' '.join(self._control)}]"
363 return self._control
364
365 @rule_control.setter
366 def rule_control(self, control):
367 if control.startswith("["):
368 control = control.replace(" = ", "=").replace("[", "").replace("]", "")
369 self._control = control.split(" ")
370 else:
371 self._control = control
372
373 @property
374 def rule_args(self):
375 if not self._args:
376 return []
377 return self._args
378
379 @rule_args.setter
380 def rule_args(self, args):
381 self._args = parse_module_arguments(args)
382
383 @property
384 def line(self):
385 return str(self)
386
387 @classmethod
388 def is_action_unsigned_int(cls, string_num):
389 number = 0
390 try:
391 number = int(string_num)
392 except ValueError:
393 return False
394
395 return number >= 0
396
397 @property
398 def is_valid(self):
399 return self.validate()[0]
400
401 def validate(self):
402 # Validate the rule type
403 if self.rule_type not in VALID_TYPES:
404 return False, f"Rule type, {self.rule_type}, is not valid in rule {self.line}"
405 # Validate the rule control
406 if isinstance(self._control, str) and self.rule_control not in PamdRule.valid_simple_controls:
407 return False, f"Rule control, {self.rule_control}, is not valid in rule {self.line}"
408 elif isinstance(self._control, list):
409 for control in self._control:
410 value, action = control.split("=")
411 if value not in PamdRule.valid_control_values:
412 return False, f"Rule control value, {value}, is not valid in rule {self.line}"
413 if action not in PamdRule.valid_control_actions and not PamdRule.is_action_unsigned_int(action):
414 return False, f"Rule control action, {action}, is not valid in rule {self.line}"
415
416 # TODO: Validate path
417
418 return True, f"Rule is valid {self.line}"
419
420
421 # PamdService encapsulates an entire service and contains one or more rules. It seems the best way is to do this
422 # as a doubly linked list.
423 class PamdService:
424 def __init__(self, content):
425 self._head = None
426 self._tail = None
427 for line in content.splitlines():
428 if line.lstrip().startswith("#"):
429 pamd_line = PamdComment(line)
430 elif line.lstrip().startswith("@include"):
431 pamd_line = PamdInclude(line)
432 elif line.strip() == "":
433 pamd_line = PamdEmptyLine(line)
434 else:
435 pamd_line = PamdRule.rule_from_string(line)
436
437 self.append(pamd_line)
438
439 def append(self, pamd_line):
440 if self._head is None:
441 self._head = self._tail = pamd_line
442 else:
443 pamd_line.prev = self._tail
444 pamd_line.next = None
445 self._tail.next = pamd_line
446 self._tail = pamd_line
447
448 def remove(self, rule_type, rule_control, rule_path):
449 current_line = self._head
450 changed = 0
451
452 while current_line is not None:
453 if current_line.matches(rule_type, rule_control, rule_path):
454 if current_line.prev is not None:
455 current_line.prev.next = current_line.next
456 if current_line.next is not None:
457 current_line.next.prev = current_line.prev
458 else:
459 self._head = current_line.next
460 current_line.next.prev = None
461 changed += 1
462
463 current_line = current_line.next
464 return changed
465
466 def get(self, rule_type, rule_control, rule_path):
467 lines = []
468 current_line = self._head
469 while current_line is not None:
470 if isinstance(current_line, PamdRule) and current_line.matches(rule_type, rule_control, rule_path):
471 lines.append(current_line)
472
473 current_line = current_line.next
474
475 return lines
476
477 def has_rule(self, rule_type, rule_control, rule_path):
478 return bool(self.get(rule_type, rule_control, rule_path))
479
480 def update_rule(
481 self, rule_type, rule_control, rule_path, new_type=None, new_control=None, new_path=None, new_args=None
482 ):
483 # Get a list of rules we want to change
484 rules_to_find = self.get(rule_type, rule_control, rule_path)
485
486 new_args = parse_module_arguments(new_args, return_none=True)
487
488 changes = 0
489 for current_rule in rules_to_find:
490 rule_changed = False
491 if new_type:
492 if current_rule.rule_type != new_type:
493 rule_changed = True
494 current_rule.rule_type = new_type
495 if new_control:
496 if current_rule.rule_control != new_control:
497 rule_changed = True
498 current_rule.rule_control = new_control
499 if new_path:
500 if current_rule.rule_path != new_path:
501 rule_changed = True
502 current_rule.rule_path = new_path
503 if new_args is not None:
504 if current_rule.rule_args != new_args:
505 rule_changed = True
506 current_rule.rule_args = new_args
507
508 if rule_changed:
509 changes += 1
510
511 return changes
512
513 def insert_before(
514 self, rule_type, rule_control, rule_path, new_type=None, new_control=None, new_path=None, new_args=None
515 ):
516 # Get a list of rules we want to change
517 rules_to_find = self.get(rule_type, rule_control, rule_path)
518 changes = 0
519 # There are two cases to consider.
520 # 1. The new rule doesn't exist before the existing rule
521 # 2. The new rule exists
522
523 for current_rule in rules_to_find:
524 # Create a new rule
525 new_rule = PamdRule(new_type, new_control, new_path, new_args)
526 # First we'll get the previous rule.
527 previous_rule = current_rule.prev
528
529 # Next we may have to loop backwards if the previous line is a comment. If it
530 # is, we'll get the previous "rule's" previous.
531 while previous_rule is not None and isinstance(previous_rule, (PamdComment, PamdEmptyLine)):
532 previous_rule = previous_rule.prev
533 # Next we'll see if the previous rule matches what we are trying to insert.
534 if previous_rule is not None and not previous_rule.matches(new_type, new_control, new_path):
535 # First set the original previous rule's next to the new_rule
536 previous_rule.next = new_rule
537 # Second, set the new_rule's previous to the original previous
538 new_rule.prev = previous_rule
539 # Third, set the new rule's next to the current rule
540 new_rule.next = current_rule
541 # Fourth, set the current rule's previous to the new_rule
542 current_rule.prev = new_rule
543
544 changes += 1
545
546 # Handle the case where it is the first rule in the list.
547 elif previous_rule is None:
548 # This is the case where the current rule is not only the first rule
549 # but the first line as well. So we set the head to the new rule
550 if current_rule.prev is None:
551 self._head = new_rule
552 # This case would occur if the previous line was a comment.
553 else:
554 current_rule.prev.next = new_rule
555 new_rule.prev = current_rule.prev
556 new_rule.next = current_rule
557 current_rule.prev = new_rule
558 changes += 1
559
560 return changes
561
562 def insert_after(
563 self, rule_type, rule_control, rule_path, new_type=None, new_control=None, new_path=None, new_args=None
564 ):
565 # Get a list of rules we want to change
566 rules_to_find = self.get(rule_type, rule_control, rule_path)
567 changes = 0
568 # There are two cases to consider.
569 # 1. The new rule doesn't exist after the existing rule
570 # 2. The new rule exists
571 for current_rule in rules_to_find:
572 # First we'll get the next rule.
573 next_rule = current_rule.next
574 # Next we may have to loop forwards if the next line is a comment. If it
575 # is, we'll get the next "rule's" next.
576 while next_rule is not None and isinstance(next_rule, (PamdComment, PamdEmptyLine)):
577 next_rule = next_rule.next
578
579 # First we create a new rule
580 new_rule = PamdRule(new_type, new_control, new_path, new_args)
581 if next_rule is not None and not next_rule.matches(new_type, new_control, new_path):
582 # If the previous rule doesn't match we'll insert our new rule.
583
584 # Second set the original next rule's previous to the new_rule
585 next_rule.prev = new_rule
586 # Third, set the new_rule's next to the original next rule
587 new_rule.next = next_rule
588 # Fourth, set the new rule's previous to the current rule
589 new_rule.prev = current_rule
590 # Fifth, set the current rule's next to the new_rule
591 current_rule.next = new_rule
592
593 changes += 1
594
595 # This is the case where the current_rule is the last in the list
596 elif next_rule is None:
597 new_rule.prev = self._tail
598 new_rule.next = None
599 self._tail.next = new_rule
600 self._tail = new_rule
601
602 current_rule.next = new_rule
603 changes += 1
604
605 return changes
606
607 def add_module_arguments(self, rule_type, rule_control, rule_path, args_to_add):
608 # Get a list of rules we want to change
609 rules_to_find = self.get(rule_type, rule_control, rule_path)
610
611 args_to_add = parse_module_arguments(args_to_add)
612
613 changes = 0
614
615 for current_rule in rules_to_find:
616 rule_changed = False
617
618 # create some structures to evaluate the situation
619 simple_new_args = set()
620 key_value_new_args = dict()
621
622 for arg in args_to_add:
623 if arg.startswith("["):
624 continue
625 elif "=" in arg:
626 key, value = arg.split("=")
627 key_value_new_args[key] = value
628 else:
629 simple_new_args.add(arg)
630
631 key_value_new_args_set = set(key_value_new_args)
632
633 simple_current_args = set()
634 key_value_current_args = dict()
635
636 for arg in current_rule.rule_args:
637 if arg.startswith("["):
638 continue
639 elif "=" in arg:
640 key, value = arg.split("=")
641 key_value_current_args[key] = value
642 else:
643 simple_current_args.add(arg)
644
645 key_value_current_args_set = set(key_value_current_args)
646
647 new_args_to_add = list()
648
649 # Handle new simple arguments
650 if simple_new_args.difference(simple_current_args):
651 for arg in simple_new_args.difference(simple_current_args):
652 new_args_to_add.append(arg)
653
654 # Handle new key value arguments
655 if key_value_new_args_set.difference(key_value_current_args_set):
656 for key in key_value_new_args_set.difference(key_value_current_args_set):
657 new_args_to_add.append(f"{key}={key_value_new_args[key]}")
658
659 if new_args_to_add:
660 current_rule.rule_args += new_args_to_add
661 rule_changed = True
662
663 # Handle existing key value arguments when value is not equal
664 if key_value_new_args_set.intersection(key_value_current_args_set):
665 for key in key_value_new_args_set.intersection(key_value_current_args_set):
666 if key_value_current_args[key] != key_value_new_args[key]:
667 arg_index = current_rule.rule_args.index(f"{key}={key_value_current_args[key]}")
668 current_rule.rule_args[arg_index] = str(f"{key}={key_value_new_args[key]}")
669 rule_changed = True
670
671 if rule_changed:
672 changes += 1
673
674 return changes
675
676 def remove_module_arguments(self, rule_type, rule_control, rule_path, args_to_remove):
677 # Get a list of rules we want to change
678 rules_to_find = self.get(rule_type, rule_control, rule_path)
679
680 args_to_remove = parse_module_arguments(args_to_remove)
681
682 changes = 0
683
684 for current_rule in rules_to_find:
685 if not args_to_remove:
686 args_to_remove = []
687
688 # Let's check to see if there are any args to remove by finding the intersection
689 # of the rule's current args and the args_to_remove lists
690 if not list(set(current_rule.rule_args) & set(args_to_remove)):
691 continue
692
693 # There are args to remove, so we create a list of new_args absent the args
694 # to remove.
695 current_rule.rule_args = [arg for arg in current_rule.rule_args if arg not in args_to_remove]
696
697 changes += 1
698
699 return changes
700
701 def validate(self):
702 current_line = self._head
703
704 while current_line is not None:
705 curr_validate = current_line.validate()
706 if not curr_validate[0]:
707 return curr_validate
708 current_line = current_line.next
709 return True, "Module is valid"
710
711 def __str__(self):
712 lines = []
713 current_line = self._head
714
715 mark = f"# Updated by Ansible - {datetime.now().isoformat()}"
716 while current_line is not None:
717 lines.append(str(current_line))
718 current_line = current_line.next
719
720 if len(lines) <= 1:
721 lines.insert(0, "")
722 lines.insert(1, mark)
723 else:
724 if lines[1].startswith("# Updated by Ansible"):
725 lines[1] = mark
726 else:
727 lines.insert(1, mark)
728
729 lines_joined = "\n".join(lines)
730 return f"{lines_joined}\n"
731
732
733 def parse_module_arguments(module_arguments, return_none=False):
734 # If args is None, return empty list by default.
735 # But if return_none is True, then return None
736 if module_arguments is None:
737 return None if return_none else []
738 if isinstance(module_arguments, list) and len(module_arguments) == 1 and not module_arguments[0]:
739 return []
740
741 if not isinstance(module_arguments, list):
742 module_arguments = [module_arguments]
743
744 # From this point on, module_arguments is guaranteed to be a list, empty or not
745 parsed_args = []
746
747 re_clear_spaces = re.compile(r"\s*=\s*")
748 for arg in module_arguments:
749 for item in filter(None, RULE_ARG_REGEX.findall(arg)):
750 if not item.startswith("["):
751 re_clear_spaces.sub("=", item)
752 parsed_args.append(item)
753
754 return parsed_args
755
756
757 def main():
758 module = AnsibleModule(
759 argument_spec=dict(
760 name=dict(type="str", required=True),
761 type=dict(type="str", required=True, choices=VALID_TYPES),
762 control=dict(type="str", required=True),
763 module_path=dict(type="str", required=True),
764 new_type=dict(type="str", choices=VALID_TYPES),
765 new_control=dict(type="str"),
766 new_module_path=dict(type="str"),
767 module_arguments=dict(type="list", elements="str"),
768 state=dict(
769 type="str",
770 default="updated",
771 choices=["absent", "after", "args_absent", "args_present", "before", "updated"],
772 ),
773 path=dict(type="path", default="/etc/pam.d"),
774 backup=dict(type="bool", default=False),
775 ),
776 supports_check_mode=True,
777 required_if=[
778 ("state", "args_present", ["module_arguments"]),
779 ("state", "args_absent", ["module_arguments"]),
780 ("state", "before", ["new_control", "new_type", "new_module_path"]),
781 ("state", "after", ["new_control", "new_type", "new_module_path"]),
782 ],
783 )
784 content = ""
785 fname = os.path.join(module.params["path"], module.params["name"])
786
787 # Open the file and read the content or fail
788 try:
789 with open(fname) as service_file_obj:
790 content = service_file_obj.read()
791 except OSError as e:
792 # If unable to read the file, fail out
793 module.fail_json(msg=f"Unable to open/read PAM module file {fname} with error {e}.")
794
795 # Assuming we didn't fail, create the service
796 service = PamdService(content)
797 # Set the action
798 action = module.params["state"]
799
800 changes = 0
801
802 # Take action
803 if action == "updated":
804 changes = service.update_rule(
805 module.params["type"],
806 module.params["control"],
807 module.params["module_path"],
808 module.params["new_type"],
809 module.params["new_control"],
810 module.params["new_module_path"],
811 module.params["module_arguments"],
812 )
813 elif action == "before":
814 changes = service.insert_before(
815 module.params["type"],
816 module.params["control"],
817 module.params["module_path"],
818 module.params["new_type"],
819 module.params["new_control"],
820 module.params["new_module_path"],
821 module.params["module_arguments"],
822 )
823 elif action == "after":
824 changes = service.insert_after(
825 module.params["type"],
826 module.params["control"],
827 module.params["module_path"],
828 module.params["new_type"],
829 module.params["new_control"],
830 module.params["new_module_path"],
831 module.params["module_arguments"],
832 )
833 elif action == "args_absent":
834 changes = service.remove_module_arguments(
835 module.params["type"],
836 module.params["control"],
837 module.params["module_path"],
838 module.params["module_arguments"],
839 )
840 elif action == "args_present":
841 if [arg for arg in parse_module_arguments(module.params["module_arguments"]) if arg.startswith("[")]:
842 module.fail_json(
843 msg="Unable to process bracketed '[' complex arguments with 'args_present'. Please use 'updated'."
844 )
845
846 changes = service.add_module_arguments(
847 module.params["type"],
848 module.params["control"],
849 module.params["module_path"],
850 module.params["module_arguments"],
851 )
852 elif action == "absent":
853 changes = service.remove(module.params["type"], module.params["control"], module.params["module_path"])
854
855 valid, msg = service.validate()
856
857 # If the module is not valid (meaning one of the rules is invalid), we will fail
858 if not valid:
859 module.fail_json(msg=msg)
860
861 result = dict(
862 changed=(changes > 0),
863 change_count=changes,
864 backupdest="",
865 )
866
867 # If not check mode and something changed, backup the original if necessary then write out the file or fail
868 if not module.check_mode and result["changed"]:
869 # First, create a backup if desired.
870 if module.params["backup"]:
871 result["backupdest"] = module.backup_local(fname)
872 try:
873 temp_file = NamedTemporaryFile(mode="w", dir=module.tmpdir, delete=False)
874 with open(temp_file.name, "w") as fd:
875 fd.write(str(service))
876
877 except OSError:
878 module.fail_json(msg=f"Unable to create temporary file {temp_file}")
879
880 module.atomic_move(temp_file.name, os.path.realpath(fname))
881
882 module.exit_json(**result)
883
884
885 if __name__ == "__main__":
886 main()