Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Nimbis Services, Inc.
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: htpasswd
11 short_description: Manage user files for basic authentication
12 description:
13 - Add and remove username/password entries in a password file using htpasswd.
14 - This is used by web servers such as Apache and Nginx for basic authentication.
15 attributes:
16 check_mode:
17 support: full
18 diff_mode:
19 support: none
20 options:
21 path:
22 type: path
23 required: true
24 aliases: [dest, destfile]
25 description:
26 - Path to the file that contains the usernames and passwords.
27 name:
28 type: str
29 required: true
30 aliases: [username]
31 description:
32 - User name to add or remove.
33 password:
34 type: str
35 description:
36 - Password associated with user.
37 - Must be specified if user does not exist yet.
38 hash_scheme:
39 type: str
40 default: "apr_md5_crypt"
41 description:
42 - Hashing scheme to be used. As well as the four choices listed here, you can also use any other hash supported by passlib,
43 such as V(portable_apache22) and V(host_apache24); or V(md5_crypt) and V(sha256_crypt), which are Linux passwd hashes.
44 Only some schemes in addition to the four choices below are compatible with Apache or Nginx, and supported schemes
45 depend on C(passlib) version and its dependencies.
46 - See U(https://passlib.readthedocs.io/en/stable/lib/passlib.apache.html#passlib.apache.HtpasswdFile) parameter C(default_scheme).
47 - 'Some of the available choices might be: V(apr_md5_crypt), V(des_crypt), V(ldap_sha1), V(plaintext).'
48 - 'B(WARNING): The module has no mechanism to determine the O(hash_scheme) of an existing entry, therefore, it does
49 not detect whether the O(hash_scheme) has changed. If you want to change the scheme, you must remove the existing
50 entry and then create a new one using the new scheme.'
51 aliases: [crypt_scheme]
52 state:
53 type: str
54 choices: [present, absent]
55 default: "present"
56 description:
57 - Whether the user entry should be present or not.
58 create:
59 type: bool
60 default: true
61 description:
62 - Used with O(state=present). If V(true), the file is created if it does not exist. Conversely, if set to V(false) and
63 the file does not exist, it fails.
64 notes:
65 - This module depends on the C(passlib) Python library, which needs to be installed on all target systems.
66 - 'On Debian < 11, Ubuntu <= 20.04, or Fedora: install C(python-passlib).'
67 - 'On Debian, Ubuntu: install C(python3-passlib).'
68 - 'On RHEL or CentOS: Enable EPEL, then install C(python-passlib).'
69 requirements: [passlib>=1.6]
70 author: "Ansible Core Team"
71 extends_documentation_fragment:
72 - ansible.builtin.files
73 - community.general._attributes
74 """
75
76 EXAMPLES = r"""
77 - name: Add a user to a password file and ensure permissions are set
78 community.general.htpasswd:
79 path: /etc/nginx/passwdfile
80 name: janedoe
81 password: '9s36?;fyNp'
82 owner: root
83 group: www-data
84 mode: '0640'
85
86 - name: Remove a user from a password file
87 community.general.htpasswd:
88 path: /etc/apache2/passwdfile
89 name: foobar
90 state: absent
91
92 - name: Add a user to a password file suitable for use by libpam-pwdfile
93 community.general.htpasswd:
94 path: /etc/mail/passwords
95 name: alex
96 password: oedu2eGh
97 hash_scheme: md5_crypt
98 """
99
100
101 import os
102 import tempfile
103
104 from ansible.module_utils.basic import AnsibleModule
105
106 from ansible_collections.community.general.plugins.module_utils import _deps as deps
107
108 with deps.declare("passlib"):
109 # Apparently the type infos don't know htpasswd_context, which *does* exist
110 # (but isn't mentioned in the documentation for some reason)
111 from passlib.apache import HtpasswdFile, htpasswd_context # type: ignore[attr-defined]
112 from passlib.context import CryptContext
113
114
115 apache_hashes = ["apr_md5_crypt", "des_crypt", "ldap_sha1", "plaintext"]
116
117
118 def create_missing_directories(dest):
119 destpath = os.path.dirname(dest)
120 if not os.path.exists(destpath):
121 os.makedirs(destpath)
122
123
124 def present(dest, username, password, hash_scheme, create, check_mode):
125 """Ensures user is present
126
127 Returns (msg, changed)"""
128 if hash_scheme in apache_hashes:
129 context = htpasswd_context
130 else:
131 context = CryptContext(schemes=[hash_scheme] + apache_hashes)
132 if not os.path.exists(dest):
133 if not create:
134 raise ValueError(f"Destination {dest} does not exist")
135 if check_mode:
136 return (f"Create {dest}", True)
137 create_missing_directories(dest)
138 ht = HtpasswdFile(dest, new=True, default_scheme=hash_scheme, context=context)
139 ht.set_password(username, password)
140 ht.save()
141 return (f"Created {dest} and added {username}", True)
142 else:
143 ht = HtpasswdFile(dest, new=False, default_scheme=hash_scheme, context=context)
144
145 found = ht.check_password(username, password)
146
147 if found:
148 return (f"{username} already present", False)
149 else:
150 if not check_mode:
151 ht.set_password(username, password)
152 ht.save()
153 return (f"Add/update {username}", True)
154
155
156 def absent(dest, username, check_mode):
157 """Ensures user is absent
158
159 Returns (msg, changed)"""
160 ht = HtpasswdFile(dest, new=False)
161
162 if username not in ht.users():
163 return (f"{username} not present", False)
164 else:
165 if not check_mode:
166 ht.delete(username)
167 ht.save()
168 return (f"Remove {username}", True)
169
170
171 def check_file_attrs(module, changed, message):
172 file_args = module.load_file_common_arguments(module.params)
173 if module.set_fs_attributes_if_different(file_args, False):
174 if changed:
175 message += " and "
176 changed = True
177 message += "ownership, perms or SE linux context changed"
178
179 return message, changed
180
181
182 def main():
183 arg_spec = dict(
184 path=dict(type="path", required=True, aliases=["dest", "destfile"]),
185 name=dict(type="str", required=True, aliases=["username"]),
186 password=dict(type="str", no_log=True),
187 hash_scheme=dict(type="str", default="apr_md5_crypt", aliases=["crypt_scheme"]),
188 state=dict(type="str", default="present", choices=["present", "absent"]),
189 create=dict(type="bool", default=True),
190 )
191 module = AnsibleModule(argument_spec=arg_spec, add_file_common_args=True, supports_check_mode=True)
192
193 path = module.params["path"]
194 username = module.params["name"]
195 password = module.params["password"]
196 hash_scheme = module.params["hash_scheme"]
197 state = module.params["state"]
198 create = module.params["create"]
199 check_mode = module.check_mode
200
201 deps.validate(module)
202
203 # TODO double check if this hack below is still needed.
204 # Check file for blank lines in effort to avoid "need more than 1 value to unpack" error.
205 try:
206 with open(path) as f:
207 lines = f.readlines()
208
209 # If the file gets edited, it returns true, so only edit the file if it has blank lines
210 strip = False
211 for line in lines:
212 if not line.strip():
213 strip = True
214 break
215
216 if strip:
217 # If check mode, create a temporary file
218 if check_mode:
219 temp = tempfile.NamedTemporaryFile()
220 path = temp.name
221 with open(path, "w") as f:
222 f.writelines(line for line in lines if line.strip())
223
224 except OSError:
225 # No preexisting file to remove blank lines from
226 pass
227
228 try:
229 if state == "present":
230 (msg, changed) = present(path, username, password, hash_scheme, create, check_mode)
231 elif state == "absent":
232 if not os.path.exists(path):
233 module.warn(f"{path} does not exist")
234 module.exit_json(msg=f"{username} not present", changed=False)
235 (msg, changed) = absent(path, username, check_mode)
236 else:
237 module.fail_json(msg=f"Invalid state: {state}")
238 return # needed to make pylint happy
239
240 (msg, changed) = check_file_attrs(module, changed, msg)
241 module.exit_json(msg=msg, changed=changed)
242 except Exception as e:
243 module.fail_json(msg=f"{e}")
244
245
246 if __name__ == "__main__":
247 main()