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/states/__pycache__/x509_v2.cpython-310.pyc
o

�N�g��@s�dZddlZddlZddlZddlZddlmZmZmZddl	Z
ddlmZm
Z
ddlmZzddlmZddlmZddlmZddlmmZdZWneyXd	ZYnwe�e�Zd
Z dd�Z!				
																					d6dd�Z"								
	d7dd�Z#			
	d8dd�Z$dd�Z%				
						d9dd�Z&dd�Z'dd�Z(dd�Z)d:d d!�Z*d"d#�Z+	d;d$d%�Z,d&d'�Z-d(d)�Z.d*d+�Z/d,d-�Z0d.d/�Z1d0d1�Z2d2d3�Z3d4d5�Z4dS)<a/
Manage X.509 certificates
=========================

.. versionadded:: 3006.0

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

:depends: cryptography

.. note::

    All parameters that take a public key, private key, certificate,
    CSR or CRL 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.

Configuration instructions and general remarks are documented
in the :ref:`execution module docs <x509-setup>`.

For the list of breaking changes versus the previous ``x509`` modules,
please also refer to the :ref:`execution module docs <x509-setup>`.

About
-----
This module can enable managing a complete PKI infrastructure, including creating
private keys, CAs, certificates and CRLs. It includes the ability to generate a
private key on a server, and have the corresponding public key sent to a remote
CA to create a CA signed certificate. This can be done in a secure manner, where
private keys are always generated locally and never moved across the network.

Example
-------
Here is a simple example scenario. In this example ``ca`` is the ca server,
and ``www`` is a web server that needs a certificate signed by ``ca``.

.. note::

    Remote signing requires the setup of :term:`Peer Communication` and signing
    policies. Please see the :ref:`execution module docs <x509-setup>`.


/srv/salt/top.sls

.. code-block:: yaml

    base:
      '*':
        - cert
      'ca':
        - ca
      'www':
        - www

This state creates the CA key, certificate and signing policy. It also publishes
the certificate to the mine, where it can be easily retrieved by other minions.

.. code-block:: yaml

    # /srv/salt/ca.sls

    Configure the x509 module:
      file.managed:
        - name: /etc/salt/minion.d/x509.conf
        - source: salt://x509.conf

    Restart Salt minion:
      cmd.run:
        - name: 'salt-call service.restart salt-minion'
        - bg: true
        - onchanges:
          - file: /etc/salt/minion.d/x509.conf

    Ensure PKI directories exist:
      file.directory:
        - name: /etc/pki/issued_certs
        - makedirs: true

    Create CA private key:
      x509.private_key_managed:
        - name: /etc/pki/ca.key
        - keysize: 4096
        - backup: true
        - require:
          - file: /etc/pki/issued_certs

    Create self-signed CA certificate:
      x509.certificate_managed:
        - name: /etc/pki/ca.crt
        - signing_private_key: /etc/pki/ca.key
        - CN: ca.example.com
        - C: US
        - ST: Utah
        - L: Salt Lake City
        - basicConstraints: "critical, CA:true"
        - keyUsage: "critical, cRLSign, keyCertSign"
        - subjectKeyIdentifier: hash
        - authorityKeyIdentifier: keyid:always,issuer
        - days_valid: 3650
        - days_remaining: 0
        - backup: true
        - require:
          - x509: /etc/pki/ca.key

.. code-block:: yaml

    # /srv/salt/x509.conf

    # enable x509_v2
    features:
      x509_v2: true

    # publish the CA certificate to the mine
    mine_functions:
      x509.get_pem_entries: [/etc/pki/ca.crt]

    # define at least one signing policy for remote signing
    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 keyEncipherment"
        - subjectKeyIdentifier: hash
        - authorityKeyIdentifier: keyid:always,issuer
        - days_valid: 30
        - copypath: /etc/pki/issued_certs/


This example state will instruct all minions to trust certificates signed by
our new CA. Mind that this example works for Debian-based OS only.
Also note the Jinja call to encode the string to JSON, which will avoid
YAML issues with newline characters.

.. code-block:: jinja

    # /srv/salt/cert.sls

    Ensure the CA trust bundle exists:
      file.directory:
        - name: /usr/local/share/ca-certificates

    Ensure our self-signed CA certificate is included:
      x509.pem_managed:
        - name: /usr/local/share/ca-certificates/myca.crt
        - text: {{ salt["mine.get"]("ca", "x509.get_pem_entries")["ca"]["/etc/pki/ca.crt"] | json }}

This state creates a private key, then requests a certificate signed by our CA
according to the www policy.

.. code-block:: yaml

    # /srv/salt/www.sls

    Ensure PKI directory exists:
      file.directory:
        - name: /etc/pki

    Create private key for the certificate:
      x509.private_key_managed:
        - name: /etc/pki/www.key
        - keysize: 4096
        - backup: true
        - require:
          - file: /etc/pki

    Request certificate:
      x509.certificate_managed:
        - name: /etc/pki/www.crt
        - ca_server: ca
        - signing_policy: www
        - private_key: /etc/pki/www.key
        - CN: www.example.com
        - days_remaining: 7
        - backup: true
        - require:
          - x509: /etc/pki/www.key
�N)�datetime�	timedelta�timezone)�CommandExecutionError�SaltInvocationError)�STATE_INTERNAL_KEYWORDS)�UnsupportedAlgorithm)�hashesTF�x509cCstsdStd�d�s
dStS)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�G/opt/saltstack/salt/lib/python3.10/site-packages/salt/states/x509_v2.py�__virtual__�s
r�pem�sha256c/Ks$|dur |dur ztjj�dd�d}Wntyd}Ynw|dur<ztjj�dd�d}Wnty;d}Ynwd	|vrMtjj�dd
�|�d	�}t�|�}|iddd
�}d}}i}d}tt	|��\}}|plg}t
|t�su|g}�zwt|fddd�|��} | ddur�d|d<d|d<t
|| �|WSd| dvr�t
|| �|WS|}!d}"td|�r�|�dd�r�tj�|�}!ntd|�d}"td|!��r�ztj|!|dd�\}}}#}$Wn0t�y
}%z#dt|%�vr�d|d<ntdt|%�vdt|%�vf�r�d}"n�WYd}%~%n�d}%~%ww||k�r||d<n|dk�r/|$jj|�r'tjj�|�ndk�r/||d <z|j}&Wnt�yF|jjtj d!�}&Ynw|&t!j"tj d"�t#|d#�k�rZd|d$<|#�p^g}#d%d&�|D�}'t$|#|'��spd|d'<t%dN||||	|
|||
|||||||d(�|��\}(})}*}+z|j&du�r�t
|j&t't�(|+d)����s�||d)<Wnt)�y�t*�+d*|�Ynw|�,t-||(|*|||d+��n||d,<|"�r�||d-<|�s�| d�r�| d.�s�t
|| �|WS||d.<|�r�|�r�d/}t.d0�r|�r�dnd|d<|�rd1|�d2�n|d|d<t
|| �|WS|�r�t/|�hd3��s>|dk�r4td4||||)|||d5�},nOtd4|||d6�},nEtd7dNid8|�d9|�d|�d:|�d|�d;|�d |�d)|�d<|	�d=|
�d>|�d?|�d@|
�dA|�dB|�dC|�dD|�dE|�dF|�dG|�|��},dH|�d2�|d<|dIv�r�t|fdJdi|��}-t
||-�t0|-||��s�|WSt1|!t2�3|,�|�dKdL��|�r�|dIv�r�t4|dIv�o�|�}"|"�r�|,nd}.t|f|.|"dM�|��}-t
||-�t0|-||��s�|WSW|SW|St5tf�y}%zd|d<t|%�|d<i|d.<WYd}%~%|Sd}%~%ww)Oa�
    Ensure an X.509 certificate is present as specified.

    This function accepts the same arguments as :py:func:`x509.create_certificate <salt.modules.x509_v2.create_certificate>`,
    as well as most ones for `:py:func:`file.managed <salt.states.file.managed>`.

    name
        The path the certificate should be present at.

    days_remaining
        The certificate will be recreated once the remaining certificate validity
        period is less than this number of days.
        Defaults to ``90`` (until v3009) or ``7`` (from v3009 onwards).

    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.  Also, the Salt master must
        permit peers to call the ``x509.sign_remote_certificate`` function.
        See the :ref:`execution module docs <x509-setup>` for details.

    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.

    encoding
        Specify the encoding of the resulting certificate. It can be serialized
        as a ``pem`` (or ``pkcs7_pem``) text file or in several 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.

    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.

    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.

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

    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.

    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.

    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)

    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 a 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.

    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 ``365`` (until v3009) or ``30`` (from v3009 onwards).

    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.

    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.
    N�	PotassiumzYThe default value for `days_valid` will change to 30. Please adapt your code accordingly.im�z\The default value for `days_remaining` will change to 7. Please adapt your code accordingly.�Z��	algorithm�B`algorithm` has been renamed to `digest`. Please update your code.Tz'The certificate is in the correct state��name�changes�result�comment�createF��test�replacer�:Problem while testing file.managed changes, see its outputr�*is not present and is not set for creation�file.is_link�follow_symlinks�file.remove�file.file_exists��
passphrase�get_encoding�Bad decrypt�pkcs12_passphrase�!Could not deserialize binary data�Could not load PEM-encoded�encodingZpkcs12�pkcs12_friendlyname��tzinfo��tz��days�
expirationcSsg|]}t�|��qSr)�x509util�	load_cert��.0�xrrr�
<listcomp>�sz'certificate_managed.<locals>.<listcomp>�additional_certs)�	ca_server�signing_policy�digest�signing_private_key�signing_private_key_passphrase�signing_cert�
public_key�private_key�private_key_passphrase�csr�subject�
serial_number�
not_before�	not_after�
days_validrB�HCould not determine signature hash algorithm of '%s'. Continuing anyways)rErKrLrM�created�replacedr�recreater!z The certificate would have been �d>r1r0r?zx509.encode_certificate)�append_certsr0rGr-�pkcs12_encryption_compatr1)r0rTzx509.create_certificater@rArTrUrCrDrErFrGrHrIrJrKrLrMrNzThe certificate has been )rZ	pkcs7_pemr"�backup���contentsr"r)6�salt�utils�versions�
warn_until�RuntimeError�popr9�ensure_cert_kwargs_compat�_split_file_kwargs�_filter_state_internal_kwargs�
isinstance�list�
_file_managed�_add_sub_state_run�__salt__r
�os�path�realpathr:r�str�any�certZ
friendly_nameZstringutils�to_bytesZnot_valid_after_utc�AttributeErrorZnot_valid_afterr"r�utcr�nowr�_compare_ca_chain�_build_cert�signature_hash_algorithm�type�get_hashing_algorithmr�log�warning�update�
_compare_certr�set�_check_file_ret�_safe_atomic_write�base64�	b64decode�boolr)/r�days_remainingr@rAr0rTZcopypathZ
prepend_cnrBrCrDrErFrGrHrIrJrKrLrMrNr-rUr1�kwargs�ret�current�current_encodingr�verb�	file_argsZ	cert_args�file_managed_test�	real_namer"Z
current_chainZ
current_extra�errZcurr_not_afterZca_chain�builder�private_key_loadedZsigning_cert_loaded�final_kwargsrm�file_managed_retrYrrr�certificate_managed�s(�����

�
�

��


����

��

���
������������

��

�
���������	�
���
��������

����
�����r�c"Ks\d|vrtjj�dgd�|�d�|dur.ztjj�dd�d}Wnty-d}Ynw|durJztjj�dd�d}WntyId	}Ynwg}|D]R}
i}t|
�d
kr{t|
t	t
|
��t�r{tjj�dd�|
t	t
|
��D]}|�|�qsd|p|
vr�tjj�dd
�tjj
�|p�|
d|p�|
�d��|�|p�|
�qN|}|iddd�}d}}i}d}tt|��\}}|
p�i}
|r�tdt|������z?t|fddd�|��}|ddur�d|d<d|d<t||�|WSd|dvr�t||�|WS|}d}td|��r|�dd��rtj�|�}ntd|�d}td|��rztj|dd�\}}Wn&t�yS}ztdt|�vd t|�vf��rHd}n�WYd}~n�d}~wwz|jdu�rkt|jtt� |����sk||d!<Wnt!�y|t"�#d"|�Ynw|	|k�r�|	|d#<z|j$}Wnt%�y�|j&j't(j)d$�}Ynw|�r�|t*j+t(j)d%�t,|d&�k�r�d|d'<|
�d(�d)k}|�r�|
�d(�tj-|||||||
d*�\}}|�t.|||�/���|�rd)|
d(<|d+d,�|d+d,�0d(��t|d+�1���s|�d+�n||d-<|�r
||d.<|�s"|d�r"|d/�s"t||�|WS||d/<|�r.|�r.d0}t2d1�rS|�r8dnd|d<|�rEd2|�d3�n|d|d<t||�|WS|�r�t3|�d#h�sgtd4||	d5�}n8|
�d(�d)k�r�z|j4�5t6j7�j8j9d
|
d(<Wnt%t6j:f�y�d
|
d(<Ynwtd6||||||||	|
d7�	}d8|�d3�|d<|	d9k�r�t|fd:di|��} t|| �t;| ||��s�|WSt<|t=�>|�|�d;d<��|�r�|	d=k�rt?|	d=k�o�|�}|�r�|nd}!t|f|!|d>�|��} t|| �t;| ||��s|WSW|SW|St@tf�y-}zd|d<t|�|d<i|d/<WYd}~|Sd}~ww)?a�
    Ensure a certificate revocation list is present as specified.

    This function accepts the same arguments as :py:func:`x509.create_crl <salt.modules.x509_v2.create_crl>`,
    as well as most ones for `:py:func:`file.managed <salt.states.file.managed>`.

    name
        The path the certificate revocation list should be present at.

    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. 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 became invalid.
            The value should be a string in the same format as ``revocation_date``.

    days_remaining
        The certificate revocation list will be recreated once the remaining
        CRL validity period is less than this number of days.
        Defaults to ``30`` (until v3009) or ``3`` (from v3009 onwards).
        Set to 0 to disable automatic renewal without anything changing.

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

    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 that the CRL should be valid for. This sets the ``Next Update``
        field in the CRL. 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 serialized as a ``pem`` text or binary ``der`` file.
        Defaults to ``pem``.

    extensions
        Add CRL extensions. See :py:func:`x509.create_crl <salt.modules.x509_v2.create_crl>`
        for details.

        .. note::

            For ``cRLNumber``, in addition the value ``auto`` is supported, which
            automatically increases the counter every time a new CRL is issued.

    Example:

    .. code-block:: yaml

        Manage CRL:
          x509.crl_managed:
            - name: /etc/pki/ca.crl
            - signing_private_key: /etc/pki/myca.key
            - signing_cert: /etc/pki/myca.crt
            - revoked:
              - certificate: /etc/pki/certs/badweb.crt
                revocation_date: 2022-11-01 00:00:00
                extensions:
                  CRLReason: keyCompromise
              - serial_number: D6:D2:DC:D8:4D:5C:C0:F4
                not_after: 2023-03-14 00:00:00
                revocation_date: 2022-10-25 00:00:00
                extensions:
                  CRLReason: cessationOfOperation
            - extensions:
                cRLNumber: auto
    �textrNzXThe default value for `days_valid` will change to 7. Please adapt your code accordingly.�drz\The default value for `days_remaining` will change to 3. Please adapt your code accordingly.r��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:CRLReasonTz7The certificate revocation list is in the correct staterr� Unrecognized keyword arguments: Fr rr#rr$r%r&r'r(�r+r/�Could not load DER-encodedrBrOr0r2r4r6r8Z	cRLNumber�auto)rErD�include_expiredrN�
extensionsr��removedrPrQrrRr!z0The certificate revocation list would have been rSzx509.encode_crl�r0zx509.create_crl)rErDr�rNrBr0r�z)The certificate revocation list has been �derr"rVrWrrX)ArZr[r\�kwargs_warn_untilr_r]r^�lenrc�next�iterrdryZ
dictupdateZset_dict_key_value�appendrarbrrerfrgr
rhrirjr9Zload_crlrlrkrtrurvrrwrxZnext_update_utcroZnext_updater"rrprrqrZ	build_crl�_compare_crlrF�index�valuesrr{r�Zget_extension_for_class�cx509Z	CRLNumber�valueZ
crl_number�ExtensionNotFoundr|r}r~rr�r)"rrC�revokedr�rErDr�rNrBr0r�r�Zrevoked_parsed�rev�parsed�valr�r�r�rr�r��
extra_argsr�r�r"r�Zcurr_next_updateZcrl_autor�Zsig_privkeyZcrlr�rYrrr�crl_managed�s�{
����"�����

�

���������

��

�	�
����

��
��
���

����
�
����r�c
Ks0d|vrtjj�dd�|�d�}t�|�}|iddd�}d}}	i}
d}tt|��\}}
�z�t	|fdd	d
�|��}|dd	urPd	|d<d|d
<t
||�|WSd|d
vr^t
||�|WS|}d	}td|�r}|�dd�rut
j�|�}ntd|�d}td|��rztj|dd�\}}	Wn3ty�}ztdt|�vdt|�vf�r�d}n�WYd}~njd}~wtjy�d|
d<d}YnWwz|jdur�t|jtt�|���s�||
d<Wnty�t�d|�Ynw||	kr�||
d<tj|f||d�|
��\}}t�|��|��sd|
d<|
� t!||��n||
d<|�r ||
d<|
�s5|d�r5|d�s5t
||�|WS|
|d<|�rA|
�rAd}t"d �rf|
�rKdnd|d<|
�rXd!|�d"�n|d
|d
<t
||�|WS|
�r�t#|
�dh�sztd#||d$�}ntd%|f||||d&�|
��}d'|�d"�|d
<|d(k�r�t	|fd)d	i|��}t
||�t$|||��s�|WSt%|t&�'|�|�d*d+��|
�r�|d,k�r�t(|d,k�o�|
�}|�r�|nd}t	|f||d-�|��}t
||�t$|||��s�|WSW|SW|St)tf�y}zd	|d<t|�|d
<i|d<WYd}~|Sd}~ww).a�
    Ensure a certificate signing request is present as specified.

    This function accepts the same arguments as :py:func:`x509.create_csr <salt.modules.x509_v2.create_csr>`,
    as well as most ones for :py:func:`file.managed <salt.states.file.managed>`.

    name
        The path the certificate signing request should be present at.

    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 revocation list.
        It can be serialized as a ``pem`` text or binary ``der`` file.
        Defaults to ``pem``.

    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``).
    rrrTz7The certificate signing request is in the correct staterNrFr rr#rr$r%r&r'r(r�r/r�Zinvalid_versionrBrOr0)rHrJrGrPrQrrRr!z0The certificate signing request would have been rSzx509.encode_csrr�zx509.create_csr)rHrBr0rJz)The certificate signing request has been r�r"rVrWrrX)*rZr[r\r]r_r9r`rarbrerfrgr
rhrirjZload_csrrrlrkr�ZInvalidVersionrtrcrurvrrwrxZ	build_csrZis_pairrFry�_compare_csrrr{r|r}r~rr�r)rrGrHrBr0rJr�r�r�r�rr�r�Zcsr_argsr�r�r"r�r�ZprivkeyrIr�rYrrr�csr_managed�s&-�

��

�

�����������
����

��
���

����
�����r�c
Ks�t|�\}}|rtdt|�����ztd|d�|d<Wnttfy9}z|dt|�id�WYd}~Sd}~wwt|fi|��S)aK
    Manage the contents of a PEM file directly with the content in text,
    ensuring correct formatting.

    name
        The path to the file to manage.

    text
        The PEM-formatted text to write.

    kwargs
        Most arguments supported by :py:func:`file.managed <salt.states.file.managed>` are passed through.
    r�zx509.get_pem_entry)r�rYF)rrrrN)rarrdrgrrkre)rr�r�r�r�r�rrr�pem_managed�s��r��rsac
Ksjd|vrtjj�dd�|�d�}hd��|�}	|	r,tjj�|	d�|	D]}
|�|
�q$|iddd�}d}}
i}d	}t|�\}}|rLtd
t	|�����|�
d�sUd|d<�z:|rd|d
vrdtd|����t|fddd�|��}|ddur�d|d<d|d<t||�|WSd|dvr�t||�|WS|}d}t
d|�r�|�
dd�r�tj�|�}nt
d|�d}t
d|�}|�r?|�s?z
tj||dd�\}}
}Wnst�y>}zfdt|�vr�|s�td�|�d|d<nNtdt|�vdt|�vdt|�vf��r|�std �|�d}n/d!t|�v�rd|d<tj|ddd�\}}
}nd"t|�v�r3|�s3|�s.td#�|�d|d<n�WYd}~nd}~ww|�r�t�|�}|}|du�r]|d$k�rVd%}n|d&k�r]d'}t|d$k�oi|tjjk|d&k�ot|tjjk|d(k�o|tjjk|d)k�o�|tjjkf��r�||d*<d*|v�r�|d+v�r�|j|k�r�||d,<||
k�r�||d-<n|�r�|�r�||d.<n||d/<|�s�|d�r�|d0�s�t||�|WS||d0<|�r�|�r�d1}td2�r|�r�dnd|d<|�r�d3|�d4�n|d|d<t||�|WS|�rYt|�d-dh�st
d5|||d6�}nt
d7|||||d8�}d9|�d4�|d<|d:k�rYt|fd;di|��}t||�t|||��sL|WSt |t!�"|�|�
d<d=��|�ra|d:k�r�t#|d:k�oh|�}|�ro|nd}t|f||d>�|��}t||�t|||��s�|WSW|SW|Sttf�y�}zd|d<t|�|d<i|d0<WYd}~|Sd}~ww)?a

    Ensure a private key is present as specified.

    This function accepts the same arguments as :py:func:`x509.create_private_key <salt.modules.x509_v2.create_private_key>`,
    as well as most ones for :py:func:`file.managed <salt.states.file.managed>`.

    .. note::

        If ``mode`` is unspecified, it will default to ``0400``.

    name
        The path the private key should be present at.

    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 serialized
        as a ``pem`` text, binary ``der`` or ``pkcs12`` file.
        Defaults to ``pem``.

    new
        Always create a new key. Defaults to false.
        Combining new with :mod:`prereq <salt.states.requisites.prereq>`
        can allow key rotation whenever a new certificate is generated.

    overwrite
        Overwrite an existing private key if the provided passphrase cannot decrypt it.
        Defaults to false.

    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>`_.

    Example:

    The Jinja templating in this example ensures a new private key is generated
    if the file does not exist and whenever the associated certificate
    is to be renewed.

    .. code-block:: jinja

        Manage www private key:
          x509.private_key_managed:
            - name: /etc/pki/www.key
            - keysize: 4096
            - new: true
        {%- if salt["file.file_exists"]("/etc/pki/www.key") %}
            - prereq:
              - x509: /etc/pki/www.crt
        {%- endif %}
    �bitsrz>`bits` has been renamed to `keysize`. Please update your code.>r��cipher�verboseTz'The private key is in the correct staterNrr��modeZ0400)�ed25519�ed448z$keysize is an invalid parameter for Fr rr#rr$r%r&r'r(r)r,zbThe provided passphrase cannot decrypt the private key. Pass overwrite: true to force regenerationr*r.r�r/z�The existing file does not seem to be a private key formatted as DER, PEM or embedded in PKCS12. Pass overwrite: true to force regenerationzPrivate key is unencryptedzPrivate key is encryptedz]The existing file is encrypted. Pass overwrite: true to force regeneration without passphraser�i�ec�r�r��algo)r�r��keysizer0rQrPrrRr!z The private key would have been rSzx509.encode_private_key)r*r0zx509.create_private_key)r�r�r*r0rUzThe private key has been rr"rVrWrX)$rZr[r\r]r_�intersectionr�rarrdr
rerfrgrhrirjr9Zload_privkeyrkrrlZget_key_typeZKEY_TYPEZRSAZECZED25519ZED448Zkey_sizerr{r|r}r~rr�)rr�r�r*r0�newZ	overwriterUr�Zignored_paramsr=r�r�r�rr�r�r�r�r�r"Zfile_exists�_r�Zkey_typeZ
check_keysize�pkr�rYrrr�private_key_managed�shN�
��
�

���



�������
��$



��


�
���

��
��

����
�
����r�cs$tt�dh��fdd�|��D�S)N�	check_cmdcsi|]\}}|�vr||�qSrr)r<�k�v��ignorerr�
<dictcomp>sz1_filter_state_internal_kwargs.<locals>.<dictcomp>)r{�_STATE_INTERNAL_KEYWORDS�items)r�rr�rrb�srbcCsHgd�}ddi}i}|��D]\}}||vr|||<q|||<q||fS)N)�user�groupr�Zattrs�makedirsZdir_moderVrr&r�Ztmp_dirZtmp_extZselinuxr0Zencoding_errorsZ	win_ownerZ	win_permsZwin_deny_permsZwin_inheritanceZwin_perms_resetZshow_changesF)r�)r�Zvalid_file_argsr�r�r�r�rrrras

racCs<|ddtddd�|d<d|vrg|d<|d�|�dS)Nr�file�__id__Zmanaged)r�stater�Zfun�lowZ
sub_state_run)Z__low__r�)r��subrrrrf%s
�rfcKsF|dvrtd��|p
td}tdd|fd|i|��}|tt|��S)N)NTz#test param can only be None or Truer!zstate.singlezfile.managed)rrrgr�r�)rr!r��resrrrre1s
recCs<|ddurd|d<d|sdnd�d�|d<i|d<dSd	S)
NrFz
Could not rryz file, see file.managed outputrrTr)Zfretr�r�rrrr|:s�r|c	Ksbt�|�}||d<t�td||d�|�|�d�}tj|fd|dui|��\}}}}||||fS)NrCzx509.get_signing_policy)r@Zskip_load_signing_private_key)�copy�deepcopyr9Zmerge_signing_policyrgr_Z	build_crt)	r@rArCr�r�r�r�r�rErrrrsEs
�
���rscCs�i}|durt|d�|jkr||d<t�t|d�|���s!d|d<|r/t�||���s/d|d<t|d�|jkr@t|d���|d<t|d	�|jkrQt|d	���|d
<t	||�}t
|���r`||d<|S)NZ_serial_numberrKZ_public_keyTrGrC�
_subject_name�subject_name�_issuer_name�issuer_namer�)�
_getattr_saferKr9Zmatch_pubkeyrFZverify_signaturerJ�rfc4514_string�issuer�
_compare_extsrlr�)r�r�rErKrLrMr�ext_changesrrrrzXs0����
rzcCsFi}t|d|j�st|d���|d<t||�}t|���r!||d<|S)Nr�r�r�)�_compareattr_saferJr�r�r�rlr�)r�r�rr�rrrr�ys��
r�c
Cs�dd�}dd�}i}t|d�|jkrt|d���|d<|�|�s$d|d<gggd	�}t|d
�}|D][}|�|j�}	|	durI|d�t�|j��q1|j	D]%}
||	j	|
j
�}t|du|j|
jk|j
|
j
kf�rq|d�t�|j��qL|	j	D]}||j	|j
�dur�|d�t�|j��quq1|D]}|||j�dur�|d
�t�|j��q�t|���r�||d<t||�}t|���r�||d<|S)Nc�.z�fdd�|D�dWStyYdSw)Nc�g|]	}|j�kr|�qSr)rKr;��serialrrr>��zS_compare_crl.<locals>._get_revoked_certificate_by_serial_number.<locals>.<listcomp>r��
IndexError)r�r�rr�r�)_get_revoked_certificate_by_serial_number��
�z?_compare_crl.<locals>._get_revoked_certificate_by_serial_numbercr�)Ncr�r��oidr;r�rrr>�r�z@_compare_crl.<locals>._get_extension_for_oid.<locals>.<listcomp>rr�)r�r�rr�r�_get_extension_for_oid�r�z,_compare_crl.<locals>._get_extension_for_oidr�r�TrF��added�changedr�Z_revoked_certificatesr�r�r�Zrevocationsr�)r�r�r�Zis_signature_validZ(get_revoked_certificate_by_serial_numberrKr�r9Zdec2hexr�r�rl�criticalr�r�r�)
r�r�Z
sig_pubkeyr�r�rZrev_changesr�r�Zcur�ext�cur_extr�rrrr��sR




���
��
��
r�c		Cs�dd�}g}g}g}t�t|d��}t|�D]0}z|j�|jj�}|j|jks-|j|jkr4|�	||��Wqtj
yF|�	||��Yqw|jD]}z	|�|jj�WqJtj
yf|�	||��YqJw|||d�S)NcSs&z|jjWSty|jjYSw�N)r��_nameroZ
dotted_string)r�rrr�
getextname�s

�z!_compare_exts.<locals>.getextnameZ_extensionsr�)r�Z
Extensionsr�r�r�Zget_extension_for_oidr�r�r�r�r�)	r�r�r�r�r�r�Zbuilder_extensionsr�r�rrrr��s*��
�r�cCsPt|�t|�ks
dSt|�D]\}}|�t���||�t���kr%dSqdS)NFT)r��	enumerateZfingerprintr	�SHA256)r�r��iZnew_certrrrrr�s��rrc
CsBzt||�WSty }ztd|�d|jj�d��|�d}~ww)NzCould not get attribute z from z.. Did the internal API of cryptography change?)�getattrror�	__class__�__name__)�obj�attrr�rrrr��s����r�cCs&zt||�|kWStyYdSw)NF)r�ro)r�r��comprrrr��s
�r�cCs�tjjjtjjjd�}tjj�|d��
}|�|�Wd�n1s#wYtjj�||td|�t	d�tjj�
|�dS)z~
    Create a temporary file with only user r/w perms and atomically
    copy it to the destination, honoring ``backup``.
    )�prefix�wbNzconfig.backup_modeZcachedir)rZr[�filesZmkstempZTEMPFILE_PREFIXZfopen�write�copyfilergrZsafe_rm)�dst�datarV�tmpZtmp_rrrr}s��r})NNNrNNFrNNNNNNNNNNNNNFN)NNNFNrrN)NrrN)r�NNrFFFr�)NNN)5�__doc__r~r��loggingZos.pathrhrrrZsalt.utils.filesrZZsalt.exceptionsrrZ
salt.staterr�Zcryptography.x509r
r�Zcryptography.exceptionsrZcryptography.hazmat.primitivesr	Zsalt.utils.x509r[r9r�ImportError�	getLoggerr�rwrrr�r�r�r�r�rbrarfrer|rsrzr�r�r�rrr�r�r}rrrr�<module>s�8�

�<
�n
�R
�!
	
�!@