Fix invalid-name issues. (#909)

This commit is contained in:
Felix Fontein
2025-05-30 23:06:24 +02:00
committed by GitHub
parent 31933955e3
commit 6d273bc5b7
8 changed files with 97 additions and 94 deletions

View File

@@ -380,7 +380,6 @@ disable=raw-checker-failed,
broad-exception-caught,
broad-exception-raised,
fixme,
invalid-name,
unused-argument,
# Cannot remove yet due to inadequacy of rules
inconsistent-return-statements, # doesn't notice that fail_json() does not return

View File

@@ -35,15 +35,15 @@ ASN1_STRING_REGEX = re.compile(
class TagClass(enum.Enum):
universal = 0
application = 1
context_specific = 2
private = 3
UNIVERSAL = 0
APPLICATION = 1
CONTEXT_SPECIFIC = 2
PRIVATE = 3
# Universal tag numbers that can be encoded.
class TagNumber(enum.Enum):
utf8_string = 12
UTF8_STRING = 12
def _pack_octet_integer(value: int) -> bytes:
@@ -92,22 +92,22 @@ def serialize_asn1_string_as_der(value: str) -> bytes:
# We should only do a universal type tag if not IMPLICITLY tagged or the tag class is not universal.
if not tag_type or (tag_type == "EXPLICIT" and tag_class != "U"):
b_value = pack_asn1(
tag_class=TagClass.universal,
tag_class=TagClass.UNIVERSAL,
constructed=False,
tag_number=TagNumber.utf8_string,
tag_number=TagNumber.UTF8_STRING,
b_data=b_value,
)
if tag_type:
tag_class_enum = {
"U": TagClass.universal,
"A": TagClass.application,
"P": TagClass.private,
"C": TagClass.context_specific,
"U": TagClass.UNIVERSAL,
"A": TagClass.APPLICATION,
"P": TagClass.PRIVATE,
"C": TagClass.CONTEXT_SPECIFIC,
}[tag_class]
# When adding support for more types this should be looked into further. For now it works with UTF8Strings.
constructed = tag_type == "EXPLICIT" and tag_class_enum != TagClass.universal
constructed = tag_type == "EXPLICIT" and tag_class_enum != TagClass.UNIVERSAL
b_value = pack_asn1(
tag_class=tag_class_enum,
constructed=constructed,

View File

@@ -118,15 +118,15 @@ if t.TYPE_CHECKING:
cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey,
cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey,
]
PublicKeyTypesWOEdwards = t.Union[
PublicKeyTypesWOEdwards = t.Union[ # pylint: disable=invalid-name
DHPublicKey, DSAPublicKey, EllipticCurvePublicKey, RSAPublicKey
]
PrivateKeyTypesWOEdwards = t.Union[
PrivateKeyTypesWOEdwards = t.Union[ # pylint: disable=invalid-name
DHPrivateKey, DSAPrivateKey, EllipticCurvePrivateKey, RSAPrivateKey
]
else:
PublicKeyTypesWOEdwards = None
PrivateKeyTypesWOEdwards = None
PublicKeyTypesWOEdwards = None # pylint: disable=invalid-name
PrivateKeyTypesWOEdwards = None # pylint: disable=invalid-name
CRYPTOGRAPHY_TIMEZONE = False

View File

@@ -71,12 +71,12 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
self.create_authority_key_identifier: bool = module.params[
"ownca_create_authority_key_identifier"
]
self.notBefore = get_relative_time_option(
self.not_before = get_relative_time_option(
module.params["ownca_not_before"],
input_name="ownca_not_before",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
)
self.notAfter = get_relative_time_option(
self.not_after = get_relative_time_option(
module.params["ownca_not_after"],
input_name="ownca_not_after",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
@@ -162,8 +162,8 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
cert_builder = cert_builder.subject_name(self.csr.subject)
cert_builder = cert_builder.issuer_name(self.ca_cert.subject)
cert_builder = cert_builder.serial_number(self.serial_number)
cert_builder = set_not_valid_before(cert_builder, self.notBefore)
cert_builder = set_not_valid_after(cert_builder, self.notAfter)
cert_builder = set_not_valid_before(cert_builder, self.not_before)
cert_builder = set_not_valid_after(cert_builder, self.not_after)
cert_builder = cert_builder.public_key(self.csr.public_key())
has_ski = False
for extension in self.csr.extensions:
@@ -224,7 +224,7 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
not_after: datetime.datetime | None = None,
) -> bool:
if super().needs_regeneration(
not_before=self.notBefore, not_after=self.notAfter
not_before=self.not_before, not_after=self.not_after
):
return True
@@ -283,8 +283,8 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
if self.module.check_mode:
result.update(
{
"notBefore": self.notBefore.strftime("%Y%m%d%H%M%SZ"),
"notAfter": self.notAfter.strftime("%Y%m%d%H%M%SZ"),
"notBefore": self.not_before.strftime("%Y%m%d%H%M%SZ"),
"notAfter": self.not_after.strftime("%Y%m%d%H%M%SZ"),
"serial_number": self.serial_number,
}
)

View File

@@ -64,12 +64,12 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
self.create_subject_key_identifier: t.Literal[
"create_if_not_provided", "always_create", "never_create"
] = module.params["selfsigned_create_subject_key_identifier"]
self.notBefore = get_relative_time_option(
self.not_before = get_relative_time_option(
module.params["selfsigned_not_before"],
input_name="selfsigned_not_before",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
)
self.notAfter = get_relative_time_option(
self.not_after = get_relative_time_option(
module.params["selfsigned_not_after"],
input_name="selfsigned_not_after",
with_timezone=CRYPTOGRAPHY_TIMEZONE,
@@ -124,8 +124,8 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
cert_builder = cert_builder.subject_name(self.csr.subject)
cert_builder = cert_builder.issuer_name(self.csr.subject)
cert_builder = cert_builder.serial_number(self.serial_number)
cert_builder = set_not_valid_before(cert_builder, self.notBefore)
cert_builder = set_not_valid_after(cert_builder, self.notAfter)
cert_builder = set_not_valid_before(cert_builder, self.not_before)
cert_builder = set_not_valid_after(cert_builder, self.not_after)
cert_builder = cert_builder.public_key(self.privatekey.public_key())
has_ski = False
for extension in self.csr.extensions:
@@ -168,7 +168,7 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
assert self.privatekey is not None
if super().needs_regeneration(
not_before=self.notBefore, not_after=self.notAfter
not_before=self.not_before, not_after=self.not_after
):
return True
@@ -190,8 +190,8 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
if self.module.check_mode:
result.update(
{
"notBefore": self.notBefore.strftime("%Y%m%d%H%M%SZ"),
"notAfter": self.notAfter.strftime("%Y%m%d%H%M%SZ"),
"notBefore": self.not_before.strftime("%Y%m%d%H%M%SZ"),
"notAfter": self.not_after.strftime("%Y%m%d%H%M%SZ"),
"serial_number": self.serial_number,
}
)

View File

@@ -98,20 +98,24 @@ class CertificateSigningRequestBackend(metaclass=abc.ABCMeta):
self.privatekey_content = None
self.privatekey_passphrase: str | None = module.params["privatekey_passphrase"]
self.version: t.Literal[1] = module.params["version"]
self.subjectAltName: list[str] | None = module.params["subject_alt_name"]
self.subjectAltName_critical: bool = module.params["subject_alt_name_critical"]
self.keyUsage: list[str] | None = module.params["key_usage"]
self.keyUsage_critical: bool = module.params["key_usage_critical"]
self.extendedKeyUsage: list[str] | None = module.params["extended_key_usage"]
self.extendedKeyUsage_critical: bool = module.params[
self.subject_alt_name: list[str] | None = module.params["subject_alt_name"]
self.subject_alt_name_critical: bool = module.params[
"subject_alt_name_critical"
]
self.key_usage: list[str] | None = module.params["key_usage"]
self.key_usage_critical: bool = module.params["key_usage_critical"]
self.extended_key_usage: list[str] | None = module.params["extended_key_usage"]
self.extended_key_usage_critical: bool = module.params[
"extended_key_usage_critical"
]
self.basicConstraints: list[str] | None = module.params["basic_constraints"]
self.basicConstraints_critical: bool = module.params[
self.basic_constraints: list[str] | None = module.params["basic_constraints"]
self.basic_constraints_critical: bool = module.params[
"basic_constraints_critical"
]
self.ocspMustStaple: bool = module.params["ocsp_must_staple"]
self.ocspMustStaple_critical: bool = module.params["ocsp_must_staple_critical"]
self.ocsp_must_staple: bool = module.params["ocsp_must_staple"]
self.ocsp_must_staple_critical: bool = module.params[
"ocsp_must_staple_critical"
]
self.name_constraints_permitted: list[str] = (
module.params["name_constraints_permitted"] or []
)
@@ -175,10 +179,10 @@ class CertificateSigningRequestBackend(metaclass=abc.ABCMeta):
raise CertificateSigningRequestError(str(exc)) from exc
self.using_common_name_for_san = False
if not self.subjectAltName and module.params["use_common_name_for_san"]:
if not self.subject_alt_name and module.params["use_common_name_for_san"]:
for sub in self.subject:
if sub[0] in ("commonName", "CN"):
self.subjectAltName = [f"DNS:{sub[1]}"]
self.subject_alt_name = [f"DNS:{sub[1]}"]
self.using_common_name_for_san = True
break
@@ -279,11 +283,11 @@ class CertificateSigningRequestBackend(metaclass=abc.ABCMeta):
result: dict[str, t.Any] = {
"privatekey": self.privatekey_path,
"subject": self.subject,
"subjectAltName": self.subjectAltName,
"keyUsage": self.keyUsage,
"extendedKeyUsage": self.extendedKeyUsage,
"basicConstraints": self.basicConstraints,
"ocspMustStaple": self.ocspMustStaple,
"subjectAltName": self.subject_alt_name,
"keyUsage": self.key_usage,
"extendedKeyUsage": self.extended_key_usage,
"basicConstraints": self.basic_constraints,
"ocspMustStaple": self.ocsp_must_staple,
"name_constraints_permitted": self.name_constraints_permitted,
"name_constraints_excluded": self.name_constraints_excluded,
}
@@ -390,43 +394,43 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
except ValueError as e:
raise CertificateSigningRequestError(e) from e
if self.subjectAltName:
if self.subject_alt_name:
csr = csr.add_extension(
cryptography.x509.SubjectAlternativeName(
[cryptography_get_name(name) for name in self.subjectAltName]
[cryptography_get_name(name) for name in self.subject_alt_name]
),
critical=self.subjectAltName_critical,
critical=self.subject_alt_name_critical,
)
if self.keyUsage:
params = cryptography_parse_key_usage_params(self.keyUsage)
if self.key_usage:
params = cryptography_parse_key_usage_params(self.key_usage)
csr = csr.add_extension(
cryptography.x509.KeyUsage(**params), critical=self.keyUsage_critical
cryptography.x509.KeyUsage(**params), critical=self.key_usage_critical
)
if self.extendedKeyUsage:
if self.extended_key_usage:
usages = [
cryptography_name_to_oid(usage) for usage in self.extendedKeyUsage
cryptography_name_to_oid(usage) for usage in self.extended_key_usage
]
csr = csr.add_extension(
cryptography.x509.ExtendedKeyUsage(usages),
critical=self.extendedKeyUsage_critical,
critical=self.extended_key_usage_critical,
)
if self.basicConstraints:
if self.basic_constraints:
params = {}
ca, path_length = cryptography_get_basic_constraints(self.basicConstraints)
ca, path_length = cryptography_get_basic_constraints(self.basic_constraints)
csr = csr.add_extension(
cryptography.x509.BasicConstraints(ca, path_length),
critical=self.basicConstraints_critical,
critical=self.basic_constraints_critical,
)
if self.ocspMustStaple:
if self.ocsp_must_staple:
csr = csr.add_extension(
cryptography.x509.TLSFeature(
[cryptography.x509.TLSFeatureType.status_request]
),
critical=self.ocspMustStaple_critical,
critical=self.ocsp_must_staple_critical,
)
if self.name_constraints_permitted or self.name_constraints_excluded:
@@ -566,7 +570,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
(ext for ext in extensions if isinstance(ext.value, exttype)), None
)
def _check_subjectAltName(extensions: cryptography.x509.Extensions) -> bool:
def _check_subject_alt_name(extensions: cryptography.x509.Extensions) -> bool:
current_altnames_ext = _find_extension(
extensions, cryptography.x509.SubjectAlternativeName
)
@@ -578,33 +582,33 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
altnames = (
[
to_text(cryptography_get_name(altname))
for altname in self.subjectAltName
for altname in self.subject_alt_name
]
if self.subjectAltName
if self.subject_alt_name
else []
)
if set(altnames) != set(current_altnames):
return False
if altnames and current_altnames_ext:
if current_altnames_ext.critical != self.subjectAltName_critical:
if current_altnames_ext.critical != self.subject_alt_name_critical:
return False
return True
def _check_keyUsage(extensions: cryptography.x509.Extensions) -> bool:
def _check_key_usage(extensions: cryptography.x509.Extensions) -> bool:
current_keyusage_ext = _find_extension(
extensions, cryptography.x509.KeyUsage
)
if not self.keyUsage:
if not self.key_usage:
return current_keyusage_ext is None
if current_keyusage_ext is None:
return False
params = cryptography_parse_key_usage_params(self.keyUsage)
params = cryptography_parse_key_usage_params(self.key_usage)
for param, value in params.items():
if getattr(current_keyusage_ext.value, param) != value:
return False
return current_keyusage_ext.critical == self.keyUsage_critical
return current_keyusage_ext.critical == self.key_usage_critical
def _check_extenededKeyUsage(extensions: cryptography.x509.Extensions) -> bool:
def _check_extended_key_usage(extensions: cryptography.x509.Extensions) -> bool:
current_usages_ext = _find_extension(
extensions, cryptography.x509.ExtendedKeyUsage
)
@@ -616,23 +620,23 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
usages = (
[
str(cryptography_name_to_oid(usage))
for usage in self.extendedKeyUsage
for usage in self.extended_key_usage
]
if self.extendedKeyUsage
if self.extended_key_usage
else []
)
if set(current_usages) != set(usages):
return False
if usages and current_usages_ext:
if current_usages_ext.critical != self.extendedKeyUsage_critical:
if current_usages_ext.critical != self.extended_key_usage_critical:
return False
return True
def _check_basicConstraints(extensions: cryptography.x509.Extensions) -> bool:
def _check_basic_constraints(extensions: cryptography.x509.Extensions) -> bool:
bc_ext = _find_extension(extensions, cryptography.x509.BasicConstraints)
current_ca = bc_ext.value.ca if bc_ext else False
current_path_length = bc_ext.value.path_length if bc_ext else None
ca, path_length = cryptography_get_basic_constraints(self.basicConstraints)
ca, path_length = cryptography_get_basic_constraints(self.basic_constraints)
# Check CA flag
if ca != current_ca:
return False
@@ -640,19 +644,19 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
if path_length != current_path_length:
return False
# Check criticality
if self.basicConstraints:
if self.basic_constraints:
return (
bc_ext is not None
and bc_ext.critical == self.basicConstraints_critical
and bc_ext.critical == self.basic_constraints_critical
)
return bc_ext is None
def _check_ocspMustStaple(extensions: cryptography.x509.Extensions) -> bool:
def _check_ocsp_must_staple(extensions: cryptography.x509.Extensions) -> bool:
tlsfeature_ext = _find_extension(extensions, cryptography.x509.TLSFeature)
if self.ocspMustStaple:
if self.ocsp_must_staple:
if (
not tlsfeature_ext
or tlsfeature_ext.critical != self.ocspMustStaple_critical
or tlsfeature_ext.critical != self.ocsp_must_staple_critical
):
return False
return (
@@ -661,7 +665,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
)
return tlsfeature_ext is None
def _check_nameConstraints(extensions: cryptography.x509.Extensions) -> bool:
def _check_name_constraints(extensions: cryptography.x509.Extensions) -> bool:
current_nc_ext = _find_extension(
extensions, cryptography.x509.NameConstraints
)
@@ -762,14 +766,14 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
def _check_extensions(csr: cryptography.x509.CertificateSigningRequest) -> bool:
extensions = csr.extensions
return (
_check_subjectAltName(extensions)
and _check_keyUsage(extensions)
and _check_extenededKeyUsage(extensions)
and _check_basicConstraints(extensions)
and _check_ocspMustStaple(extensions)
_check_subject_alt_name(extensions)
and _check_key_usage(extensions)
and _check_extended_key_usage(extensions)
and _check_basic_constraints(extensions)
and _check_ocsp_must_staple(extensions)
and _check_subject_key_identifier(extensions)
and _check_authority_key_identifier(extensions)
and _check_nameConstraints(extensions)
and _check_name_constraints(extensions)
and _check_crl_distribution_points(extensions)
)

View File

@@ -39,7 +39,7 @@ if t.TYPE_CHECKING:
DateFormatStr = t.Literal["human_readable", "openssh"]
DateFormatInt = t.Literal["timestamp"]
else:
KeyType = None
KeyType = None # pylint: disable=invalid-name
# Protocol References

View File

@@ -226,7 +226,7 @@ def is_parent(
module.fail_json(msg=f"Unknown error on signature validation: {e}")
def parse_PEM_list(
def parse_pem_list(
module: AnsibleModule,
text: str,
source: str | os.PathLike,
@@ -250,7 +250,7 @@ def parse_PEM_list(
return result
def load_PEM_list(
def load_pem_list(
module: AnsibleModule, path: str | os.PathLike, fail_on_error: bool = True
) -> list[Certificate]:
"""
@@ -258,7 +258,7 @@ def load_PEM_list(
"""
try:
with open(path, "rb") as f:
return parse_PEM_list(
return parse_pem_list(
module,
f.read().decode("utf-8"),
source=path,
@@ -287,7 +287,7 @@ class CertificateSet:
self.certificate_by_cert: dict[cryptography.x509.Certificate, Certificate] = {}
def _load_file(self, path: str | os.PathLike) -> None:
certs = load_PEM_list(self.module, path, fail_on_error=False)
certs = load_pem_list(self.module, path, fail_on_error=False)
for cert in certs:
self.certificates.add(cert)
if cert.cert.subject not in self.certificates_by_issuer:
@@ -358,7 +358,7 @@ def main() -> t.NoReturn:
)
# Load chain
chain = parse_PEM_list(module, module.params["input_chain"], source="input chain")
chain = parse_pem_list(module, module.params["input_chain"], source="input chain")
if len(chain) == 0:
module.fail_json(msg="Input chain must contain at least one certificate")