Repository: ansible-collections/community.general

Issue:
community.general.sudoers should do a syntax check
### Summary

The `sudoers` module currently allows writing broken `sudoers` files, for example when `commands` is not an absolute path. This kind of user error can easily be detected by running `visudo -c -f ...` on the new file. I think it makes sense for the `sudoers` module to run this check.

Some errors, such as duplicate aliases, can only be detected in the context of the other `sudoers` files. According to [this post](https://serverfault.com/a/901906) a more comprehensive check can be done by running a full configuration check `visudo -c` after installing the new file. However, I'm not sure if this is worth implementing. The `sudoers` module does not currently seem to be capable of producing syntax error that can not be detected by a simple `visudo -c -f ...`.

### Issue Type

Feature Idea

### Component Name

sudoers

### Additional Information

Slightly modified example task from the documentation:
```yaml
- name: >-
    Allow the alice user to run sudo /bin/systemctl restart my-service or
    sudo /bin/systemctl reload my-service, but a password is required
  community.general.sudoers:
    name: alice-service
    user: alice
    commands:
      - systemctl restart my-service
```

`sudo` commands complain about the syntax error:
```
visudo -c -f /etc/sudoers.d/alice-service
alice-service:1:21: syntax error
alice ALL=NOPASSWD: systemctl restart my-service
                    ^~~~~~~~~
```

### Code of Conduct

- [X] I agree to follow the Ansible Code of Conduct


Discussion:
Files identified in the description:
* [`plugins/modules/system/sudoers.py`](https://github.com/ansible-collections/community.general/blob/main/plugins/modules/system/sudoers.py)

If these files are incorrect, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/devel/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @JonEllis @JonEllis0
[click here for bot help](https://github.com/ansible/ansibullbot/blob/devel/ISSUE_HELP.md)
<!--- boilerplate: notify --->
For me on RHEL 8 boxes the "visudo -c "check command reports that the file permissions are bad on files that were created by the sudoers module. New files are created with 644. Should I create a new issue for this?
```
# visudo -c 
/etc/sudoers: parsed OK
/etc/sudores.d/some-new-rule: bad permissions, should be mode 0440

# umask
0022

# ls -l /etc/sudores.d/some-new-rule
-rw-r--r--. 1 root root 340 May 30 2020 some-new-rule
```


@repcsi since it's not related to the current issue, yes please.
Great suggestion. Validation sounds like a good addition to me.

Resolving patch:
diff --git a/plugins/modules/system/sudoers.py b/plugins/modules/system/sudoers.py
--- a/plugins/modules/system/sudoers.py
+++ b/plugins/modules/system/sudoers.py
@@ -65,6 +65,15 @@
       - The name of the user for the sudoers rule.
       - This option cannot be used in conjunction with I(group).
     type: str
+  validation:
+    description:
+      - If C(absent), the sudoers rule will be added without validation.
+      - If C(detect) and visudo is available, then the sudoers rule will be validated by visudo.
+      - If C(required), visudo must be available to validate the sudoers rule.
+    type: str
+    default: detect
+    choices: [ absent, detect, required ]
+    version_added: 5.2.0
 '''
 
 EXAMPLES = '''
@@ -118,6 +127,8 @@ class Sudoers(object):
     FILE_MODE = 0o440
 
     def __init__(self, module):
+        self.module = module
+
         self.check_mode = module.check_mode
         self.name = module.params['name']
         self.user = module.params['user']
@@ -128,6 +139,7 @@ def __init__(self, module):
         self.sudoers_path = module.params['sudoers_path']
         self.file = os.path.join(self.sudoers_path, self.name)
         self.commands = module.params['commands']
+        self.validation = module.params['validation']
 
     def write(self):
         if self.check_mode:
@@ -167,6 +179,20 @@ def content(self):
         runas_str = '({runas})'.format(runas=self.runas) if self.runas is not None else ''
         return "{owner} ALL={runas}{nopasswd} {commands}\n".format(owner=owner, runas=runas_str, nopasswd=nopasswd_str, commands=commands_str)
 
+    def validate(self):
+        if self.validation == 'absent':
+            return
+
+        visudo_path = self.module.get_bin_path('visudo', required=self.validation == 'required')
+        if visudo_path is None:
+            return
+
+        check_command = [visudo_path, '-c', '-f', '-']
+        rc, stdout, stderr = self.module.run_command(check_command, data=self.content())
+
+        if rc != 0:
+            raise Exception('Failed to validate sudoers rule:\n{stdout}'.format(stdout=stdout))
+
     def run(self):
         if self.state == 'absent':
             if self.exists():
@@ -175,6 +201,8 @@ def run(self):
             else:
                 return False
 
+        self.validate()
+
         if self.exists() and self.matches():
             return False
 
@@ -209,6 +237,10 @@ def main():
             'choices': ['present', 'absent'],
         },
         'user': {},
+        'validation': {
+            'default': 'detect',
+            'choices': ['absent', 'detect', 'required']
+        },
     }
 
     module = AnsibleModule(


Test patch:
diff --git a/tests/integration/targets/sudoers/tasks/main.yml b/tests/integration/targets/sudoers/tasks/main.yml
--- a/tests/integration/targets/sudoers/tasks/main.yml
+++ b/tests/integration/targets/sudoers/tasks/main.yml
@@ -1,11 +1,16 @@
 ---
 # Initialise environment
 
-- name: Register sudoers.d directory
+- name: Register variables
   set_fact:
     sudoers_path: /etc/sudoers.d
     alt_sudoers_path: /etc/sudoers_alt
 
+- name: Install sudo package
+  ansible.builtin.package:
+    name: sudo
+  when: ansible_os_family != 'Darwin'
+
 - name: Ensure sudoers directory exists
   ansible.builtin.file:
     path: "{{ sudoers_path }}"
@@ -135,6 +140,52 @@
   register: revoke_rule_1_stat
 
 
+# Validation testing
+
+- name: Attempt command without full path to executable
+  community.general.sudoers:
+    name: edge-case-1
+    state: present
+    user: alice
+    commands: systemctl
+  ignore_errors: true
+  register: edge_case_1
+
+
+- name: Attempt command without full path to executable, but disabling validation
+  community.general.sudoers:
+    name: edge-case-2
+    state: present
+    user: alice
+    commands: systemctl
+    validation: absent
+    sudoers_path: "{{ alt_sudoers_path }}"
+  register: edge_case_2
+
+- name: find visudo
+  command:
+    cmd: which visudo
+  register: which_visudo
+  when: ansible_os_family != 'Darwin'
+
+- name: Prevent visudo being executed
+  file:
+    path: "{{ which_visudo.stdout }}"
+    mode: '-x'
+  when: ansible_os_family != 'Darwin'
+
+- name: Attempt command without full path to executable, but enforcing validation with no visudo present
+  community.general.sudoers:
+    name: edge-case-3
+    state: present
+    user: alice
+    commands: systemctl
+    validation: required
+  ignore_errors: true
+  when: ansible_os_family != 'Darwin'
+  register: edge_case_3
+  
+  
 - name: Revoke non-existing rule
   community.general.sudoers:
     name: non-existing-rule
@@ -175,8 +226,22 @@
       - "rule_5_contents['content'] | b64decode == 'alice ALL=NOPASSWD: /usr/local/bin/command\n'"
       - "rule_6_contents['content'] | b64decode == 'alice ALL=(bob)NOPASSWD: /usr/local/bin/command\n'"
 
-- name: Check stats
+- name: Check revocation stat
   ansible.builtin.assert:
     that:
       - not revoke_rule_1_stat.stat.exists
       - not revoke_non_existing_rule_stat.stat.exists
+      
+- name: Check edge case responses
+  ansible.builtin.assert:
+    that:
+      - edge_case_1 is failed
+      - "'Failed to validate sudoers rule' in edge_case_1.msg"
+      - edge_case_2 is not failed
+
+- name: Check missing validation edge case
+  ansible.builtin.assert:
+    that:
+      - edge_case_3 is failed
+      - "'Failed to find required executable' in edge_case_3.msg"
+  when: ansible_os_family != 'Darwin'