/
risky_file_permissions.py
447 lines (389 loc) · 13.9 KB
/
risky_file_permissions.py
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# Copyright (c) 2020 Sorin Sbarnea <sorin.sbarnea@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""MissingFilePermissionsRule used with ansible-lint."""
from __future__ import annotations
import sys
from typing import TYPE_CHECKING, Any
from ansiblelint.rules import AnsibleLintRule
if TYPE_CHECKING:
from ansiblelint.file_utils import Lintable
# Despite documentation mentioning 'preserve' only these modules support it:
_modules_with_preserve = (
"copy",
"template",
)
_MODULES: set[str] = {
"archive",
"community.general.archive",
"assemble",
"ansible.builtin.assemble",
"copy", # supports preserve
"ansible.builtin.copy",
"file",
"ansible.builtin.file",
"get_url",
"ansible.builtin.get_url",
"replace", # implicit preserve behavior but mode: preserve is invalid
"ansible.builtin.replace",
"template", # supports preserve
"ansible.builtin.template",
# 'unarchive', # disabled because .tar.gz files can have permissions inside
}
_MODULES_WITH_CREATE: dict[str, bool] = {
"blockinfile": False,
"ansible.builtin.blockinfile": False,
"htpasswd": True,
"community.general.htpasswd": True,
"ini_file": True,
"community.general.ini_file": True,
"lineinfile": False,
"ansible.builtin.lineinfile": False,
}
class MissingFilePermissionsRule(AnsibleLintRule):
"""File permissions unset or incorrect."""
id = "risky-file-permissions"
description = (
"Missing or unsupported mode parameter can cause unexpected file "
"permissions based "
"on version of Ansible being used. Be explicit, like `mode: 0644` to "
"avoid hitting this rule. Special `preserve` value is accepted "
f"only by {', '.join([f'`{x}`' for x in _modules_with_preserve])} modules."
)
link = "https://github.com/ansible/ansible/issues/71200"
severity = "VERY_HIGH"
tags = ["unpredictability", "experimental"]
version_added = "v4.3.0"
_modules = _MODULES
_modules_with_create = _MODULES_WITH_CREATE
# pylint: disable=too-many-return-statements
def matchtask(
self, task: dict[str, Any], file: Lintable | None = None
) -> bool | str:
module = task["action"]["__ansible_module__"]
mode = task["action"].get("mode", None)
if module not in self._modules and module not in self._modules_with_create:
return False
if mode == "preserve" and module not in _modules_with_preserve:
return True
if module in self._modules_with_create:
create = task["action"].get("create", self._modules_with_create[module])
return create and mode is None
# A file that doesn't exist cannot have a mode
if task["action"].get("state", None) == "absent":
return False
# A symlink always has mode 0777
if task["action"].get("state", None) == "link":
return False
# Recurse on a directory does not allow for an uniform mode
if task["action"].get("recurse", None):
return False
# The file module does not create anything when state==file (default)
if module == "file" and task["action"].get("state", "file") == "file":
return False
# replace module is the only one that has a valid default preserve
# behavior, but we want to trigger rule if user used incorrect
# documentation and put 'preserve', which is not supported.
if module == "replace" and mode is None:
return False
return mode is None
if "pytest" in sys.modules: # noqa: C901
import pytest
from ansiblelint.testing import RunFromText # pylint: disable=ungrouped-imports
SUCCESS_PERMISSIONS_PRESENT = """
- hosts: all
tasks:
- name: Permissions not missing and numeric
file:
path: foo
mode: 0600
"""
SUCCESS_PERMISSIONS_PRESENT_GET_URL = """
- hosts: all
tasks:
- name: Permissions not missing and numeric
get_url:
url: http://foo
dest: foo
mode: 0600
"""
SUCCESS_ABSENT_STATE = """
- hosts: all
tasks:
- name: Permissions missing while state is absent is fine
file:
path: foo
state: absent
"""
SUCCESS_DEFAULT_STATE = """
- hosts: all
tasks:
- name: Permissions missing while state is file (default) is fine
file:
path: foo
"""
SUCCESS_LINK_STATE = """
- hosts: all
tasks:
- name: Permissions missing while state is link is fine
file:
path: foo2
src: foo
state: link
"""
SUCCESS_CREATE_FALSE = """
- hosts: all
tasks:
- name: File edit when create is false
lineinfile:
path: foo
create: false
line: some content here
"""
SUCCESS_REPLACE = """
- hosts: all
tasks:
- name: Replace should not require mode
replace:
path: foo
"""
SUCCESS_RECURSE = """
- hosts: all
tasks:
- name: File with recursive does not require mode
file:
state: directory
recurse: yes
- name: Permissions not missing and numeric (fqcn)
ansible.builtin.file:
path: bar
mode: 755
- name: File edit when create is false (fqcn)
ansible.builtin.lineinfile:
path: foo
create: false
line: some content here
"""
FAIL_PRESERVE_MODE = """
- hosts: all
tasks:
- name: File does not allow preserve value for mode
file:
path: foo
mode: preserve
"""
FAIL_MISSING_PERMISSIONS_TOUCH = """
- hosts: all
tasks:
- name: Permissions missing and might create file
file:
path: foo
state: touch
- name: Permissions missing and might create file (fqcn)
ansible.builtin.file:
path: foo
state: touch
"""
FAIL_MISSING_PERMISSIONS_DIRECTORY = """
- hosts: all
tasks:
- name: Permissions missing and might create directory
file:
path: foo
state: directory
- name: Lineinfile when create is true (fqcn)
ansible.builtin.lineinfile:
path: foo
create: true
line: some content here
"""
FAIL_MISSING_PERMISSIONS_GET_URL = """
---
- hosts: all
tasks:
- name: Permissions missing
# noqa: fqcn-builtins
get_url:
url: http://foo
dest: foo
"""
FAIL_LINEINFILE_CREATE = """
- hosts: all
tasks:
- name: Lineinfile when create is true
ansible.builtin.lineinfile:
path: foo
create: true
line: some content here
"""
FAIL_REPLACE_PRESERVE = """
- hosts: all
tasks:
- name: Replace does not allow preserve mode
replace:
path: foo
mode: preserve
"""
FAIL_PERMISSION_COMMENT = """
- hosts: all
tasks:
- name: Permissions is only a comment
file:
path: foo
owner: root
group: root
state: directory
# mode: 0755
"""
FAIL_INI_PERMISSION = """
- hosts: all
tasks:
- name: Permissions needed if create is used
ini_file:
path: foo
create: true
"""
FAIL_INI_PRESERVE = """
- hosts: all
tasks:
- name: Ini_file does not accept preserve mode
ini_file:
path: foo
create: true
mode: preserve
"""
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_permissions_present(rule_runner: RunFromText) -> None:
"""Permissions present and numeric."""
results = rule_runner.run_playbook(SUCCESS_PERMISSIONS_PRESENT)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_permissions_present_get_url(rule_runner: RunFromText) -> None:
"""Permissions present and numeric for get_url."""
results = rule_runner.run_playbook(SUCCESS_PERMISSIONS_PRESENT_GET_URL)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_absent_state(rule_runner: RunFromText) -> None:
"""No permissions required if file is absent."""
results = rule_runner.run_playbook(SUCCESS_ABSENT_STATE)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_default_state(rule_runner: RunFromText) -> None:
"""No permissions required if default state."""
results = rule_runner.run_playbook(SUCCESS_DEFAULT_STATE)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_link_state(rule_runner: RunFromText) -> None:
"""No permissions required if it is a link."""
results = rule_runner.run_playbook(SUCCESS_LINK_STATE)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_create_false(rule_runner: RunFromText) -> None:
"""No permissions required if file is not created."""
results = rule_runner.run_playbook(SUCCESS_CREATE_FALSE)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_replace(rule_runner: RunFromText) -> None:
"""Replacing a file do not require mode."""
results = rule_runner.run_playbook(SUCCESS_REPLACE)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_success_recurse(rule_runner: RunFromText) -> None:
"""Do not require mode when recursing."""
results = rule_runner.run_playbook(SUCCESS_RECURSE)
assert len(results) == 0
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_preserve_mode(rule_runner: RunFromText) -> None:
"""File does not allow preserve value for mode."""
results = rule_runner.run_playbook(FAIL_PRESERVE_MODE)
assert len(results) == 1
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_missing_permissions_touch(rule_runner: RunFromText) -> None:
"""Missing permissions when possibly creating file."""
results = rule_runner.run_playbook(FAIL_MISSING_PERMISSIONS_TOUCH)
assert len(results) == 2
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_missing_permissions_directory(rule_runner: RunFromText) -> None:
"""Missing permissions when possibly creating a directory."""
results = rule_runner.run_playbook(FAIL_MISSING_PERMISSIONS_DIRECTORY)
assert len(results) == 2
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_missing_permissions_get_url(rule_runner: RunFromText) -> None:
"""Missing permissions with get_url module."""
results = rule_runner.run_playbook(FAIL_MISSING_PERMISSIONS_GET_URL)
assert len(results) == 1
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_lineinfile_create(rule_runner: RunFromText) -> None:
"""Lineinfile might create a file."""
results = rule_runner.run_playbook(FAIL_LINEINFILE_CREATE)
assert len(results) == 1
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_replace_preserve(rule_runner: RunFromText) -> None:
"""Replace does not allow preserve mode."""
results = rule_runner.run_playbook(FAIL_REPLACE_PRESERVE)
assert len(results) == 1
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_permission_comment(rule_runner: RunFromText) -> None:
"""Permissions is only a comment."""
results = rule_runner.run_playbook(FAIL_PERMISSION_COMMENT)
assert len(results) == 1
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_ini_permission(rule_runner: RunFromText) -> None:
"""Permissions needed if create is used."""
results = rule_runner.run_playbook(FAIL_INI_PERMISSION)
assert len(results) == 1
@pytest.mark.parametrize(
"rule_runner", (MissingFilePermissionsRule,), indirect=["rule_runner"]
)
def test_fail_ini_preserve(rule_runner: RunFromText) -> None:
"""The ini_file module does not accept preserve mode."""
results = rule_runner.run_playbook(FAIL_INI_PRESERVE)
assert len(results) == 1