| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2019, George Rawlinson <[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: pacman_key |
| 11 |
author: |
| 12 |
- George Rawlinson (@grawlinson) |
| 13 |
version_added: "3.2.0" |
| 14 |
short_description: Manage pacman's list of trusted keys |
| 15 |
description: |
| 16 |
- Add or remove gpg keys from the pacman keyring. |
| 17 |
notes: |
| 18 |
- Use full-length key ID (40 characters). |
| 19 |
- Keys are verified when using O(data), O(file), or O(url) unless O(verify) is overridden. |
| 20 |
- Keys are locally signed after being imported into the keyring. |
| 21 |
- If the key ID exists in the keyring, the key is not added unless O(force_update) is specified. |
| 22 |
- O(data), O(file), O(url), and O(keyserver) are mutually exclusive. |
| 23 |
requirements: |
| 24 |
- gpg |
| 25 |
- pacman-key |
| 26 |
extends_documentation_fragment: |
| 27 |
- community.general._attributes |
| 28 |
attributes: |
| 29 |
check_mode: |
| 30 |
support: full |
| 31 |
diff_mode: |
| 32 |
support: none |
| 33 |
options: |
| 34 |
id: |
| 35 |
description: |
| 36 |
- The 40 character identifier of the key. |
| 37 |
- Including this allows check mode to correctly report the changed state. |
| 38 |
- Do not specify a subkey ID, instead specify the primary key ID. |
| 39 |
required: true |
| 40 |
type: str |
| 41 |
data: |
| 42 |
description: |
| 43 |
- The keyfile contents to add to the keyring. |
| 44 |
- Must be of C(PGP PUBLIC KEY BLOCK) type. |
| 45 |
type: str |
| 46 |
file: |
| 47 |
description: |
| 48 |
- The path to a keyfile on the remote server to add to the keyring. |
| 49 |
- Remote file must be of C(PGP PUBLIC KEY BLOCK) type. |
| 50 |
type: path |
| 51 |
url: |
| 52 |
description: |
| 53 |
- The URL to retrieve keyfile from. |
| 54 |
- Remote file must be of C(PGP PUBLIC KEY BLOCK) type. |
| 55 |
type: str |
| 56 |
keyserver: |
| 57 |
description: |
| 58 |
- The keyserver used to retrieve key from. |
| 59 |
type: str |
| 60 |
verify: |
| 61 |
description: |
| 62 |
- Whether or not to verify the keyfile's key ID against specified key ID. |
| 63 |
type: bool |
| 64 |
default: true |
| 65 |
force_update: |
| 66 |
description: |
| 67 |
- This forces the key to be updated if it already exists in the keyring. |
| 68 |
type: bool |
| 69 |
default: false |
| 70 |
keyring: |
| 71 |
description: |
| 72 |
- The full path to the keyring folder on the remote server. |
| 73 |
- If not specified, module uses pacman's default (V(/etc/pacman.d/gnupg)). |
| 74 |
- Useful if the remote system requires an alternative gnupg directory. |
| 75 |
type: path |
| 76 |
default: /etc/pacman.d/gnupg |
| 77 |
state: |
| 78 |
description: |
| 79 |
- Ensures that the key is V(present) (added) or V(absent) (revoked). |
| 80 |
default: present |
| 81 |
choices: [absent, present] |
| 82 |
type: str |
| 83 |
ensure_trusted: |
| 84 |
description: |
| 85 |
- Ensure that the key is trusted (signed by the Pacman machine key and not expired). |
| 86 |
type: bool |
| 87 |
default: false |
| 88 |
version_added: 11.0.0 |
| 89 |
""" |
| 90 |
|
| 91 |
EXAMPLES = r""" |
| 92 |
- name: Import a key via local file |
| 93 |
community.general.pacman_key: |
| 94 |
id: 01234567890ABCDE01234567890ABCDE12345678 |
| 95 |
data: "{{ lookup('file', 'keyfile.asc') }}" |
| 96 |
state: present |
| 97 |
|
| 98 |
- name: Import a key via remote file |
| 99 |
community.general.pacman_key: |
| 100 |
id: 01234567890ABCDE01234567890ABCDE12345678 |
| 101 |
file: /tmp/keyfile.asc |
| 102 |
state: present |
| 103 |
|
| 104 |
- name: Import a key via url |
| 105 |
community.general.pacman_key: |
| 106 |
id: 01234567890ABCDE01234567890ABCDE12345678 |
| 107 |
url: https://domain.tld/keys/keyfile.asc |
| 108 |
state: present |
| 109 |
|
| 110 |
- name: Import a key via keyserver |
| 111 |
community.general.pacman_key: |
| 112 |
id: 01234567890ABCDE01234567890ABCDE12345678 |
| 113 |
keyserver: keyserver.domain.tld |
| 114 |
|
| 115 |
- name: Import a key into an alternative keyring |
| 116 |
community.general.pacman_key: |
| 117 |
id: 01234567890ABCDE01234567890ABCDE12345678 |
| 118 |
file: /tmp/keyfile.asc |
| 119 |
keyring: /etc/pacman.d/gnupg-alternative |
| 120 |
|
| 121 |
- name: Remove a key from the keyring |
| 122 |
community.general.pacman_key: |
| 123 |
id: 01234567890ABCDE01234567890ABCDE12345678 |
| 124 |
state: absent |
| 125 |
""" |
| 126 |
|
| 127 |
RETURN = r""" # """ |
| 128 |
|
| 129 |
import os.path |
| 130 |
import tempfile |
| 131 |
|
| 132 |
from ansible.module_utils.basic import AnsibleModule |
| 133 |
from ansible.module_utils.common.text.converters import to_native |
| 134 |
from ansible.module_utils.urls import fetch_url |
| 135 |
|
| 136 |
|
| 137 |
class GpgListResult: |
| 138 |
"""Wraps gpg --list-* output.""" |
| 139 |
|
| 140 |
def __init__(self, line): |
| 141 |
self._parts = line.split(":") |
| 142 |
|
| 143 |
@property |
| 144 |
def kind(self): |
| 145 |
return self._parts[0] |
| 146 |
|
| 147 |
@property |
| 148 |
def valid(self): |
| 149 |
return self._parts[1] |
| 150 |
|
| 151 |
@property |
| 152 |
def is_fully_valid(self): |
| 153 |
return self.valid == "f" |
| 154 |
|
| 155 |
@property |
| 156 |
def key(self): |
| 157 |
return self._parts[4] |
| 158 |
|
| 159 |
@property |
| 160 |
def user_id(self): |
| 161 |
return self._parts[9] |
| 162 |
|
| 163 |
|
| 164 |
def gpg_get_first_attr_of_kind(lines, kind, attr): |
| 165 |
for line in lines: |
| 166 |
glr = GpgListResult(line) |
| 167 |
if glr.kind == kind: |
| 168 |
return getattr(glr, attr) |
| 169 |
|
| 170 |
|
| 171 |
def gpg_get_all_attrs_of_kind(lines, kind, attr): |
| 172 |
result = [] |
| 173 |
for line in lines: |
| 174 |
glr = GpgListResult(line) |
| 175 |
if glr.kind == kind: |
| 176 |
result.append(getattr(glr, attr)) |
| 177 |
return result |
| 178 |
|
| 179 |
|
| 180 |
class PacmanKey: |
| 181 |
def __init__(self, module): |
| 182 |
self.module = module |
| 183 |
# obtain binary paths for gpg & pacman-key |
| 184 |
self.gpg_binary = module.get_bin_path("gpg", required=True) |
| 185 |
self.pacman_key_binary = module.get_bin_path("pacman-key", required=True) |
| 186 |
|
| 187 |
# obtain module parameters |
| 188 |
keyid = module.params["id"] |
| 189 |
url = module.params["url"] |
| 190 |
data = module.params["data"] |
| 191 |
file = module.params["file"] |
| 192 |
keyserver = module.params["keyserver"] |
| 193 |
verify = module.params["verify"] |
| 194 |
force_update = module.params["force_update"] |
| 195 |
keyring = module.params["keyring"] |
| 196 |
state = module.params["state"] |
| 197 |
ensure_trusted = module.params["ensure_trusted"] |
| 198 |
self.keylength = 40 |
| 199 |
|
| 200 |
# sanitise key ID & check if key exists in the keyring |
| 201 |
keyid = self.sanitise_keyid(keyid) |
| 202 |
key_validity = self.key_validity(keyring, keyid) |
| 203 |
key_present = len(key_validity) > 0 |
| 204 |
key_valid = any(key_validity) |
| 205 |
|
| 206 |
# check mode |
| 207 |
if module.check_mode: |
| 208 |
if state == "present": |
| 209 |
changed = (key_present and force_update) or not key_present |
| 210 |
if not changed and ensure_trusted: |
| 211 |
changed = not (key_valid and self.key_is_trusted(keyring, keyid)) |
| 212 |
module.exit_json(changed=changed) |
| 213 |
if state == "absent": |
| 214 |
module.exit_json(changed=key_present) |
| 215 |
|
| 216 |
if state == "present": |
| 217 |
trusted = key_valid and self.key_is_trusted(keyring, keyid) |
| 218 |
if not force_update and key_present and (not ensure_trusted or trusted): |
| 219 |
module.exit_json(changed=False) |
| 220 |
changed = False |
| 221 |
if data: |
| 222 |
file = self.save_key(data) |
| 223 |
self.add_key(keyring, file, keyid, verify) |
| 224 |
changed = True |
| 225 |
elif file: |
| 226 |
self.add_key(keyring, file, keyid, verify) |
| 227 |
changed = True |
| 228 |
elif url: |
| 229 |
data = self.fetch_key(url) |
| 230 |
file = self.save_key(data) |
| 231 |
self.add_key(keyring, file, keyid, verify) |
| 232 |
changed = True |
| 233 |
elif keyserver: |
| 234 |
self.recv_key(keyring, keyid, keyserver) |
| 235 |
changed = True |
| 236 |
if changed or (ensure_trusted and not trusted): |
| 237 |
self.lsign_key(keyring=keyring, keyid=keyid) |
| 238 |
changed = True |
| 239 |
module.exit_json(changed=changed) |
| 240 |
elif state == "absent": |
| 241 |
if key_present: |
| 242 |
self.remove_key(keyring, keyid) |
| 243 |
module.exit_json(changed=True) |
| 244 |
module.exit_json(changed=False) |
| 245 |
|
| 246 |
def gpg(self, args, keyring=None, **kwargs): |
| 247 |
cmd = [self.gpg_binary] |
| 248 |
if keyring: |
| 249 |
cmd.append(f"--homedir={keyring}") |
| 250 |
cmd.extend(["--no-permission-warning", "--with-colons", "--quiet", "--batch", "--no-tty"]) |
| 251 |
return self.module.run_command(cmd + args, **kwargs) |
| 252 |
|
| 253 |
def pacman_key(self, args, keyring, **kwargs): |
| 254 |
return self.module.run_command([self.pacman_key_binary, "--gpgdir", keyring] + args, **kwargs) |
| 255 |
|
| 256 |
def pacman_machine_key(self, keyring): |
| 257 |
unused_rc, stdout, unused_stderr = self.gpg(["--list-secret-key"], keyring=keyring) |
| 258 |
return gpg_get_first_attr_of_kind(stdout.splitlines(), "sec", "key") |
| 259 |
|
| 260 |
def is_hexadecimal(self, string): |
| 261 |
"""Check if a given string is valid hexadecimal""" |
| 262 |
try: |
| 263 |
int(string, 16) |
| 264 |
except ValueError: |
| 265 |
return False |
| 266 |
return True |
| 267 |
|
| 268 |
def sanitise_keyid(self, keyid): |
| 269 |
"""Sanitise given key ID. |
| 270 |
|
| 271 |
Strips whitespace, uppercases all characters, and strips leading `0X`. |
| 272 |
""" |
| 273 |
sanitised_keyid = keyid.strip().upper().replace(" ", "").replace("0X", "") |
| 274 |
if len(sanitised_keyid) != self.keylength: |
| 275 |
self.module.fail_json(msg=f"key ID is not full-length: {sanitised_keyid}") |
| 276 |
if not self.is_hexadecimal(sanitised_keyid): |
| 277 |
self.module.fail_json(msg=f"key ID is not hexadecimal: {sanitised_keyid}") |
| 278 |
return sanitised_keyid |
| 279 |
|
| 280 |
def fetch_key(self, url): |
| 281 |
"""Downloads a key from url""" |
| 282 |
response, info = fetch_url(self.module, url) |
| 283 |
if info["status"] != 200: |
| 284 |
self.module.fail_json(msg=f"failed to fetch key at {url}, error was {info['msg']}") |
| 285 |
return to_native(response.read()) |
| 286 |
|
| 287 |
def recv_key(self, keyring, keyid, keyserver): |
| 288 |
"""Receives key via keyserver""" |
| 289 |
self.pacman_key(["--keyserver", keyserver, "--recv-keys", keyid], keyring=keyring, check_rc=True) |
| 290 |
|
| 291 |
def lsign_key(self, keyring, keyid): |
| 292 |
"""Locally sign key""" |
| 293 |
self.pacman_key(["--lsign-key", keyid], keyring=keyring, check_rc=True) |
| 294 |
|
| 295 |
def save_key(self, data): |
| 296 |
"Saves key data to a temporary file" |
| 297 |
tmpfd, tmpname = tempfile.mkstemp() |
| 298 |
self.module.add_cleanup_file(tmpname) |
| 299 |
tmpfile = os.fdopen(tmpfd, "w") |
| 300 |
tmpfile.write(data) |
| 301 |
tmpfile.close() |
| 302 |
return tmpname |
| 303 |
|
| 304 |
def add_key(self, keyring, keyfile, keyid, verify): |
| 305 |
"""Add key to pacman's keyring""" |
| 306 |
if verify: |
| 307 |
self.verify_keyfile(keyfile, keyid) |
| 308 |
self.pacman_key(["--add", keyfile], keyring=keyring, check_rc=True) |
| 309 |
|
| 310 |
def remove_key(self, keyring, keyid): |
| 311 |
"""Remove key from pacman's keyring""" |
| 312 |
self.pacman_key(["--delete", keyid], keyring=keyring, check_rc=True) |
| 313 |
|
| 314 |
def verify_keyfile(self, keyfile, keyid): |
| 315 |
"""Verify that keyfile matches the specified key ID""" |
| 316 |
if keyfile is None: |
| 317 |
self.module.fail_json(msg="expected a key, got none") |
| 318 |
elif keyid is None: |
| 319 |
self.module.fail_json(msg="expected a key ID, got none") |
| 320 |
|
| 321 |
rc, stdout, stderr = self.gpg( |
| 322 |
["--with-fingerprint", "--show-keys", keyfile], |
| 323 |
check_rc=True, |
| 324 |
) |
| 325 |
|
| 326 |
extracted_keyid = gpg_get_first_attr_of_kind(stdout.splitlines(), "fpr", "user_id") |
| 327 |
if extracted_keyid != keyid: |
| 328 |
self.module.fail_json(msg=f"key ID does not match. expected {keyid}, got {extracted_keyid}") |
| 329 |
|
| 330 |
def key_validity(self, keyring, keyid): |
| 331 |
"Check if the key ID is in pacman's keyring and not expired" |
| 332 |
rc, stdout, stderr = self.gpg(["--no-default-keyring", "--list-keys", keyid], keyring=keyring, check_rc=False) |
| 333 |
if rc != 0: |
| 334 |
if stderr.find("No public key") >= 0: |
| 335 |
return [] |
| 336 |
else: |
| 337 |
self.module.fail_json(msg=f"gpg returned an error: {stderr}") |
| 338 |
return gpg_get_all_attrs_of_kind(stdout.splitlines(), "uid", "is_fully_valid") |
| 339 |
|
| 340 |
def key_is_trusted(self, keyring, keyid): |
| 341 |
"""Check if key is signed and not expired.""" |
| 342 |
unused_rc, stdout, unused_stderr = self.gpg(["--check-signatures", keyid], keyring=keyring) |
| 343 |
return self.pacman_machine_key(keyring) in gpg_get_all_attrs_of_kind(stdout.splitlines(), "sig", "key") |
| 344 |
|
| 345 |
|
| 346 |
def main(): |
| 347 |
module = AnsibleModule( |
| 348 |
argument_spec=dict( |
| 349 |
id=dict(type="str", required=True), |
| 350 |
data=dict(type="str"), |
| 351 |
file=dict(type="path"), |
| 352 |
url=dict(type="str"), |
| 353 |
keyserver=dict(type="str"), |
| 354 |
verify=dict(type="bool", default=True), |
| 355 |
force_update=dict(type="bool", default=False), |
| 356 |
keyring=dict(type="path", default="/etc/pacman.d/gnupg"), |
| 357 |
ensure_trusted=dict(type="bool", default=False), |
| 358 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 359 |
), |
| 360 |
supports_check_mode=True, |
| 361 |
mutually_exclusive=(("data", "file", "url", "keyserver"),), |
| 362 |
required_if=[("state", "present", ("data", "file", "url", "keyserver"), True)], |
| 363 |
) |
| 364 |
module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"} |
| 365 |
PacmanKey(module) |
| 366 |
|
| 367 |
|
| 368 |
if __name__ == "__main__": |
| 369 |
main() |