Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/pem.py

raw
1 # Copyright (c) 2019, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import typing as t
11
12 PEM_START = "-----BEGIN "
13 PEM_END_START = "-----END "
14 PEM_END = "-----"
15 PKCS8_PRIVATEKEY_NAMES = ("PRIVATE KEY", "ENCRYPTED PRIVATE KEY")
16 PKCS1_PRIVATEKEY_SUFFIX = " PRIVATE KEY"
17
18
19 def identify_pem_format(content: bytes, *, encoding: str = "utf-8") -> bool:
20 """Given the contents of a binary file, tests whether this could be a PEM file."""
21 try:
22 first_pem = extract_first_pem(content.decode(encoding))
23 if first_pem is None:
24 return False
25 lines = first_pem.splitlines(False)
26 if (
27 lines[0].startswith(PEM_START)
28 and lines[0].endswith(PEM_END)
29 and len(lines[0]) > len(PEM_START) + len(PEM_END)
30 ):
31 return True
32 except UnicodeDecodeError:
33 pass
34 return False
35
36
37 def identify_private_key_format(
38 content: bytes, *, encoding: str = "utf-8"
39 ) -> t.Literal["raw", "pkcs1", "pkcs8", "unknown-pem"]:
40 """Given the contents of a private key file, identifies its format."""
41 # See https://github.com/openssl/openssl/blob/master/crypto/pem/pem_pkey.c#L40-L85
42 # (PEM_read_bio_PrivateKey)
43 # and https://github.com/openssl/openssl/blob/master/include/openssl/pem.h#L46-L47
44 # (PEM_STRING_PKCS8, PEM_STRING_PKCS8INF)
45 try:
46 first_pem = extract_first_pem(content.decode(encoding))
47 if first_pem is None:
48 return "raw"
49 lines = first_pem.splitlines(False)
50 if (
51 lines[0].startswith(PEM_START)
52 and lines[0].endswith(PEM_END)
53 and len(lines[0]) > len(PEM_START) + len(PEM_END)
54 ):
55 name = lines[0][len(PEM_START) : -len(PEM_END)]
56 if name in PKCS8_PRIVATEKEY_NAMES:
57 return "pkcs8"
58 if len(name) > len(PKCS1_PRIVATEKEY_SUFFIX) and name.endswith(
59 PKCS1_PRIVATEKEY_SUFFIX
60 ):
61 return "pkcs1"
62 return "unknown-pem"
63 except UnicodeDecodeError:
64 pass
65 return "raw"
66
67
68 def split_pem_list(text: str, *, keep_inbetween: bool = False) -> list[str]:
69 """
70 Split concatenated PEM objects into a list of strings, where each is one PEM object.
71 """
72 result = []
73 current: list[str] | None = [] if keep_inbetween else None
74 for line in text.splitlines(True):
75 if line.strip():
76 if not keep_inbetween and line.startswith("-----BEGIN "):
77 current = []
78 if current is not None:
79 current.append(line)
80 if line.startswith("-----END "):
81 result.append("".join(current))
82 current = [] if keep_inbetween else None
83 return result
84
85
86 def extract_first_pem(text: str) -> str | None:
87 """
88 Given one PEM or multiple concatenated PEM objects, return only the first one, or None if there is none.
89 """
90 all_pems = split_pem_list(text)
91 if not all_pems:
92 return None
93 return all_pems[0]
94
95
96 def _extract_type(line: str, *, start: str = PEM_START) -> str | None:
97 if not line.startswith(start):
98 return None
99 if not line.endswith(PEM_END):
100 return None
101 return line[len(start) : -len(PEM_END)]
102
103
104 def extract_pem(content: str, *, strict: bool = False) -> tuple[str, str]:
105 lines = content.splitlines()
106 if len(lines) < 3:
107 raise ValueError(f"PEM must have at least 3 lines, have only {len(lines)}")
108 header_type = _extract_type(lines[0])
109 if header_type is None:
110 raise ValueError(
111 f"First line is not of format {PEM_START}...{PEM_END}: {lines[0]!r}"
112 )
113 footer_type = _extract_type(lines[-1], start=PEM_END_START)
114 if strict:
115 if header_type != footer_type:
116 raise ValueError(
117 f"Header type ({header_type}) is different from footer type ({footer_type})"
118 )
119 for idx, line in enumerate(lines[1:-2]):
120 if len(line) != 64:
121 raise ValueError(f"Line {idx} has length {len(line)} instead of 64")
122 if not (0 < len(lines[-2]) <= 64):
123 raise ValueError(
124 f"Last line has length {len(lines[-2])}, should be in (0, 64]"
125 )
126 return header_type, "".join(lines[1:-1])
127
128
129 __all__ = (
130 "PEM_END",
131 "PEM_END_START",
132 "PEM_START",
133 "PKCS1_PRIVATEKEY_SUFFIX",
134 "PKCS8_PRIVATEKEY_NAMES",
135 "extract_first_pem",
136 "extract_pem",
137 "identify_pem_format",
138 "identify_private_key_format",
139 "split_pem_list",
140 )