summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/general/plugins/modules/sudoers.py
blob: a392b4adfaaab2c992140263d2d34a2254ba94f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/python
# -*- coding: utf-8 -*-


# Copyright (c) 2019, Jon Ellis (@JonEllis) <ellis.jp@gmail.com>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

from __future__ import absolute_import, division, print_function
__metaclass__ = type


DOCUMENTATION = '''
---
module: sudoers
short_description: Manage sudoers files
version_added: "4.3.0"
description:
  - This module allows for the manipulation of sudoers files.
author:
  - "Jon Ellis (@JonEllis) <ellis.jp@gmail.com>"
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  commands:
    description:
      - The commands allowed by the sudoers rule.
      - Multiple can be added by passing a list of commands.
      - Use V(ALL) for all commands.
    type: list
    elements: str
  group:
    description:
      - The name of the group for the sudoers rule.
      - This option cannot be used in conjunction with O(user).
    type: str
  name:
    required: true
    description:
      - The name of the sudoers rule.
      - This will be used for the filename for the sudoers file managed by this rule.
    type: str
  noexec:
    description:
      - Whether a command is prevented to run further commands itself.
    default: false
    type: bool
    version_added: 8.4.0
  nopassword:
    description:
      - Whether a password will be required to run the sudo'd command.
    default: true
    type: bool
  setenv:
    description:
      - Whether to allow keeping the environment when command is run with sudo.
    default: false
    type: bool
    version_added: 6.3.0
  host:
    description:
      - Specify the host the rule is for.
    default: ALL
    type: str
    version_added: 6.2.0
  runas:
    description:
      - Specify the target user the command(s) will run as.
    type: str
    version_added: 4.7.0
  sudoers_path:
    description:
      - The path which sudoers config files will be managed in.
    default: /etc/sudoers.d
    type: str
  state:
    default: "present"
    choices:
      - present
      - absent
    description:
      - Whether the rule should exist or not.
    type: str
  user:
    description:
      - The name of the user for the sudoers rule.
      - This option cannot be used in conjunction with O(group).
    type: str
  validation:
    description:
      - If V(absent), the sudoers rule will be added without validation.
      - If V(detect) and visudo is available, then the sudoers rule will be validated by visudo.
      - If V(required), visudo must be available to validate the sudoers rule.
    type: str
    default: detect
    choices: [ absent, detect, required ]
    version_added: 5.2.0
'''

EXAMPLES = '''
- name: Allow the backup user to sudo /usr/local/bin/backup
  community.general.sudoers:
    name: allow-backup
    state: present
    user: backup
    commands: /usr/local/bin/backup

- name: Allow the bob user to run any commands as alice with sudo -u alice
  community.general.sudoers:
    name: bob-do-as-alice
    state: present
    user: bob
    runas: alice
    commands: ALL

- name: >-
    Allow the monitoring group to run sudo /usr/local/bin/gather-app-metrics
    without requiring a password on the host called webserver
  community.general.sudoers:
    name: monitor-app
    group: monitoring
    host: webserver
    commands: /usr/local/bin/gather-app-metrics

- 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:
      - /bin/systemctl restart my-service
      - /bin/systemctl reload my-service
    nopassword: false

- name: Revoke the previous sudo grants given to the alice user
  community.general.sudoers:
    name: alice-service
    state: absent

- name: Allow alice to sudo /usr/local/bin/upload and keep env variables
  community.general.sudoers:
    name: allow-alice-upload
    user: alice
    commands: /usr/local/bin/upload
    setenv: true

- name: >-
    Allow alice to sudo /usr/bin/less but prevent less from
    running further commands itself
  community.general.sudoers:
    name: allow-alice-restricted-less
    user: alice
    commands: /usr/bin/less
    noexec: true
'''

import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native


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']
        self.group = module.params['group']
        self.state = module.params['state']
        self.noexec = module.params['noexec']
        self.nopassword = module.params['nopassword']
        self.setenv = module.params['setenv']
        self.host = module.params['host']
        self.runas = module.params['runas']
        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:
            return

        with open(self.file, 'w') as f:
            f.write(self.content())

        os.chmod(self.file, self.FILE_MODE)

    def delete(self):
        if self.check_mode:
            return

        os.remove(self.file)

    def exists(self):
        return os.path.exists(self.file)

    def matches(self):
        with open(self.file, 'r') as f:
            content_matches = f.read() == self.content()

        current_mode = os.stat(self.file).st_mode & 0o777
        mode_matches = current_mode == self.FILE_MODE

        return content_matches and mode_matches

    def content(self):
        if self.user:
            owner = self.user
        elif self.group:
            owner = '%{group}'.format(group=self.group)

        commands_str = ', '.join(self.commands)
        noexec_str = 'NOEXEC:' if self.noexec else ''
        nopasswd_str = 'NOPASSWD:' if self.nopassword else ''
        setenv_str = 'SETENV:' if self.setenv else ''
        runas_str = '({runas})'.format(runas=self.runas) if self.runas is not None else ''
        return "{owner} {host}={runas}{noexec}{nopasswd}{setenv} {commands}\n".format(
            owner=owner,
            host=self.host,
            runas=runas_str,
            noexec=noexec_str,
            nopasswd=nopasswd_str,
            setenv=setenv_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():
                self.delete()
                return True
            else:
                return False

        self.validate()

        if self.exists() and self.matches():
            return False

        self.write()
        return True


def main():
    argument_spec = {
        'commands': {
            'type': 'list',
            'elements': 'str',
        },
        'group': {},
        'name': {
            'required': True,
        },
        'noexec': {
            'type': 'bool',
            'default': False,
        },
        'nopassword': {
            'type': 'bool',
            'default': True,
        },
        'setenv': {
            'type': 'bool',
            'default': False,
        },
        'host': {
            'type': 'str',
            'default': 'ALL',
        },
        'runas': {
            'type': 'str',
            'default': None,
        },
        'sudoers_path': {
            'type': 'str',
            'default': '/etc/sudoers.d',
        },
        'state': {
            'default': 'present',
            'choices': ['present', 'absent'],
        },
        'user': {},
        'validation': {
            'default': 'detect',
            'choices': ['absent', 'detect', 'required']
        },
    }

    module = AnsibleModule(
        argument_spec=argument_spec,
        mutually_exclusive=[['user', 'group']],
        supports_check_mode=True,
        required_if=[('state', 'present', ['commands'])],
    )

    sudoers = Sudoers(module)

    try:
        changed = sudoers.run()
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=to_native(e))


if __name__ == '__main__':
    main()