Debian Codegraph @

lib/ansible/modules/rpm_key.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Ansible module to import third party repo keys to your rpm db
4 # Copyright: (c) 2013, Héctor Acosta <[email protected]>
5
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import annotations
9
10
11 DOCUMENTATION = """
12 ---
13 module: rpm_key
14 author:
15 - Hector Acosta (@hacosta) <[email protected]>
16 short_description: Adds or removes a gpg key from the rpm db
17 description:
18 - Adds or removes C(rpm --import) a gpg key to your rpm database.
19 version_added: "1.3"
20 options:
21 key:
22 description:
23 - Key that will be modified. Can be a url, a file on the managed node, or a keyid if the key
24 already exists in the database.
25 - This can also be the fingerprint when attempting to delete an already installed key.
26 type: str
27 required: true
28 state:
29 description:
30 - If the key will be imported or removed from the rpm db.
31 type: str
32 default: present
33 choices: [ absent, present ]
34 validate_certs:
35 description:
36 - If V(false) and the O(key) is a url starting with V(https), SSL certificates will not be validated.
37 - This should only be used on personally controlled sites using self-signed certificates.
38 type: bool
39 default: 'yes'
40 fingerprint:
41 description:
42 - The long-form fingerprint of the key being imported.
43 - This will be used to verify the specified key.
44 type: list
45 elements: str
46 version_added: 2.9
47 extends_documentation_fragment:
48 - action_common_attributes
49 attributes:
50 check_mode:
51 support: full
52 diff_mode:
53 support: none
54 platform:
55 platforms: rhel
56 """
57
58 EXAMPLES = """
59 - name: Import a key from a url
60 ansible.builtin.rpm_key:
61 state: present
62 key: http://apt.sw.be/RPM-GPG-KEY.dag.txt
63
64 - name: Import a key from a file
65 ansible.builtin.rpm_key:
66 state: present
67 key: /path/to/key.gpg
68
69 - name: Ensure a key is not present in the db
70 ansible.builtin.rpm_key:
71 state: absent
72 key: DEADB33F
73
74 - name: Verify the key, using a fingerprint, before import
75 ansible.builtin.rpm_key:
76 key: /path/to/RPM-GPG-KEY.dag.txt
77 fingerprint: EBC6 E12C 62B1 C734 026B 2122 A20E 5214 6B8D 79E6
78
79 - name: Verify the key, using multiple fingerprints, before import
80 ansible.builtin.rpm_key:
81 key: /path/to/RPM-GPG-KEY.dag.txt
82 fingerprint:
83 - EBC6 E12C 62B1 C734 026B 2122 A20E 5214 6B8D 79E6
84 - 19B7 913E 6284 8E3F 4D78 D6B4 ECD9 1AB2 2EB6 8D86
85 """
86
87 RETURN = r"""#"""
88
89 import ctypes
90 import ctypes.util
91 import hashlib
92 import re
93 import os.path
94 import tempfile
95 import typing as _t
96
97 # import module snippets
98 from ansible.module_utils.basic import AnsibleModule
99 from ansible.module_utils.urls import fetch_url, is_fetch_success, mask_url
100 from ansible.module_utils.compat.version import LooseVersion
101 from ansible.module_utils.common.text.converters import to_native
102
103 # Type alias for ctypes pointer to uint8 array (packet data)
104 # Using Any here because ctypes._Pointer is private, but documenting the actual type
105 PktPointer = _t.Any # Actually: ctypes.POINTER(ctypes.c_uint8)
106
107
108 class LibRPM:
109 """
110 Wrapper for librpm PGP key functions.
111
112 The APIs in librpm vary across different versions. Since this module must work on a variety of
113 systems, we are extremely limited in the API calls that we can guarantee will be available.
114 """
115
116 # Constants
117 PGPTAG_PUBLIC_KEY = 6
118 PGPTAG_PUBLIC_SUBKEY = 14
119
120 def __init__(self) -> None:
121 # Load the librpm library
122 if not (lib_path := ctypes.util.find_library('rpm')):
123 raise ImportError("Error: Could not find librpm library")
124
125 self._lib = ctypes.CDLL(lib_path)
126 self._libc = ctypes.CDLL(None)
127
128 # void free(void *ptr)
129 self._libc.free.argtypes = [ctypes.c_void_p]
130 self._libc.free.restype = None
131
132 # pgpArmor pgpParsePkts(const char *armor, uint8_t **pkt, size_t *pktlen)
133 self._lib.pgpParsePkts.argtypes = [
134 ctypes.c_char_p,
135 ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8)),
136 ctypes.POINTER(ctypes.c_size_t)
137 ]
138 self._lib.pgpParsePkts.restype = ctypes.c_int
139
140 # Identify the version of the RPM library
141 _lib_rpmversion = ctypes.c_char_p.in_dll(self._lib, "RPMVERSION")
142 self._rpmversion = _lib_rpmversion.value.decode()
143
144 @property
145 def using_librpm6(self) -> bool:
146 """
147 Check if the librpm version in use is at least version 6.0.0.
148
149 RPM version 6.0.0 and higher uses fingerprints instead of short key ID everywhere. This changes
150 how we must approach certain operations, such as key deletion from the rpmdb.
151 """
152 if LooseVersion(self._rpmversion) >= LooseVersion('6.0.0'):
153 return True
154 return False
155
156 def _parse_armor(self, armor: str) -> tuple[PktPointer | None, int]:
157 """
158 Parse ASCII armored PGP data using pgpParsePkts().
159 Returns (pkt, pktlen) tuple or (None, 0) on error.
160 """
161 pkt = ctypes.POINTER(ctypes.c_uint8)()
162 pktlen = ctypes.c_size_t()
163
164 if not armor.endswith("\n"):
165 armor += "\n"
166
167 armor_bytes = armor.encode()
168 result = self._lib.pgpParsePkts(armor_bytes, ctypes.byref(pkt), ctypes.byref(pktlen))
169
170 if result < 0 or not pkt:
171 return None, 0
172
173 return pkt, pktlen.value
174
175 def _parse_packet_header(self, pkt: PktPointer, offset: int, pktlen: int) -> tuple[int | None, int, int]:
176 """
177 Parse a PGP packet header to get tag and packet length.
178 Returns (tag, body_length, header_length) or (None, 0, 0) on error.
179
180 Per RFC 9580 - Section 4.2: Packet Headers
181 https://www.rfc-editor.org/rfc/rfc9580.html#name-packet-headers
182 """
183 if offset >= pktlen:
184 return None, 0, 0
185
186 tag_byte = pkt[offset]
187
188 # Check if it's a new format packet (bit 6 set)
189 if tag_byte & 0x40:
190 # New format
191 tag = tag_byte & 0x3f # bits 0-5 are packet type ID
192 offset += 1
193
194 if offset >= pktlen:
195 return None, 0, 0
196
197 first_len_byte = pkt[offset]
198
199 if first_len_byte < 192:
200 # One-octet length
201 return tag, first_len_byte, 2
202 elif first_len_byte < 224:
203 # Two-octet length
204 if offset + 1 >= pktlen:
205 return None, 0, 0
206 length = ((first_len_byte - 192) << 8) + pkt[offset + 1] + 192
207 return tag, length, 3
208 elif first_len_byte == 255:
209 # Five-octet length
210 if offset + 4 >= pktlen:
211 return None, 0, 0
212 length = (pkt[offset + 1] << 24) | (pkt[offset + 2] << 16) | \
213 (pkt[offset + 3] << 8) | pkt[offset + 4]
214 return tag, length, 6
215 else:
216 # Partial body length (not supported here)
217 return None, 0, 0
218 else:
219 # Old format
220 tag = (tag_byte >> 2) & 0x0f
221 length_type = tag_byte & 0x03
222
223 if length_type == 0:
224 # One-octet length
225 if offset + 1 >= pktlen:
226 return None, 0, 0
227 return tag, pkt[offset + 1], 2
228 elif length_type == 1:
229 # Two-octet length
230 if offset + 2 >= pktlen:
231 return None, 0, 0
232 length = (pkt[offset + 1] << 8) | pkt[offset + 2]
233 return tag, length, 3
234 elif length_type == 2:
235 # Four-octet length
236 if offset + 4 >= pktlen:
237 return None, 0, 0
238 length = (pkt[offset + 1] << 24) | (pkt[offset + 2] << 16) | \
239 (pkt[offset + 3] << 8) | pkt[offset + 4]
240 return tag, length, 5
241 else:
242 # Indeterminate length (not supported)
243 return None, 0, 0
244
245 def _find_key_packets(self, pkt: PktPointer, pktlen: int) -> list[tuple[int, int]]:
246 """
247 Walk the packet stream and find all PGPTAG_PUBLIC_KEY and PGPTAG_PUBLIC_SUBKEY packets.
248 Returns list of (offset, total_packet_length) tuples.
249 """
250 key_packets: list[tuple[int, int]] = []
251 offset = 0
252
253 while offset < pktlen:
254 tag, body_len, header_len = self._parse_packet_header(pkt, offset, pktlen)
255
256 if tag is None:
257 break
258
259 if tag in (self.PGPTAG_PUBLIC_KEY, self.PGPTAG_PUBLIC_SUBKEY):
260 # Found a key packet
261 total_len = header_len + body_len
262 key_packets.append((offset, total_len))
263
264 # Move to next packet
265 offset += header_len + body_len
266
267 return key_packets
268
269 def _get_key_version(self, pkt: PktPointer, offset: int, pktlen: int) -> int | None:
270 """
271 Get the version byte from a key packet.
272 Returns version number (4 or 6) or None on error.
273 """
274 tag, dummy, header_len = self._parse_packet_header(pkt, offset, pktlen)
275 if tag is None:
276 return None
277
278 # Extract packet body (skip the packet header)
279 body_offset = offset + header_len
280 if body_offset >= pktlen:
281 return None
282
283 # First byte of body is the version
284 return pkt[body_offset]
285
286 def _compute_v4_fingerprint(self, pkt: PktPointer, offset: int, pktlen: int) -> str | None:
287 """
288 Compute V4 fingerprint from packet data.
289 For V4 keys, fingerprint = SHA-1(0x99 || 2-byte-length || packet_body)
290 Per RFC 4880 Section 12.2
291 """
292 tag, body_len, header_len = self._parse_packet_header(pkt, offset, pktlen)
293
294 if tag is None:
295 return None
296
297 # Extract packet body (skip the packet header)
298 body_offset = offset + header_len
299 if body_offset + body_len > pktlen:
300 return None
301
302 # Check if it's a V4 key (first byte of body should be 0x04)
303 if pkt[body_offset] != 0x04:
304 return None
305
306 # Build the data for fingerprint: 0x99 || 2-byte length || body
307 fp_data = bytearray()
308 fp_data.append(0x99) # V4 public key packet tag
309 fp_data.append((body_len >> 8) & 0xFF) # Length high byte
310 fp_data.append(body_len & 0xFF) # Length low byte
311
312 # Append the packet body
313 for i in range(body_len):
314 fp_data.append(pkt[body_offset + i])
315
316 # Compute SHA-1 hash
317 return hashlib.sha1(fp_data).hexdigest().upper()
318
319 def _compute_v6_fingerprint(self, pkt: PktPointer, offset: int, pktlen: int) -> str | None:
320 """
321 Compute V6 fingerprint from packet data.
322 For V6 keys, fingerprint = SHA-256(0x9B || 4-byte-length || packet_body)
323 Per RFC 9580 Section 5.5.4
324 """
325 tag, body_len, header_len = self._parse_packet_header(pkt, offset, pktlen)
326
327 if tag is None:
328 return None
329
330 # Extract packet body (skip the packet header)
331 body_offset = offset + header_len
332 if body_offset + body_len > pktlen:
333 return None
334
335 # Check if it's a V6 key (first byte of body should be 0x06)
336 if pkt[body_offset] != 0x06:
337 return None
338
339 # Build the data for fingerprint: 0x9B || 4-byte length || body
340 fp_data = bytearray()
341 fp_data.append(0x9B) # V6 public key packet tag
342 fp_data.append((body_len >> 24) & 0xFF) # Length byte 1 (MSB)
343 fp_data.append((body_len >> 16) & 0xFF) # Length byte 2
344 fp_data.append((body_len >> 8) & 0xFF) # Length byte 3
345 fp_data.append(body_len & 0xFF) # Length byte 4 (LSB)
346
347 # Append the packet body
348 for i in range(body_len):
349 fp_data.append(pkt[body_offset + i])
350
351 # Compute SHA-256 hash
352 return hashlib.sha256(fp_data).hexdigest().upper()
353
354 def identify_keys(self, armor: str) -> list[dict[str, str]]:
355 """Return a list of dicts with key ID (8-byte) and fingerprint for the primary key and each subkey"""
356 key_info: list[dict[str, str]] = []
357
358 pkt, pktlen = self._parse_armor(armor)
359 if not pkt:
360 raise Exception("Unable to parse PGP key armor")
361
362 # Find all key packets in the stream and compute their fingerprints.
363 key_packets = self._find_key_packets(pkt, pktlen)
364
365 for offset, dummy in key_packets:
366 # Detect key version
367 version = self._get_key_version(pkt, offset, pktlen)
368
369 if version == 0x04:
370 # V4 key
371 computed_fp = self._compute_v4_fingerprint(pkt, offset, pktlen)
372 if computed_fp:
373 # V4: Key ID is the last 8 bytes (16 hex chars) of the fingerprint
374 keyid_from_fp = computed_fp[-16:]
375 key_info.append({'keyid': keyid_from_fp, 'fingerprint': computed_fp})
376 elif version == 0x06:
377 # V6 key
378 computed_fp = self._compute_v6_fingerprint(pkt, offset, pktlen)
379 if computed_fp:
380 # V6: Key ID is the first 8 bytes (16 hex chars) of the fingerprint
381 keyid_from_fp = computed_fp[:16]
382 key_info.append({'keyid': keyid_from_fp, 'fingerprint': computed_fp})
383 else:
384 raise Exception(f"Unhandled key version {version:#04x}")
385
386 self._libc.free(pkt)
387
388 return key_info
389
390 def get_key_ids_from_armor(self, armor: str) -> list[str]:
391 """
392 Get the key IDs from the primary PGP key, and all subkeys of that key, from the ASCII armored key.
393
394 'armor' is expected to be a single ASCII armored PGP key (v4 or v6). The primary key should be the
395 first item in the results, followed by its subkeys. Returned key IDs are 8-byte (16 hex characters)
396 in length. This must be accounted for if comparing against the short key ID (4-bytes).
397 """
398 return [key['keyid'] for key in self.identify_keys(armor)]
399
400 def get_fingerprints_from_armor(self, armor: str) -> list[str]:
401 """
402 Get the fingerprints from the primary PGP key, and all subkeys of that key, from the ASCII armored key.
403
404 'armor' is expected to be a single ASCII armored PGP key (v4 or v6). The primary key should be the
405 first item in the results, followed by its subkeys.
406 """
407 return [key['fingerprint'] for key in self.identify_keys(armor)]
408
409
410 def is_pubkey(string: str) -> bool:
411 """Verifies if string is a pubkey"""
412 pgp_regex = ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*"
413 return bool(re.match(pgp_regex, to_native(string, errors='surrogate_or_strict'), re.DOTALL))
414
415
416 class RpmKey(object):
417
418 def __init__(self, module: AnsibleModule) -> None:
419 # If the key is a url, we need to check if it's present to be idempotent,
420 # to do that, we need to check the keyid, which we can get from the armor.
421 keyfile = None
422 should_cleanup_keyfile = False
423 self.module = module
424 self.rpm = self.module.get_bin_path('rpm', True)
425 self.rpmkeys = self.module.get_bin_path('rpmkeys', True)
426 state = module.params['state']
427 key = module.params['key']
428 fingerprint = module.params['fingerprint']
429 fingerprints = set()
430
431 if fingerprint:
432 if not isinstance(fingerprint, list):
433 fingerprint = [fingerprint]
434 fingerprints = set(f.replace(' ', '').upper() for f in fingerprint)
435
436 self.librpm = LibRPM()
437
438 if '://' in key:
439 keyfile = self.fetch_key(key)
440 keyid = self.getkeyid(keyfile)
441 should_cleanup_keyfile = True
442 elif self.is_keyid(key):
443 keyid = key
444 elif os.path.isfile(key):
445 keyfile = key
446 keyid = self.getkeyid(keyfile)
447 else:
448 self.module.fail_json(msg="Not a valid key %s" % key)
449 keyid = self.normalize_keyid(keyid)
450
451 self.installed_keys = self.get_installed_keys()
452
453 if state == 'present':
454 if self.is_key_imported(keyid):
455 module.exit_json(changed=False)
456 else:
457 if not keyfile:
458 self.module.fail_json(msg="When importing a key, a valid file must be given")
459 if fingerprints:
460 keyfile_fingerprints = self.getfingerprints(keyfile)
461 if not fingerprints.issubset(keyfile_fingerprints):
462 self.module.fail_json(
463 msg=("The specified fingerprint, '%s', "
464 "does not match any key fingerprints in '%s'") % (fingerprints, keyfile_fingerprints)
465 )
466 self.import_key(keyfile)
467 if should_cleanup_keyfile:
468 self.module.cleanup(keyfile)
469 module.exit_json(changed=True)
470 else:
471 if self.is_key_imported(keyid):
472 self.drop_key(keyid)
473 module.exit_json(changed=True)
474 else:
475 module.exit_json(changed=False)
476
477 def fetch_key(self, url: str) -> str:
478 """Downloads a key from url, returns a valid path to a gpg key"""
479 rsp, info = fetch_url(self.module, url)
480
481 if not is_fetch_success(info):
482 self.module.fail_json(msg="failed to fetch key at %s , error was: %s" % (mask_url(url), info['msg']))
483
484 key = rsp.read()
485 if not is_pubkey(key):
486 self.module.fail_json(msg="Not a public key: %s" % mask_url(url))
487 tmpfd, tmpname = tempfile.mkstemp()
488 self.module.add_cleanup_file(tmpname)
489 with os.fdopen(tmpfd, "w+b") as tmpfile:
490 tmpfile.write(key)
491 return tmpname
492
493 def normalize_keyid(self, keyid: str) -> str:
494 """Ensure a keyid doesn't have a leading 0x, has leading or trailing whitespace, and make sure is uppercase"""
495 ret = keyid.strip().upper()
496 if ret.startswith('0x'):
497 return ret[2:]
498 elif ret.startswith('0X'):
499 return ret[2:]
500 else:
501 return ret
502
503 def getkeyid(self, keyfile: str) -> str:
504 with open(keyfile, "r") as key_fd:
505 key_ids = self.librpm.get_key_ids_from_armor(key_fd.read())
506 if not key_ids:
507 self.module.fail_json(msg="Failed to get keyid")
508 return key_ids[0]
509
510 def getfingerprints(self, keyfile: str) -> frozenset[str]:
511 with open(keyfile, "r") as key_fd:
512 fingerprints = self.librpm.get_fingerprints_from_armor(key_fd.read())
513 if not fingerprints:
514 self.module.fail_json(msg="Failed to get fingerprint")
515 return frozenset(fingerprints)
516
517 def is_keyid(self, keystr: str) -> re.Match[str] | None:
518 """
519 Verifies if a key, as provided by the user, is a key ID.
520
521 Note that this allows the short form of the key ID (4-bytes, or 8 hex characters), used in older
522 versions of RPM, while a full key ID is 8-bytes, or 16 hex characters.
523 """
524 keystr = keystr.replace(' ', '')
525 return re.match('(0x)?[0-9a-f]{8}', keystr, flags=re.IGNORECASE)
526
527 def execute_command(self, cmd: str | list[str]) -> tuple[str, str]:
528 rc, stdout, stderr = self.module.run_command(cmd, use_unsafe_shell=True)
529 if rc != 0:
530 self.module.fail_json(msg=stderr)
531 return stdout, stderr
532
533 def get_installed_keys(self) -> list[dict[str, str]]:
534 """
535 Get the key ID and fingerprint for every key installed on the system.
536
537 This will grab the armor string for every key reported from `rpm -q gpg-pubkey` and parse
538 it to obtain the key ID and fingerprint, including subkeys.
539 """
540 installed_keys = []
541
542 cmd = self.rpm + ' -q gpg-pubkey'
543 rc, stdout, stderr = self.module.run_command(cmd)
544 if rc != 0: # No key is installed on system
545 return []
546 cmd += ' --qf "%{description}"'
547 stdout, stderr = self.execute_command(cmd)
548
549 # Split the content into individual key blocks
550 key_blocks = []
551 current_block = []
552 in_key_block = False
553
554 for line in stdout.splitlines():
555 if line.strip() == '-----BEGIN PGP PUBLIC KEY BLOCK-----':
556 in_key_block = True
557 current_block = [line]
558 elif line.strip() == '-----END PGP PUBLIC KEY BLOCK-----':
559 current_block.append(line)
560 key_blocks.append('\n'.join(current_block))
561 current_block = []
562 in_key_block = False
563 elif in_key_block:
564 current_block.append(line)
565
566 for armor_string in key_blocks:
567 installed_keys.extend(self.librpm.identify_keys(armor_string))
568
569 return installed_keys
570
571 def is_key_imported(self, keyid: str) -> bool:
572 """Check the supplied key ID value against the currently installed keys."""
573 keyid_len = len(keyid)
574 if keyid in [k['keyid'][-keyid_len:] for k in self.installed_keys]:
575 return True
576
577 # Allow the user supplied key to also be a fingerprint
578 if keyid in [f['fingerprint'] for f in self.installed_keys]:
579 return True
580
581 return False
582
583 def import_key(self, keyfile: str) -> None:
584 if not self.module.check_mode:
585 self.execute_command([self.rpm, '--import', keyfile])
586
587 def _drop_key_rpm6(self, keyid: str) -> None:
588 """
589 Remove the key with the given key ID from the keyring using RPM 6+ method.
590
591 RPM version 6+ uses fingerprints and the 'rpmkeys --delete' command.
592 """
593 fingerprints = []
594 keyid_len = len(keyid)
595
596 for installed in self.installed_keys:
597 if keyid == installed['keyid'][-keyid_len:]:
598 fingerprints.append(installed['fingerprint'])
599 # We allow the user supplied 'key' to also be the full fingerprint.
600 elif keyid == installed['fingerprint']:
601 fingerprints.append(installed['fingerprint'])
602
603 if not fingerprints:
604 self.module.fail_json(msg=f"Supplied key ID {keyid} is not installed.")
605 elif len(fingerprints) == 1:
606 self.execute_command([self.rpmkeys, '--delete', fingerprints[0]])
607 else:
608 self.module.fail_json(msg=f"Supplied key ID {keyid} matches more than one fingerprint. Try using the fingerprint instead.")
609
610 def _drop_key_rpm4(self, keyid: str) -> None:
611 """
612 Remove the key with the given key ID from the keyring using RPM 4 method.
613
614 Older RPM versions use short form key ID (4-bytes) and 'rpm --erase' command.
615 """
616 # If keyid is actually a fingerprint, we need to get the associated key ID and use it.
617 for installed in self.installed_keys:
618 if keyid == installed['fingerprint']:
619 keyid = installed['keyid']
620 break
621
622 self.execute_command([self.rpm, '--erase', '--allmatches', "gpg-pubkey-%s" % keyid[-8:].lower()])
623
624 def drop_key(self, keyid: str) -> None:
625 """Remove the key with the given key ID from the keyring."""
626 if not self.module.check_mode:
627 if self.librpm.using_librpm6:
628 self._drop_key_rpm6(keyid)
629 else:
630 self._drop_key_rpm4(keyid)
631
632
633 def main():
634 module = AnsibleModule(
635 argument_spec=dict(
636 state=dict(type='str', default='present', choices=['absent', 'present']),
637 key=dict(type='str', required=True, no_log=False),
638 fingerprint=dict(type='list', elements='str'),
639 validate_certs=dict(type='bool', default=True),
640 ),
641 supports_check_mode=True,
642 )
643
644 RpmKey(module)
645
646
647 if __name__ == '__main__':
648 main()