Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Sebastien Rohaut <[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: pam_limits
11 author:
12 - "Sebastien Rohaut (@usawa)"
13 short_description: Modify Linux PAM limits
14 description:
15 - The M(community.general.pam_limits) module modifies PAM limits.
16 - The default file is V(/etc/security/limits.conf).
17 - For the full documentation, see C(man 5 limits.conf).
18 extends_documentation_fragment:
19 - community.general._attributes
20 attributes:
21 check_mode:
22 support: full
23 version_added: 2.0.0
24 diff_mode:
25 support: full
26 version_added: 2.0.0
27 options:
28 domain:
29 type: str
30 description:
31 - A username, @groupname, wildcard, UID/GID range.
32 required: true
33 limit_type:
34 type: str
35 description:
36 - Limit type, see C(man 5 limits.conf) for an explanation.
37 required: true
38 choices: ["hard", "soft", "-"]
39 limit_item:
40 type: str
41 description:
42 - The limit to be set.
43 required: true
44 choices:
45 - "core"
46 - "data"
47 - "fsize"
48 - "memlock"
49 - "nofile"
50 - "rss"
51 - "stack"
52 - "cpu"
53 - "nproc"
54 - "as"
55 - "maxlogins"
56 - "maxsyslogins"
57 - "priority"
58 - "locks"
59 - "sigpending"
60 - "msgqueue"
61 - "nice"
62 - "rtprio"
63 - "chroot"
64 value:
65 type: str
66 description:
67 - The value of the limit.
68 - Value must either be V(unlimited), V(infinity) or V(-1), all of which indicate no limit, or a limit of 0 or larger.
69 - Value must be a number in the range -20 to 19 inclusive, if O(limit_item) is set to V(nice) or V(priority).
70 - Refer to the C(man 5 limits.conf) manual pages for more details.
71 required: true
72 backup:
73 description:
74 - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered
75 it incorrectly.
76 type: bool
77 default: false
78 use_min:
79 description:
80 - If set to V(true), the minimal value is used or conserved.
81 - If the specified value is inferior to the value in the file, file content is replaced with the new value, else content
82 is not modified.
83 type: bool
84 default: false
85 use_max:
86 description:
87 - If set to V(true), the maximal value is used or conserved.
88 - If the specified value is superior to the value in the file, file content is replaced with the new value, else content
89 is not modified.
90 type: bool
91 default: false
92 dest:
93 type: str
94 description:
95 - Modify the limits.conf path.
96 default: "/etc/security/limits.conf"
97 comment:
98 type: str
99 description:
100 - Comment associated with the limit.
101 default: ''
102 notes:
103 - If O(dest) file does not exist, it is created.
104 """
105
106 EXAMPLES = r"""
107 - name: Add or modify nofile soft limit for the user joe
108 community.general.pam_limits:
109 domain: joe
110 limit_type: soft
111 limit_item: nofile
112 value: 64000
113
114 - name: Add or modify fsize hard limit for the user smith. Keep or set the maximal value
115 community.general.pam_limits:
116 domain: smith
117 limit_type: hard
118 limit_item: fsize
119 value: 1000000
120 use_max: true
121
122 - name: Add or modify memlock, both soft and hard, limit for the user james with a comment
123 community.general.pam_limits:
124 domain: james
125 limit_type: '-'
126 limit_item: memlock
127 value: unlimited
128 comment: unlimited memory lock for james
129
130 - name: Add or modify hard nofile limits for wildcard domain
131 community.general.pam_limits:
132 domain: '*'
133 limit_type: hard
134 limit_item: nofile
135 value: 39693561
136 """
137
138 import os
139 import re
140 import tempfile
141
142 from ansible.module_utils.basic import AnsibleModule
143 from ansible.module_utils.common.text.converters import to_native
144
145
146 def _assert_is_valid_value(module, item, value, prefix=""):
147 if item in ["nice", "priority"]:
148 try:
149 valid = -20 <= int(value) <= 19
150 except ValueError:
151 valid = False
152 if not valid:
153 module.fail_json(
154 msg=f"{prefix} Value of {value!r} for item {item!r} is invalid. Value must be a number in the range -20 to 19 inclusive. "
155 "Refer to the limits.conf(5) manual pages for more details."
156 )
157 elif not (value in ["unlimited", "infinity", "-1"] or value.isdigit()):
158 module.fail_json(
159 msg=f"{prefix} Value of {value!r} for item {item!r} is invalid. Value must either be 'unlimited', 'infinity' or -1, all of "
160 "which indicate no limit, or a limit of 0 or larger. Refer to the limits.conf(5) manual pages for "
161 "more details."
162 )
163
164
165 def main():
166 pam_items = [
167 "core",
168 "data",
169 "fsize",
170 "memlock",
171 "nofile",
172 "rss",
173 "stack",
174 "cpu",
175 "nproc",
176 "as",
177 "maxlogins",
178 "maxsyslogins",
179 "priority",
180 "locks",
181 "sigpending",
182 "msgqueue",
183 "nice",
184 "rtprio",
185 "chroot",
186 ]
187
188 pam_types = ["soft", "hard", "-"]
189
190 limits_conf = "/etc/security/limits.conf"
191
192 module = AnsibleModule(
193 argument_spec=dict(
194 domain=dict(required=True, type="str"),
195 limit_type=dict(required=True, type="str", choices=pam_types),
196 limit_item=dict(required=True, type="str", choices=pam_items),
197 value=dict(required=True, type="str"),
198 use_max=dict(default=False, type="bool"),
199 use_min=dict(default=False, type="bool"),
200 backup=dict(default=False, type="bool"),
201 dest=dict(default=limits_conf, type="str"),
202 comment=dict(default="", type="str"),
203 ),
204 supports_check_mode=True,
205 )
206
207 domain = module.params["domain"]
208 limit_type = module.params["limit_type"]
209 limit_item = module.params["limit_item"]
210 value = module.params["value"]
211 use_max = module.params["use_max"]
212 use_min = module.params["use_min"]
213 backup = module.params["backup"]
214 limits_conf = module.params["dest"]
215 new_comment = module.params["comment"]
216
217 changed = False
218 does_not_exist = False
219
220 if os.path.isfile(limits_conf):
221 if not os.access(limits_conf, os.W_OK):
222 module.fail_json(msg=f"{limits_conf} is not writable. Use sudo")
223 else:
224 limits_conf_dir = os.path.dirname(limits_conf)
225 if os.path.isdir(limits_conf_dir) and os.access(limits_conf_dir, os.W_OK):
226 does_not_exist = True
227 changed = True
228 else:
229 module.fail_json(
230 msg=f"directory {limits_conf_dir} is not writable (check presence, access rights, use sudo)"
231 )
232
233 if use_max and use_min:
234 module.fail_json(msg="Cannot use use_min and use_max at the same time.")
235
236 _assert_is_valid_value(module, limit_item, value)
237
238 backup_file = None
239 space_pattern = re.compile(r"\s+")
240
241 if does_not_exist:
242 lines = []
243 else:
244 with open(limits_conf, "rb") as f:
245 lines = list(f)
246
247 message = ""
248 # Tempfile
249 nf = tempfile.NamedTemporaryFile(mode="w+")
250
251 found = False
252 new_value = value
253
254 for line in lines:
255 line = to_native(line, errors="surrogate_or_strict")
256 if line.startswith("#"):
257 nf.write(line)
258 continue
259
260 newline = re.sub(space_pattern, " ", line).strip()
261 if not newline:
262 nf.write(line)
263 continue
264
265 # Remove comment in line
266 newline = newline.split("#", 1)[0]
267 try:
268 old_comment = line.split("#", 1)[1]
269 except Exception:
270 old_comment = ""
271
272 newline = newline.rstrip()
273
274 if not new_comment:
275 new_comment = old_comment
276
277 line_fields = newline.split(" ")
278
279 if len(line_fields) != 4:
280 nf.write(line)
281 continue
282
283 line_domain = line_fields[0]
284 line_type = line_fields[1]
285 line_item = line_fields[2]
286 actual_value = line_fields[3]
287
288 _assert_is_valid_value(
289 module, line_item, actual_value, prefix=f"Invalid configuration found in '{limits_conf}'."
290 )
291
292 # Found the line
293 if line_domain == domain and line_type == limit_type and line_item == limit_item:
294 found = True
295 if value == actual_value:
296 message = line
297 nf.write(line)
298 continue
299
300 if line_type not in ["nice", "priority"]:
301 actual_value_unlimited = actual_value in ["unlimited", "infinity", "-1"]
302 value_unlimited = value in ["unlimited", "infinity", "-1"]
303 else:
304 actual_value_unlimited = value_unlimited = False
305
306 if use_max:
307 if actual_value_unlimited:
308 new_value = actual_value
309 elif value_unlimited:
310 new_value = value
311 else:
312 new_value = str(max(int(value), int(actual_value)))
313
314 if use_min:
315 if actual_value_unlimited and value_unlimited:
316 new_value = actual_value
317 elif actual_value_unlimited:
318 new_value = value
319 elif value_unlimited:
320 new_value = actual_value
321 else:
322 new_value = str(min(int(value), int(actual_value)))
323
324 # Change line only if value has changed
325 if new_value != actual_value:
326 changed = True
327 if new_comment:
328 new_comment = f"\t#{new_comment}"
329 new_limit = f"{domain}\t{limit_type}\t{limit_item}\t{new_value}{new_comment}\n"
330 message = new_limit
331 nf.write(new_limit)
332 else:
333 message = line
334 nf.write(line)
335 else:
336 nf.write(line)
337
338 if not found:
339 changed = True
340 if new_comment:
341 new_comment = f"\t#{new_comment}"
342 new_limit = f"{domain}\t{limit_type}\t{limit_item}\t{new_value}{new_comment}\n"
343 message = new_limit
344 nf.write(new_limit)
345
346 nf.flush()
347
348 with open(nf.name) as content:
349 content_new = content.read()
350
351 if not module.check_mode:
352 if does_not_exist:
353 with open(limits_conf, "a"):
354 pass
355
356 if backup and changed and not does_not_exist:
357 backup_file = module.backup_local(limits_conf)
358
359 # Move tempfile to newfile
360 module.atomic_move(os.path.abspath(nf.name), os.path.abspath(limits_conf))
361
362 try:
363 nf.close()
364 except Exception:
365 pass
366
367 res_args = dict(
368 changed=changed,
369 msg=message,
370 diff=dict(before=b"".join(lines), after=content_new),
371 )
372
373 if backup_file:
374 res_args["backup_file"] = backup_file
375
376 module.exit_json(**res_args)
377
378
379 if __name__ == "__main__":
380 main()