HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.109.1.lve.el8.x86_64 #1 SMP Thu Mar 5 20:23:46 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.30
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/__pycache__/x509_v2.cpython-310.pyc
o

�N�gC,�@s�dZddlZddlZddlZddlZddlZddlZddlZddl	m	Z	m
Z
mZzddlm
ZddlmZmZddlmm
ZdZWneyNdZYnwddlZddlZddlZddlmZmZddlmZe� e!�Z"d	Z#d
d�Z$										dZd
d�Z%	d[dd�Z&	d\dd�Z'								d]dd�Z(									d^dd�Z)d_dd�Z*					d`dd�Z+d_dd�Z,							dadd �Z-					dbd!d"�Z.dcd#d$�Z/d%d&�Z0d'd(�Z1ddd)d*�Z2ddd+d,�Z3d[d-d.�Z4ddd/d0�Z5d1d2�Z6d3d4�Z7d5d6�Z8d7d8�Z9	ded9d:�Z:ded;d<�Z;d=d>�Z<ddd?d@�Z=	d[dAdB�Z>dCdD�Z?dfdEdF�Z@dGdH�ZAdddIdJ�ZBdgdKdL�ZCdMdN�ZDdOdP�ZEdhdRdS�ZFdTdU�ZGdVdW�ZHdXdY�ZIdS)ia<
Manage X.509 certificates
=========================

:depends: cryptography

.. versionadded:: 3006.0

    This module represents a complete rewrite of the original ``x509`` modules
    and is named ``x509_v2`` since it introduces breaking changes.


.. note::

    * PKCS12-related operations require at least cryptography release 36.
    * PKCS12-related operations with Edwards-curve keys require at least cryptography release 37.
    * PKCS7-related operations require at least cryptography release 37.


Configuration
-------------
Explicit activation
~~~~~~~~~~~~~~~~~~~
Since this module uses the same virtualname as the previous ``x509`` modules,
but is incompatible with them, it needs to be explicitly activated on each
minion by including the following line in the minion configuration:

.. code-block:: yaml

    # /etc/salt/minion.d/x509.conf

    features:
      x509_v2: true

Peer communication
~~~~~~~~~~~~~~~~~~
To be able to remotely sign certificates, it is required to configure the Salt
master to allow :term:`Peer Communication`:

.. code-block:: yaml

    # /etc/salt/master.d/peer.conf

    peer:
      .*:
        - x509.sign_remote_certificate

In order for the :term:`Compound Matcher` to work with restricting signing
policies to a subset of minions, in addition calls to :py:func:`match.compound <salt.modules.match.compound>`
by the minion acting as the CA must be permitted:

.. code-block:: yaml

    # /etc/salt/master.d/peer.conf

    peer:
      .*:
        - x509.sign_remote_certificate

      ca_server:
        - match.compound

.. note::

    Compound matching in signing policies currently has security tradeoffs since the
    CA server queries the requesting minion itself if it matches, not the Salt master.
    It is recommended to rely on glob matching only.

Signing policies
~~~~~~~~~~~~~~~~
In addition, the minion representing the CA needs to have at least one
signing policy configured, remote calls not referencing one are always
rejected.

The parameters specified in this signing policy override any
parameters passed from the minion requesting the certificate. It can be
configured in the CA minion's pillar, which takes precedence, or any
location :py:func:`config.get <salt.modules.config.get>` looks up in.
Signing policies are defined under ``x509_signing_policies``.

You can restrict which minions can request a certificate under a configured
signing policy by specifying a matcher in ``minions``. This can be a glob
or compound matcher (for the latter, see the notes above).

.. code-block:: yaml

    x509_signing_policies:
      www:
        - minions: 'www*'
        - signing_private_key: /etc/pki/ca.key
        - signing_cert: /etc/pki/ca.crt
        - C: US
        - ST: Utah
        - L: Salt Lake City
        - basicConstraints: "critical, CA:false"
        - keyUsage: "critical, cRLSign, keyCertSign"
        - subjectKeyIdentifier: hash
        - authorityKeyIdentifier: keyid,issuer:always
        - days_valid: 90
        - copypath: /etc/pki/issued_certs/


.. note::

    The following semantics are applied regarding the order of preference
    for specifying the subject name:

    * If neither ``subject`` nor any name attributes (like ``CN``) are part of the policy,
      issued certificates can contain any requested ones.
    * If any name attributes are specified in the signing policy, ``subject`` contained
      in requests is ignored.
    * If ``subject`` is specified in the signing policy, any name attributes are ignored.
      If the request contains the same data type for ``subject`` as the signing policy
      (for dicts and lists, and only then), merging is performed, otherwise ``subject``
      is taken from the signing policy. Dicts are merged and list items are appended,
      with the items taken from the signing policy having priority.


Breaking changes versus the previous ``x509`` modules
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* The output format has changed for all ``read_*`` functions as well as the state return dict.
* The formatting of some extension definitions might have changed, but should
  be stable for most basic use cases.
* The default ordering of RDNs/Name Attributes in the subject's Distinguished Name
  has been adapted to industry standards. This might cause a reissuance
  during the first state run.
* For ``x509.private_key_managed``, the file mode defaults to ``0400``. This should
  be considered a bug fix because writing private keys with world-readable
  permissions by default is a security issue.

Note that when a ``ca_server`` is involved, both peers must use the updated module version.

.. _x509-setup:
�N)�datetime�	timedelta�timezone)�hashes�
serializationTF)�CommandExecutionError�SaltInvocationError)�OrderedDict�x509cCs"tsdSt�di��d�sdStS)N)FzCould not load cryptographyZfeaturesZx509_v2)Fz�x509_v2 needs to be explicitly enabled by setting `x509_v2: true` in the minion configuration value `features` until Salt 3008 (Argon).)�HAS_CRYPTOGRAPHY�__opts__�get�__virtualname__�rr�H/opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/x509_v2.py�__virtual__�s
r�pemc

Ks0d|
vrtjj�dd�|
�d�|
d<hd��|
�}|r$tjj�|d�t�|
�}
d|
vrId|
vrIztjj�dd�d	|
d<Wn	t	yHYnw|d
vrUt
d|�d���|
�dd
���dvrit
d|
d�d���|dkrs|rst
d��|dkrd|
vrt
d��d|
vr�|s�t
d��|r�|s�td|�r�d|�d�S|r�|dur�t
d��t||fi|
��\}}
nt�t|�|
�td#i|
��\}}
|dkr�t||||
|||t|�p�|	d�}nt|||t|�p�|	d�}|dur�|S|dkr�t|��||dd �Stjj�|d!��
}|�|�Wd�n	1�swYd"|��S)$a�)
    Create an X.509 certificate and return an encoded version of it.

    .. note::

        All parameters that take a public key, private key or certificate
        can be specified either as a PEM/hex/base64 string or a path to a
        local file encoded in all supported formats for the type.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.create_certificate signing_private_key='/etc/pki/myca.key' csr='/etc/pki/my.csr'

    ca_server
        Request a remotely signed certificate from ca_server. For this to
        work, a ``signing_policy`` must be specified, and that same policy
        must be configured on the ca_server. See `Signing policies`_ for
        details. Also, the Salt master must permit peers to call the
        ``sign_remote_certificate`` function, see `Peer communication`_.

    signing_policy
        The name of a configured signing policy. Parameters specified in there
        are hardcoded and cannot be overridden. This is required for remote signing,
        otherwise optional. See `Signing policies`_ for details.

    encoding
        Specify the encoding of the resulting certificate. It can be returned
        as a ``pem`` (or ``pkcs7_pem``) string or several (base64-encoded)
        binary formats (``der``, ``pkcs7_der``, ``pkcs12``). Defaults to ``pem``.

    append_certs
        A list of additional certificates to append to the new one, e.g. to create a CA chain.

        .. note::

            Mind that when ``der`` encoding is in use, appending certificatees is prohibited.

    copypath
        Create a copy of the issued certificate in PEM format in this directory.
        The file will be named ``<serial_number>.crt`` if prepend_cn is False.

    prepend_cn
        When ``copypath`` is set, prepend the common name of the certificate to
        the file name like so: ``<CN>-<serial_number>.crt``. Defaults to false.

    pkcs12_passphrase
        When encoding a certificate as ``pkcs12``, encrypt it with this passphrase.

        .. note::

            PKCS12 encryption is very weak and `should not be relied on for security <https://cryptography.io/en/stable/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates>`_.

    pkcs12_encryption_compat
        OpenSSL 3 and cryptography v37 switched to a much more secure default
        encryption for PKCS12, which might be incompatible with some systems.
        This forces the legacy encryption. Defaults to False.

    pkcs12_friendlyname
        When encoding a certificate as ``pkcs12``, a name for the certificate can be included.

    path
        Instead of returning the certificate, write it to this file path.

    overwrite
        If ``path`` is specified and the file exists, overwrite it.
        Defaults to true.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.

    digest
        The hashing algorithm to use for the signature. Valid values are:
        sha1, sha224, sha256, sha384, sha512, sha512_224, sha512_256, sha3_224,
        sha3_256, sha3_384, sha3_512. Defaults to ``sha256``.
        This will be ignored for ``ed25519`` and ``ed448`` key types.

    private_key
        The private key corresponding to the public key the certificate should
        be issued for. This is one way of specifying the public key that will
        be included in the certificate, the other ones being ``public_key`` and ``csr``.

    private_key_passphrase
        If ``private_key`` is specified and encrypted, the passphrase to decrypt it.

    public_key
        The public key the certificate should be issued for. Other ways of passing
        the required information are ``private_key`` and ``csr``. If neither are set,
        the public key of the ``signing_private_key`` will be included, i.e.
        a self-signed certificate is generated.

    csr
        A certificate signing request to use as a base for generating the certificate.
        The following information will be respected, depending on configuration:
        * public key
        * extensions, if not otherwise specified (arguments, signing_policy)

    signing_cert
        The CA certificate to be used for signing the issued certificate.

    signing_private_key
        The private key corresponding to the public key in ``signing_cert``. Required.

    signing_private_key_passphrase
        If ``signing_private_key`` is encrypted, the passphrase to decrypt it.

    serial_number
        A serial number to be embedded in the certificate. If unspecified, will
        autogenerate one. This should be an integer, either in decimal or
        hexadecimal notation.

    not_before
        Set a specific date the certificate should not be valid before.
        The format should follow ``%Y-%m-%d %H:%M:%S`` and will be interpreted as GMT/UTC.
        Defaults to the time of issuance.

    not_after
        Set a specific date the certificate should not be valid after.
        The format should follow ``%Y-%m-%d %H:%M:%S`` and will be interpreted as GMT/UTC.
        If unspecified, defaults to the current time plus ``days_valid`` days.

    days_valid
        If ``not_after`` is unspecified, the number of days from the time of issuance
        the certificate should be valid for. Defaults to ``30``.

    subject
        The subject's distinguished name embedded in the certificate. This is one way of
        passing this information (see ``kwargs`` below for the other).
        This argument will be preferred and allows to control the order of RDNs in the DN
        as well as to embed RDNs with multiple attributes.
        This can be specified as an RFC4514-encoded string (``CN=example.com,O=Example Inc,C=US``,
        mind that the rendered order is reversed from what is embedded), a list
        of RDNs encoded as in RFC4514 (``["C=US", "O=Example Inc", "CN=example.com"]``)
        or a dictionary (``{"CN": "example.com", "C": "US", "O": "Example Inc"}``,
        default ordering).
        Multiple name attributes per RDN are concatenated with a ``+``.

        .. note::

            Parsing of RFC4514 strings requires at least cryptography release 37.

    kwargs
        Embedded X.509v3 extensions and the subject's distinguished name can be
        controlled via supplemental keyword arguments. See the following for an overview.

    Subject properties in kwargs
        C, ST, L, STREET, O, OU, CN, MAIL, SN, GN, UID, SERIALNUMBER

    X.509v3 extensions in kwargs
        Most extensions can be configured using the same string format as OpenSSL,
        while some require adjustments. In general, since the strings are
        parsed to dicts/lists, you can always use the latter formats directly.
        Marking an extension as critical is done by including it at the beginning
        of the configuration string, in the list or as a key in the dictionary
        with the value ``true``.

        Examples (some showcase dict/list correspondance):

        basicConstraints
            ``critical, CA:TRUE, pathlen:1`` or

            .. code-block:: yaml

                - basicConstraints:
                    critical: true
                    ca: true
                    pathlen: 1

        keyUsage
            ``critical, cRLSign, keyCertSign`` or

            .. code-block:: yaml

                - keyUsage:
                    - critical
                    - cRLSign
                    - keyCertSign

        subjectKeyIdentifier
            This can be an explicit value or ``hash``, in which case the value
            will be set to the SHA1 hash of some encoding of the associated public key,
            depending on the underlying algorithm (RSA/ECDSA/EdDSA).

        authorityKeyIdentifier
            ``keyid:always, issuer``

        subjectAltName
            There is support for all OpenSSL-defined types except ``otherName``.

            ``email:me@example.com,DNS:example.com`` or

            .. code-block:: yaml

                # mind this being a list, not a dict
                - subjectAltName:
                    - email:me@example.com
                    - DNS:example.com

        issuerAltName
            The syntax is the same as for ``subjectAltName``, except that the additional
            value ``issuer:copy`` is supported, which will copy the values of
            ``subjectAltName`` in the issuer's certificate.

        authorityInfoAccess
            ``OCSP;URI:http://ocsp.example.com/,caIssuers;URI:http://myca.example.com/ca.cer``

        crlDistributionPoints
            When set to a string value, items are interpreted as fullnames:

            ``URI:http://example.com/myca.crl, URI:http://example.org/my.crl``

            There is also support for more attributes using the full form:

            .. code-block:: yaml

                - crlDistributionPoints:
                    - fullname: URI:http://example.com/myca.crl
                      crlissuer: DNS:example.org
                      reasons:
                        - keyCompromise
                    - URI:http://example.org/my.crl

        certificatePolicies
            ``critical, 1.2.4.5, 1.1.3.4``

            Again, there is support for more attributes using the full form:

            .. code-block:: yaml

                - certificatePolicies:
                    critical: true
                    1.2.3.4.5: https://my.ca.com/pratice_statement
                    1.2.4.5.6:
                      - https://my.ca.com/pratice_statement
                      - organization: myorg
                        noticeNumbers: [1, 2, 3]
                        text: mytext

        policyConstraints
            ``requireExplicitPolicy:3,inhibitPolicyMapping:1``

        inhibitAnyPolicy
            The value is just an integer: ``- inhibitAnyPolicy: 1``

        nameConstraints
            ``critical,permitted;IP:192.168.0.0/255.255.0.0,permitted;email:.example.com,excluded;email:.com``

            .. code-block:: yaml

                - nameConstraints:
                    critical: true
                    permitted:
                      - IP:192.168.0.0/24
                      - email:.example.com
                    excluded:
                      - email:.com
        noCheck
            This extension does not take any values, except ``critical``. Just the presence
            in the keyword args will include it.

        tlsfeature
            ``status_request``

        For more information, visit the `OpenSSL docs <https://www.openssl.org/docs/man3.0/man5/x509v3_config.html>`_.
    �	algorithm�	Potassium�B`algorithm` has been renamed to `digest`. Please update your code.�digest>Zserial_bits�version�text�
days_valid�	not_afterzYThe default value for `days_valid` will change to 30. Please adapt your code accordingly.im��derrZ	pkcs7_der�	pkcs7_pem�pkcs12�Invalid value '�=' for encoding. Valid: der, pem, pkcs7_der, pkcs7_pem, pkcs12�sha256��sha1�sha224r!�sha384�sha512Z
sha512_224Z
sha512_256�sha3_224�sha3_256�sha3_384�sha3_512�y' for digest. Valid: sha1, sha224, sha256, sha384, sha512, sha512_224, sha512_256, sha3_224, sha3_256, sha3_384, sha3_512r�(Cannot encode a certificate chain in DERr�private_key�QCreating a PKCS12-encoded certificate without embedded private key is unsupported�signing_private_keyzGCreating a certificate locally at least requires a signing private key.zfile.file_existszThe file at z& exists and overwrite was set to falseNzQsigning_policy must be specified to request a certificate from a remote ca_server)�append_certs�encodingr-�pkcs12_passphrase�pkcs12_encryption_compat�pkcs12_friendlyname�raw)r0r1r5r�CERTIFICATE)�	overwrite�pem_type�wbzCertificate written to r)�salt�utils�versions�
warn_until�pop�intersection�kwargs_warn_until�x509util�ensure_cert_kwargs_compat�RuntimeErrorrr
�lowerr�__salt__�_create_certificate_remote�merge_signing_policy�_get_signing_policy�_create_certificate_local�encode_certificate�bool�	write_pem�decode�files�fopen�write)�	ca_server�signing_policyr1r0r2r3r4�pathr7r5�kwargs�ignored_params�cert�private_key_loaded�out�fp_rrr�create_certificate�s���
��
�
������
����
rZc
Ks�d}|rtj||d�}t�|���|d<n|�d�r&t�t�|d��|d<|�d�r7t�t�|d��|d<t|||�}zt�|�|fWSt	t
fy[}zt	d|���|�d}~ww)N��
passphrase�
public_key�csrz(ca_server did not return a certificate: )rA�load_privkey�to_derr]r
�load_pubkey�load_csr�
_query_remote�	load_certrr)rQrRr-�private_key_passphraserTrW�result�errrrrrF4s.�
�
����rFr!cKs�tjd
i|��\}}}}d}t�|�tjjtjjfvr t�|�}|j||d�}	|r]d}
|rGz|	j�	tj
d�djd}
Wn	tyFYnwt
t�|	�tj�||
�|	jd�d��dd	�|	|fS)N�r��CNr�-�xz.crtr6)rrSr8r)rAZ	build_crt�get_key_type�KEY_TYPE�ED25519�ED448�get_hashing_algorithm�sign�subject�get_attributes_for_oid�NAME_ATTRS_OID�value�
IndexErrorrL�to_pem�osrS�join�
serial_number)rZcopypathZ
prepend_cnrT�builderr/rW�_rrVZprependrrrrIMs8�
�����rIc	
Cs�|dvrtd|�d���|dkr|rtd��|dkr |r td��|dkr*|s*td��|p-g}t|t�s6|g}t�|�}	d	d
�|D�}|dvrbttj|�	��}
|	�
|
�}|D]}|d|�
|
�7}qUnz|dkr�tj||d
�}|durvt��}
n(t|t
�r|��}|r�tjj���d��tjjj��t����|�}
nt�|�}
tjj|r�tjj� |�nd||	||
d�}n)ztj!j"|	g|ttj|dkr�dnd�d�}Wnt#y�}ztd�|�d}~ww|r�|S|dvr�|�$�St%�&|��$�S)a�
    Create an encoded representation of a certificate, optionally including
    other structures. This can be used to create certificate chains, convert
    a certificate into a different encoding or embed the corresponding
    private key (for ``pkcs12``).

    CLI Example:

    .. code-block:: bash

        salt '*' x509.encode_certificate /etc/pki/my.crt pem /etc/pki/ca.crt

    certificate
        The certificate to encode.

    encoding
        Specify the encoding of the resulting certificate. It can be returned
        as a ``pem`` (or ``pkcs7_pem``) string or several (base64-encoded)
        binary formats (``der``, ``pkcs7_der``, ``pkcs12``). Defaults to ``pem``.

    append_certs
        A list of additional certificates to encode with the new one, e.g. to create a CA chain.

        .. note::

            Mind that when ``der`` encoding is in use, appending certificatees is prohibited.

    private_key
        For ``pkcs12``, the private key corresponding to the public key of the ``certificate``
        to be embedded.

    private_key_passphrase
        For ``pkcs12``, if the private key to embed is encrypted, specify the corresponding
        passphrase.

    pkcs12_passphrase
        For ``pkcs12``, the container can be encrypted. Specify the passphrase to use here.
        Mind that PKCS12 encryption should not be relied on for security purposes, see
        note above in :py:func:`x509.create_certificate <salt.modules.x509_v2.create_certificate>`.

    pkcs12_encryption_compat
        OpenSSL 3 and cryptography v37 switched to a much more secure default
        encryption for PKCS12, which might be incompatible with some systems.
        This forces the legacy encryption. Defaults to False.

    pkcs12_friendlyname
        When encoding a certificate as ``pkcs12``, a name for the certificate can be included.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.
    rrr rr,rz<Embedding private keys is only supported for pkcs12 encodingr.cSsg|]}t�|��qSr)rArd)�.0rlrrr�
<listcomp>�sz&encode_certificate.<locals>.<listcomp>�rr�
r[N�P���name�keyrVZcas�encryption_algorithmrZPEMZDER�r1zASerialization to pkcs7 requires at least cryptography release 37.)rr)'rr�
isinstance�listrArd�getattrr�Encoding�upper�public_bytesr_�NoEncryption�str�encode�
PrivateFormat�PKCS12�encryption_builder�
kdf_rounds�key_cert_algorithmr�PBES�PBESv1SHA1And3KeyTripleDESCBC�	hmac_hashr�SHA1�build�BestAvailableEncryption�serialize_key_and_certificatesr:r;�stringutils�to_bytesZpkcs7Zserialize_certificates�AttributeErrorrM�base64�	b64encode)�certificater1r0r-rer2r3r4r5rVZcrt_encodingZ	crt_bytesZappend_cert�cipherrgrrrrJms�>
���


��


�
�

���
�����rJc	Ks>|r&d|vrtjj�dgd�|�d�dd�|D�}|r&tdt|�����|durBztjj�dd�d}WntyAd	}Ynwg}
|D]R}i}t	|�d
krst
|tt|��t�rstjj�dd�|tt|��D]}|�
|�qkd|pw|vr�tjj�dd
�tjj�|p�|d|p�|�d��|
�|p�|�qF|
}|dvr�td|�d���|��dvr�td|�d���tj|||||||d�\}}d}t�|�tjjtjjfvr�t�|�}|j||d�}t||t|	�p�|
d�}|	dur�|S|dkr�t|��|	dd�Stjj� |	d��
}|�!|�Wd�n	1�swYd|	��S)a
    Create a certificate revocation list.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.create_crl signing_cert=/etc/pki/ca.crt                 signing_private_key=/etc/pki/ca.key                 revoked="[{'certificate': '/etc/pki/certs/www1.crt', 'revocation_date': '2015-03-01 00:00:00'}]"

    signing_private_key
        Your certificate authority's private key. It will be used to sign
        the CRL. Required.

    revoked
        A list of dicts containing all the certificates to revoke. Each dict
        represents one certificate. A dict must contain either the key
        ``serial_number`` with the value of the serial number to revoke, or
        ``certificate`` with some reference to the certificate to revoke.

        The dict can optionally contain the ``revocation_date`` key. If this
        key is omitted, the revocation date will be set to now. It should be a
        string in the format "%Y-%m-%d %H:%M:%S".

        The dict can also optionally contain the ``not_after`` key. This is
        redundant if the ``certificate`` key is included, since it will be
        sourced from the certificate. If the ``certificate`` key is not included,
        this can be used for the logic behind the ``include_expired`` parameter.
        It should be a string in the format "%Y-%m-%d %H:%M:%S".

        The dict can also optionally contain the ``extensions`` key, which
        allows to set CRL entry-specific extensions. The following extensions
        are supported:

        certificateIssuer
            Identifies the certificate issuer associated with an entry in an
            indirect CRL. The format is the same as for subjectAltName.

        CRLReason
            Identifies the reason for certificate revocation.
            Available choices are ``unspecified``, ``keyCompromise``, ``CACompromise``,
            ``affiliationChanged``, ``superseded``, ``cessationOfOperation``,
            ``certificateHold``, ``privilegeWithdrawn``, ``aACompromise`` and
            ``removeFromCRL``.

        invalidityDate
            Provides the date on which the certificate likely became invalid.
            The value should be a string in the same format as ``revocation_date``.

    signing_cert
        The CA certificate to be used for signing the CRL.

    signing_private_key_passphrase
        If ``signing_private_key`` is encrypted, the passphrase to decrypt it.

    include_expired
        Also include already expired certificates in the CRL. Defaults to false.

    days_valid
        The number of days the CRL should be valid for. This sets the ``Next Update``
        field. Defaults to ``100`` (until v3009) or ``7`` (from v3009 onwards).

    digest
        The hashing algorithm to use for the signature. Valid values are:
        sha1, sha224, sha256, sha384, sha512, sha512_224, sha512_256, sha3_224,
        sha3_256, sha3_384, sha3_512. Defaults to ``sha256``.
        This will be ignored for ``ed25519`` and ``ed448`` key types.

    encoding
        Specify the encoding of the resulting certificate revocation list.
        It can be returned as a ``pem`` string or base64-encoded ``der``.
        Defaults to ``pem``.

    extensions
        Add CRL extensions. The following are available:

        authorityKeyIdentifier
            See :py:func:`x509.create_certificate <salt.modules.x509_v2.create_certificate>`.

        authorityInfoAccess
            See :py:func:`x509.create_certificate <salt.modules.x509_v2.create_certificate>`.

        cRLNumber
            Specifies a sequential number for each CRL issued by a CA.
            Values must be integers.

        deltaCRLIndicator
            If the CRL is a delta CRL, this value points to the cRLNumber
            of the base cRL. Values must be integers.

        freshestCRL
            Identifies how delta CRL information is obtained. The format
            is the same as ``crlDistributionPoints``.

        issuerAltName
            See :py:func:`x509.create_certificate <salt.modules.x509_v2.create_certificate>`.

        issuingDistributionPoint
            Identifies the CRL distribution point for a particular CRL and
            indicates what kinds of revocation it covers. The format is
            comparable to ``crlDistributionPoints``. Specify as follows:

            .. code-block:: yaml

                issuingDistributionPoint:
                  fullname:  # or relativename with RDN
                    - URI:http://example.com/myca.crl
                  onlysomereasons:
                    - keyCompromise
                  onlyuser: true
                  onlyCA: true
                  onlyAA: true
                  indirectCRL: false
    path
        Instead of returning the CRL, write it to this file path.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.
    rrcS�g|]	}|�d�s|�qS�r}��
startswith�r~�kwargrrrr��zcreate_crl.<locals>.<listcomp>� Unrecognized keyword arguments: NzXThe default value for `days_valid` will change to 7. Please adapt your code accordingly.�d��zCRevoked certificates should be specified as a simple list of dicts.�reasonz\The `reason` parameter for revoked certificates should be specified in extensions:CRLReason.zextensions:CRLReasonr�r�' for encoding. Valid: der, pemr"r+)�signing_cert�signing_private_key_passphrase�include_expiredr�
extensionsrh�r1r5rzX509 CRL�r8r9zCRL written to )"r:r;r<r@r>rr�r=rC�lenr��next�iter�updateZ
dictupdateZset_dict_key_value�appendrrDrAZ	build_crlrmrnrorprqrr�
encode_crlrKrLrMrNrOrP)r/�revokedr�r�r�rrr1r�rSr5rT�unknownZrevoked_parsedZrev�parsed�valr|r�crlrXrYrrr�
create_crl�s�
���"���
�
�
�	�
�
r�cC�b|dvrtd|�d���t�|�}ttj|���}|�|�}|r"|S|dkr*|��St	�
|���S)a
    Create an encoded representation of a certificate revocation list.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.encode_crl /etc/pki/my.crl der

    crl
        The certificate revocation list to encode.

    encoding
        Specify the encoding of the resulting certificate revocation list.
        It can be returned as a ``pem`` string or base64-encoded ``der``.
        Defaults to ``pem``.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.
    r�rr�r)rrA�load_crlr�rr�r�r�rMr�r�)r�r1r5Zcrl_encodingZ	crl_bytesrrrr��s
�

r�c
KsRd|vrtjj�dd�|�d�}ddh�|�}|r"tjj�|d�t�|�}|dvr3t	d|�d���|�
�d	vrAt	d|�d
���tj|fd|i|��\}}d}	t�|�tj
jtj
jfvrbt�|�}	|j||	d
�}
t|
|t|�pq|d�}|durz|S|dkr�t|��|dd�Stjj�|d��
}|�|�Wd�n1s�wYd|��S)a�
    Create a certificate signing request.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.create_csr private_key='/etc/pki/myca.key' CN='My Cert'

    private_key
        The private key corresponding to the public key the certificate should
        be issued for. The CSR will be signed by it. Required.

    private_key_passphrase
        If ``private_key`` is encrypted, the passphrase to decrypt it.

    digest
        The hashing algorithm to use for the signature. Valid values are:
        sha1, sha224, sha256, sha384, sha512, sha512_224, sha512_256, sha3_224,
        sha3_256, sha3_384, sha3_512. Defaults to ``sha256``.
        This will be ignored for ``ed25519`` and ``ed448`` key types.

    encoding
        Specify the encoding of the resulting certificate signing request.
        It can be returned as a ``pem`` string or base64-encoded ``der``.
        Defaults to ``pem``.

    path
        Instead of returning the CSR, write it to this file path.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.

    kwargs
        Embedded X.509v3 extensions and the subject's distinguished name can be
        controlled via supplemental keyword arguments.
        See :py:func:`x509.create_certificate <salt.modules.x509_v2.create_certificate>`
        for an overview. Mind that some extensions are not available for CSR
        (``authorityInfoAccess``, ``authorityKeyIdentifier``,
        ``issuerAltName``, ``crlDistributionPoints``).
    rrrrrr�rr�r"r+reNrhr�rzCERTIFICATE REQUESTr�r9zCSR written to )r:r;r<r=r>r?r@rArBrrDZ	build_csrrmrnrorprqrr�
encode_csrrKrLrMrNrOrP)
r-rerr1rSr5rTrUr|rr^rXrYrrr�
create_csrsR3�


�
���
��
�
r�cCr�)a
    Create an encoded representation of a certificate signing request.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.encode_csr /etc/pki/my.csr der

    csr
        The certificate signing request to encode.

    encoding
        Specify the encoding of the resulting certificate signing request.
        It can be returned as a ``pem`` string or base64-encoded ``der``.
        Defaults to ``pem``.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.
    r�rr�r)rrArbr�rr�r�r�rMr�r�)r^r1r5Zcsr_encodingZ	csr_bytesrrrr�ss
�

r��rsac
Ksd|vrtjj�dd�|�d�}hd��|�}|r,tjj�|d�|D]}	|�|	�q$dd�|D�}
|
r>tdt|
�����|dvrJt	d	|�d
���t
t||d�|||t|�pX|d�}|d
ura|S|dkrnt
|��|dd�Stjj�|d��}|�|�Wd
�d
S1s�wYd
S)a�
    Create a private key.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.create_private_key algo=ec keysize=384

    algo
        The digital signature scheme the private key should be based on.
        Available: ``rsa``, ``ec``, ``ed25519``, ``ed448``. Defaults to ``rsa``.

    keysize
        For ``rsa``, specifies the bitlength of the private key (2048, 3072, 4096).
        For ``ec``, specifies the NIST curve to use (256, 384, 521).
        Irrelevant for Edwards-curve schemes (``ed25519``, ``ed448``).
        Defaults to 2048 for RSA and 256 for EC.

    passphrase
        If this is specified, the private key will be encrypted using this
        passphrase. The encryption algorithm cannot be selected, it will be
        determined automatically as the best available one.

    encoding
        Specify the encoding of the resulting private key. It can be returned
        as a ``pem`` string, base64-encoded ``der`` or base64-encoded ``pkcs12``.
        Defaults to ``pem``.

    pkcs12_encryption_compat
        Some operating systems are incompatible with the encryption defaults
        for PKCS12 used since OpenSSL v3. This switch triggers a fallback to
        ``PBESv1SHA1And3KeyTripleDESCBC``.
        Please consider the `notes on PKCS12 encryption <https://cryptography.io/en/stable/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates>`_.

    path
        Instead of returning the private key, write it to this file path.
        Note that this does not use safe permissions and should be avoided.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.
    �bitsrz>`bits` has been renamed to `keysize`. Please update your code.>rr��verbosecSr�r�r�r�rrrr�r�z&create_private_key.<locals>.<listcomp>r��rrrr�'' for encoding. Valid: der, pem, pkcs12��algo�keysize)r1r\r3r5Nrz (?:(RSA|ENCRYPTED) )?PRIVATE KEYr�r9)r:r;r<r=r>r?r@rr�r�encode_private_key�_generate_pkrKrLrMrNrOrP)
r�r�r\r1r3rSr5rTrUrlr�rXrYrrr�create_private_key�sN5�
�
�

�
�
��r�c	Cs�|dvrtd|�d���tj||d�}|durt��}n,t|t�r%|��}|dkrC|rCtjj	�
��d��tj
jj��t����|�}nt�|�}|dvr_ttj|���}|j|tjj|d	�}ntj
jd|dd|d
�}|rn|S|dkrv|��St�|���S)a9
    Create an encoded representation of a private key.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.encode_private_key /etc/pki/my.key der

    private_key
        The private key to encode.

    encoding
        Specify the encoding of the resulting private key. It can be returned
        as a ``pem`` string, base64-encoded ``der`` and base64-encoded ``pkcs12``.
        Defaults to ``pem``.

    passphrase
        If this is specified, the private key will be encrypted using this
        passphrase. The encryption algorithm cannot be selected, it will be
        determined automatically as the best available one.

    private_key_passphrase
        .. versionadded:: 3006.2

        If the current ``private_key`` is encrypted, the passphrase to
        decrypt it.

    pkcs12_encryption_compat
        Some operating systems are incompatible with the encryption defaults
        for PKCS12 used since OpenSSL v3. This switch triggers a fallback to
        ``PBESv1SHA1And3KeyTripleDESCBC``.
        Please consider the `notes on PKCS12 encryption <https://cryptography.io/en/stable/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates>`_.

    raw
        Return the encoded raw bytes instead of a string. Defaults to false.
    r�rr�r[Nrr�r�)r1�formatr�r�r)rrAr_rr�r�r�r�r�r�r�r�r�rr�r�r�rr�r�r�r�r�r�Z
private_bytesZPKCS8r�rMr�r�)	r-r1r\rer3r5r�Zpk_encodingZpk_bytesrrrr��sD-
�


�
�

�
�r�cCsTt�|�}z|j}Wnty|jjtjd�}Ynw|tj	tjd�t
|d�kS)a�
    Determine whether a certificate will expire or has expired already.
    Returns a boolean only.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.expires /etc/pki/my.crt days=7

    certificate
        The certificate to check.

    days
        If specified, determine expiration x days in the future.
        Defaults to ``0``, which checks for the current time.
    ��tzinfo)�tz)�days)rArd�not_valid_after_utcr��not_valid_after�replacer�utcr�nowr)r�r�rVrrrr�expiresPs

�r�cCsdi}t�|�r||d<t�|�}z|j�tjd�dj|d<Wn	ty)Ynwt|�|d<|S)a
    Returns a dict containing limited details of a
    certificate and whether the certificate has expired.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.expired /etc/pki/mycert.crt

    certificate
        The certificate to check.
    rSrjr�cn�expired�	rA�isfilerdrsrtrurvrwr�)r��retrVrrrr�ks

�
��r�c	C�Ji}t�|�D]}tj�|�r"z	t|d�||<Wqty!Yqwq|S)z�
    Returns a dict containing PEM entries in files matching a glob.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.get_pem_entries "/etc/pki/*.crt"

    glob_path
        A path representing certificates to be read and returned.
    )r)�globryrSr��
get_pem_entry�
ValueError�Z	glob_pathr�rSrrr�get_pem_entries��
��r�cCs�t�|���}|�dd�}t|���dkr�|�d�r�|�d�r�g}|}t|�dkr�|�d�rJ|�|d|�	dd�d��||�	dd�dd�}n0|dd��
d	�dkre|�|dd��|dd�}n|�|d|�	d	���||�	d	�d�}t|�dks)d�|�}d
|��}|r�d|�d|��}t||�}|s�t
|��|��}|d
}|d}|d}	|d}
|d}d�|���}|d}|r�||d7}|	r�||	dd7}tdt|�d�D]}
|||
|
d�d7}q�||
d7}tjjj|dd�S)a'
    Returns a properly formatted PEM string from the input text,
    fixing any whitespace or line-break issues.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.get_pem_entry "-----BEGIN CERTIFICATE REQUEST-----MIICyzCC Ar8CAQI...-----END CERTIFICATE REQUEST"

    text
        Text containing the X509 PEM entry to be returned or path to
        a file containing the text.

    pem_type
        If specified, this function will only return a pem of a certain type,
        for example 'CERTIFICATE' or 'CERTIFICATE REQUEST'.
    z\n�
r�z-----rN��@rkzPEM text not valid:
z,PEM does not contain a single entry of type z:
�
pem_header�	proc_type�dek_info�
pem_footer�pem_bodyri�asciir�)rA�load_file_or_bytesrMr�r��
splitlinesr��endswithr��index�countrz�
_valid_pemr�	groupdict�split�ranger:r;r�r�)rr8Z	pem_fixedZpem_temp�errmsg�_matchZ_match_dictr�r�r�r�r�r��irrrr��sT��
�


r�cCs"tj||d�}t|d�sdS|jS)a;
    Return information about the keysize of a private key (RSA/EC).

    CLI Example:

    .. code-block:: bash

        salt '*' x509.get_private_key_size /etc/pki/my.key

    private_key
        The private key to check.

    passphrase
        If ``private_key`` is encrypted, the passphrase to decrypt it.
    r[�key_sizeN)rAr_�hasattrr�)r-r\�privkeyrrr�get_private_key_size�s
rc	Cs�|dur
tjj�dgd�zt�t�|����WStt	fy#Ynwzt�tj
||d������WStt	fy>Ynwzt�tj||d������WStt	fyYYnwz
t�t�
|������WSt	ysYtd��w)a�
    Returns a PEM-encoded public key derived from some reference.
    The reference should be a public key, certificate, private key or CSR.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.get_public_key /etc/pki/my.key

    key
        A reference to the structure to look the public key up for.

    passphrase
        If ``key`` is encrypted, the passphrase to decrypt it.
    N�asObjrr[zACould not load key as certificate, public key, private key or CSR)r:r;r<r@rArxrarMrrrdr]r_rb)r�r\rrrr�get_public_keysB���������rc	CsX|dur	t|�}nKd}|tvrit|<|t|vrit||<|t||vrIt||idd�}d|vrAt�t�|d����|d<|t|||<t�t|||�}tj	�
�D]%\}}|D]}||vr}tjj
�dd|�d|�d	|���|�|�||<q_qYtj�
�D]%\}}|D]}||vr�tjj
�dd|�d|�d	|���|�|�||<q�q�|S)
a[
    Returns the specified named signing policy.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.get_signing_policy www

    signing_policy
        The name of the signing policy to return.

    ca_server
        If this is set, the CA server will be queried for the
        signing policy instead of looking it up locally.
    NZ_x509_policiesT)�get_signing_policy_onlyr�rzFound z in z$. Please migrate to the short name: )rH�__context__rcrArxrdrM�copy�deepcopyZNAME_ATTRS_ALT_NAMES�itemsr:r;r<r=r>ZEXTENSIONS_ALT_NAMES)	rRrQ�policyZckeyZpolicy_r�Z
long_namesZ	long_name�extnamerrr�get_signing_policy3sP
������	���rcCs�t�|�}tj|��dd�}z|j}|j}Wnty/|jjt	j
d�}|jjt	j
d�}Ynw|jj
d|dvr>|��jnd|t�|j�t�|jt��d��t�|jt��d��d�t|j�t�t|j��|j��t|j�t�t|j��|j��|�tj�|�tj�t|�t|j�d	�}z|j j!|d
<Wn*ty�zt"j#�$�D]\}}||j kr�||d
<nq�Wn	ty�YnwYnwd
|vr�|j j%|d
<t&ddur�t�|jt�'�d��|d
d<|S)z�
    Returns a dict containing details of a certificate.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_certificate /etc/pki/mycert.crt

    certificate
        The certificate to read.
    T��	as_stringr�r���ecr�Nrh)r#r!)rr��key_typer{�fingerprintsrs�subject_hash�subject_str�issuerZissuer_hashZ
issuer_str�
not_beforerr]r��signature_algorithmZ	fips_modeFr�md5)(rArdrmr]Znot_valid_before_utcr�r�Znot_valid_beforer�rr�r�rrvr��dec2hexr{�
pretty_hexZfingerprintrr��SHA256�	_parse_dnrs�_get_name_hash�rfc4514_stringr�strftime�TIME_FMTr�_parse_extensionsr��signature_algorithm_oid�_name�cx509�SignatureAlgorithmOIDr�
dotted_stringr�MD5)r�rVrrrr�r��oidrrr�read_certificatepsb


�

�

�
�����	�r(c	Cr�)z�
    Returns a dict containing details of all certificates matching a glob.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_certificates "/etc/pki/*.crt"

    glob_path
        A path to certificates to be read and returned.
    )r�)r�ryrSr�r(r�r�rrr�read_certificates�r�r)cCsft�|�}z|j}|j}Wnty&|jjtjd�}|j	jtjd�}Ynwt
|j�|�tj
�|�tj
�it|j�d�}z|jj|d<Wn*tyoztj��D]\}}||jkra||d<nqRWn	tylYnwYnwd|vrz|jj|d<|D]4}z|j}Wnty�|jjtjd�}Ynw|d�t�|j��dd�|�tj
�t|j�d�i�q||S)z�
    Returns a dict containing details of a certificate revocation list.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_crl /etc/pki/my.crl

    crl
        The certificate revocation list to read.
    r�)r�last_update�next_update�revoked_certificatesr�rr,�:ri)�revocation_dater�)rAr�Zlast_update_utcZnext_update_utcr�r*r�rr�r+rrrrr r�r!r"r#r$rr%Zrevocation_date_utcr.r�rr{�_parse_crl_entry_extensions)r�r*r+r�r�r'r�r.rrr�read_crl�sZ


�

�
�����	
�
���r0cCstt�|�}tj|��dd�}|dvr|��jnd|t|j�t�t|j��|j�	�t�t
j�|���j
�t|j�d�S)z�
    Returns a dict containing details of a certificate signing request.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_csr /etc/pki/mycert.csr

    csr
        The certificate signing request to read.
    TrrN)r�rrsrrZpublic_key_hashr�)rArbrmr]r�rrsrrrr#ZSubjectKeyIdentifierZfrom_public_keyrr r�)r^rrrr�read_csrs

��r1c	
Ks�dgd�}z�t|�}|s|d�d�|WSd|vr<d|vr(|d�d�|WSt|�d�|d�s<|d�d�|WS|r�|�d	d�|�d
d�d|vr�zt�t�|d��|d<Wn$ttfy�}zd|d<|d�t	|��|WYd}~WSd}~ww||d<|WSt�
||�|�d
d�Wnty�}zt�
t	|��ddgd�WYd}~Sd}~wwztdi|��\}}t�|�|d<|WSty�}zd|d<|d�t	|��|WYd}~Sd}~ww)a�
    Request a certificate to be remotely signed according to a signing policy.
    This is mostly for internal use and does not make much sense on the CLI.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.sign_remote_certificate www kwargs="{'public_key': '/etc/pki/www.key'}"

    signing_policy
        The name of the signing policy to use. Required.

    kwargs
        A dict containing all the arguments to be passed into the
        :py:func:`x509.create_certificate <salt.modules.x509_v2.create_certificate>` function.

    get_signing_policy_only
        Only return the named signing policy. Defaults to false.
    N)�data�errorsr3z>signing_policy must be specified and defined on signing minionZminionsZ__pub_idz3minion sending this request could not be identifiedz4minion not permitted to use specified signing policyr/r�r�r2rQzBFailed building the signing policy. See CA server log for details.z*Internal error. This is most likely a bug.r)rHr��_match_minionsr>rAr`rdrrr�rG�	Exception�log�errorrI)	rRrTrZmore_kwargsr�rgrVr}Zerr_messagerrr�sign_remote_certificate#sr
�������������r8cCs�td|d|||gd�}|std��|tt|��}t|t�r#d|vr-t�d|�td��|�	d�r=td	d
�
|d���|dS)N�publish.publishzx509.sign_remote_certificate)�argzfca_server did not respond. Salt master must permit peers to call the sign_remote_certificate function.r2z0Received invalid return value from ca_server: %szHReceived invalid return value from ca_server. See minion log for detailsr3zca_server reported errors:
r�)rErr�r�r��dictr6r7rr
rz)rQrRrTrrfrrrrc|s(���
�rccCs"t�|�}t�t|��}|�|�S)a�
    Verify that a signature on a certificate revocation list was made
    by the private key corresponding to the public key associated
    with the specified certificate.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.verify_crl /etc/pki/my.crl /etc/pki/my.crt

    crl
        The certificate revocation list to check the signature on.

    cert
        The certificate (or any reference that can be passed
        to ``get_public_key``) to retrieve the public key from.
    )rAr�rarZis_signature_valid)r�rV�pubkeyrrr�
verify_crl�s

r=cCs(tj||d�}t�t|��}t�||�S)a�
    Verify that a private key belongs to the specified public key.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.verify_private_key /etc/pki/my.key /etc/pki/my.crt

    private_key
        The private key to check.

    public_key
        The certificate (or any reference that can be passed
        to ``get_public_key``) to retrieve the public key from.

    passphrase
        If ``private_key`` is encrypted, the passphrase to decrypt it.
    r[)rAr_rarZis_pair)r-r]r\rr<rrr�verify_private_key�sr>cCs,t�|�}t�t|p||d��}t�||�S)a�
    Verify that a signature on a certificate was made
    by the private key corresponding to the public key associated
    with the specified certificate.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.verify_signature /etc/pki/my.key /etc/pki/my.crt

    certificate
        The certificate to check the signature on.

    signing_pub_key
        Any reference that can be passed to ``get_public_key`` to retrieve
        the public key of the signing entity from. If unspecified, will
        take the public key of ``certificate``, i.e. verify a self-signed
        certificate.

    signing_pub_key_passphrase

        If ``signing_pub_key`` is encrypted, the passphrase to decrypt it.
    r[)rArdrar�verify_signature)r�Zsigning_pub_keyZsigning_pub_key_passphraserVr<rrrr?�s
��r?cCsjd|i}t�|�r
||d<t�|�}z|j�tjd�dj|d<Wn	ty+Ynwt||�|d<|S)aw
    Returns a dict containing details of a certificate and whether
    the certificate will expire in the specified number of days.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.will_expire "/etc/pki/mycert.crt" days=30

    certificate
        The certificate to check.

    days
        The number of days in the future to check the validity for.
    Z
check_daysrSrjrr��will_expirer�)r�r�r�rVrrrr@�s

�
��r@c	Cs�t||d�}tjj�d���d}d}|ru|dkrutj�|�ru|sut�	|��
�}zt|d�}WntyM}zt�
d|�tj||d�WYd}~nd}~wwzt|d	�}Wntyt}zt�
d
|�tj||d�WYd}~nd}~wwtjj�|d��6}|r�|dkr�|r�|�tjj�|��|�tjj�|��|r�|dkr�|r�|�tjj�|��Wd�n1s�wYWd�n1s�wYd|��S)
a�
    Writes out a PEM string, fixing any formatting or whitespace
    issues before writing.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.write_pem "-----BEGIN CERTIFICATE-----MIIGMzCCBBugA..." path=/etc/pki/mycert.crt

    text
        PEM string input to be written out.

    path
        Path of the file to write the PEM out to.

    overwrite
        If ``True`` (default), write_pem will overwrite the entire PEM file.
        Set to ``False`` to preserve existing private keys and DH params that may
        exist in the PEM file.

    pem_type
        The PEM type to be saved, for example ``CERTIFICATE`` or
        ``PUBLIC KEY``. Adding this will allow the function to take
        input that may contain multiple PEM types.
    r��?rir6z
DH PARAMETERSz(Error while retrieving DH PARAMETERS: %s)�exc_infoNz(?:RSA )?PRIVATE KEYz&Error while retrieving PRIVATE KEY: %s�wzPEM written to )r�r:r;rNZ	set_umaskryrSr�rAr�rMrr6�debugZtracerOrPr�Zto_str)	rrSr7r8Z	_dhparamsZ_private_keyZ
_filecontentsrg�_fprrrrLsJ�
����������
rLcCst�d|�d|�d�tj�S)z8
    Dynamically generate a regex to match pem_type
    z\s*(?P<pem_header>-----BEGIN z�-----)\s+(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[0-9A-F]{{32}}))\s*)?(?P<pem_body>.+?)\s+(?P<pem_footer>-----END z	-----)\s*)�re�compile�DOTALLr�rrr�_make_pem_regexDs��rIcCs8|durdn|}t|�}|�|�D]}|r|SqdS)Nz
[0-9A-Z ]+)rI�finditer)rr8Z_dregexr�rrrr�Ss�r�cCs`|dkrtj|p	dd�S|dkrtj|pdd�S|dkr t��S|dkr(t��Std|�d	���)
Nr�i)r�r�Zed25519Zed448z8Invalid algorithm specified for generating private key: z . Valid: rsa, ec, ed25519, ed448)rAZgenerate_rsa_privkeyZgenerate_ec_privkeyZgenerate_ed25519_privkeyZgenerate_ed448_privkeyrr�rrrr�\s
�r�cCsf|duriStddi��|�}|ptddi��|�}t|t�r/i}|D]}|�|�q%|}|p2iS)Nz
pillar.getZx509_signing_policiesz
config.get)rEr
r�r�r�)r�ZpoliciesZdict_�itemrrrrHks
rHc	CsHt�}tj��D]\}}z|�|�dj||<Wqty!Yqw|S)zA
    Returns a dict containing all values in an X509 Subject
    r)r	rArurrtrvrw)rsr�Znid_namer'rrrrxs�rr#cCsf|��dvrtd|�d���t�t�|��}|�|���|��dd�}t	j
dkr1|ddd�}|S)z�
    Returns the OpenSSL name hash.
    This is the first four bytes of the SHA1 (pre v1: MD5) hash
    of the DER-encoded form of name. On little-endian systems,
    OpenSSL inverts the bytes.
    )r#rz)Invalid hashing algorithm for name hash: z. Only SHA1 and MD5 are allowedN��little���)rDr�rZHashrArqr�r��finalize�sys�	byteorder)r�rZhsh�resrrrr�s
�
rc	C�Ni}tj��D]\}}z|�|�}Wn
tjyYqwt�|�||<q|S�N)rAZEXTENSIONS_OIDr�get_extension_for_oidr#�ExtensionNotFound�render_extension�r�r�r
r'�extrrrr ���r c	CrTrU)rAZEXTENSIONS_CRL_ENTRY_OIDrrVr#rWrXrYrrrr/�r[r/cCs@d|vrtd|d|d�}||vrtd��||Std||�S)N�@r9zmatch.compound)ZtgtZfunr:z�Could not verify if minion matches compound matching expression. Make sure the ca_server is allowed to run `match.compound` on the requesting minionz
match.glob)rEr)�testZminion�matchrrrr4�s�r4)
NNrNNFNNTF)NN)r!NF)rNNNNFNF)	NNFNr!rNNF)rF)Nr!rNF)r�NNrFNF)rNNFF)rrU)F)TN)r�N)r#)J�__doc__r�rr��loggingZos.pathryrFrQrrrZcryptography.x509r
r#Zcryptography.hazmat.primitivesrrZsalt.utils.x509r;rAr�ImportErrorZsalt.utils.dictupdater:Zsalt.utils.filesZsalt.utils.stringutilsZsalt.exceptionsrrZsalt.utils.odictr	�	getLogger�__name__r6rrrZrFrIrJr�r�r�r�r�r�r�r�r�r�rrrr(r)r0r1r8rcr=r>r?r@rLrIr�r�rHrrr r/r4rrrr�<module>s��

�
�
�"
�
�
d(
�
k&
�c
�
W

M

.=B;
�
Y

�$
 9