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.cpython-310.pyc
o

�N�g*o�@s�dZddlZddlZddlZddlZddlZddlZddlZzddl	m
Z
Wn	ey/Ynwe�e
�Zdd�Zdd�Zdd	�Zd&dd
�Z	
					d'dd�Zdd�Zd(dd�Zdd�Zdd�Zdd�Zd)dd�Z					 	!	d*d"d#�Zd(d$d%�ZdS)+a"
Manage X509 Certificates

.. versionadded:: 2015.8.0

:depends: M2Crypto

.. deprecated:: 3006.0

.. warning::
    This module has been deprecated and will be removed
    in Salt 3009 (Potassium). Please migrate to the replacement
    modules. For breaking changes between both versions,
    you can refer to the :ref:`x509_v2 execution module docs <x509-setup>`.

    They will become the default ``x509`` modules in Salt 3008 (Argon).
    You can explicitly switch to the new modules before that release
    by setting ``features: {x509_v2: true}`` in your minion configuration.


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.

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

For remote signing, peers must be permitted to remotely call the
:mod:`sign_remote_certificate <salt.modules.x509.sign_remote_certificate>` function.


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

.. code-block:: yaml

    peer:
      .*:
        - x509.sign_remote_certificate


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

/srv/salt/ca.sls

.. code-block:: yaml

    /etc/salt/minion.d/x509.conf:
      file.managed:
        - 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

    /etc/pki:
      file.directory

    /etc/pki/issued_certs:
      file.directory

    /etc/pki/ca.key:
      x509.private_key_managed:
        - bits: 4096
        - backup: True

    /etc/pki/ca.crt:
      x509.certificate_managed:
        - 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,issuer:always
        - days_valid: 3650
        - days_remaining: 0
        - backup: True
        - require:
          - file: /etc/pki


The signing policy defines properties that override any property requested or included in a CRL. It also
can define a restricted list of minions which are allowed to remotely invoke this signing policy.

/srv/salt/x509.conf

.. code-block:: yaml

    mine_functions:
      x509.get_pem_entries: [/etc/pki/ca.crt]

    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,issuer:always
        - days_valid: 90
        - copypath: /etc/pki/issued_certs/


This state will instruct all minions to trust certificates signed by our new CA.
Using Jinja to strip newlines from the text avoids dealing with newlines in the rendered YAML,
and the  :mod:`sign_remote_certificate <salt.states.x509.sign_remote_certificate>` state will
handle properly formatting the text before writing the output.

/srv/salt/cert.sls

.. code-block:: jinja

    /usr/local/share/ca-certificates:
      file.directory

    /usr/local/share/ca-certificates/intca.crt:
      x509.pem_managed:
        - text: {{ salt['mine.get']('ca', 'x509.get_pem_entries')['ca']['/etc/pki/ca.crt']|replace('\n', '') }}


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

/srv/salt/www.sls

.. code-block:: yaml

    /etc/pki/www.crt:
      x509.private_key_managed:
        - name: /etc/pki/www.key
        - bits: 4096
        - backup: True

    /etc/pki/www.crt:
      x509.certificate_managed:
        - ca_server: ca
        - signing_policy: www
        - public_key: /etc/pki/www.key
        - CN: www.example.com
        - days_remaining: 30
        - backup: True

This other state creates a private key then requests a certificate signed by ca
according to the www policy but adds a strict date range for the certificate to
be considered valid.

/srv/salt/www-time-limited.sls

.. code-block:: yaml

    /etc/pki/www-time-limited.crt:
      x509.certificate_managed:
        - ca_server: ca
        - signing_policy: www
        - public_key: /etc/pki/www-time-limited.key
        - CN: www.example.com
        - not_before: 2019-05-05 00:00:00
        - not_after: 2020-05-05 14:30:00
        - backup: True

�N)�RSAErrorcCs2td�d�r	dSdtvrtjj�dd�dSdS)	zO
    only load this module if the corresponding execution module is loaded
    ZfeaturesZx509_v2)FzSuperseded, using x509_v2�x509.get_pem_entryZ	Potassiumz�The x509 modules are deprecated. Please migrate to the replacement modules (x509_v2). They are the default from Salt 3008 (Argon) onwards.Zx509)Fz/Could not load x509 state: m2crypto unavailable)�__opts__�get�__salt__�salt�utilsZversionsZ
warn_until�r	r	�D/opt/saltstack/salt/lib/python3.10/site-packages/salt/states/x509.py�__virtual__�s�rcCshg}|D]-}|��D]&}i}|D]}|��D]\}}t|tj�r%|�d�}|||<qq|�|�q
q|S)ze
    Turn the mess of OrderedDicts and Lists into a list of dicts for
    use in the CRL module.
    �%Y-%m-%d %H:%M:%S)�values�items�
isinstance�datetime�strftime�append)ZrevsZlist_ZrevZpropsZdict_ZpropZpropname�valr	r	r
�_revoked_to_list�s

��	rcKsLgd�}i}i}|��D]\}}||vr|||<q|||<q||d<||fS)N)	�user�group�mode�makedirsZdir_mode�backup�create�follow_symlinksZ	check_cmd�name)r)r�kwargsZvalid_file_args�	file_args�
extra_args�k�vr	r	r
�_get_file_args�s

r"�FcCsjd}tj�|�r.z
td||d�}WntjjyYnty-|s+tj�d��Ynw||ko4|S)Nrzx509.get_private_key_size)Zprivate_key�
passphrasez7The provided passphrase cannot decrypt the private key.)	�os�path�isfilerr�
exceptions�SaltInvocationErrorrZCommandExecutionError)r�bitsr$�new�	overwriteZcurrent_bitsr	r	r
�_check_private_keys 
����r-�aes_128_cbcTcKs�t|fi|��\}}d}	t|||||d�r td|dd�|d<nd}	tdd||||d	�|d<tjj�|d�|d<td
di|��}
|
drO|	rOdd
i|
d<|
S)a!
    Manage a private key's existence.

    name:
        Path to the private key

    bits:
        Key length in bits. Default 2048.

    passphrase:
        Passphrase for encrypting the private key.

    cipher:
        Cipher for encrypting the private key.

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

    overwrite:
        Overwrite an existing private key if the provided passphrase cannot decrypt it.

    verbose:
        Provide visual feedback on stdout, dots while key is generated.
        Default is True.

        .. versionadded:: 2016.11.0

    kwargs:
        Any kwargs supported by file.managed are supported.

    Example:

    The JINJA templating in this example ensures a private key is generated if the file doesn't exist
    and that a new private key is generated whenever the certificate that uses it is to be renewed.

    .. code-block:: jinja

        /etc/pki/www.key:
          x509.private_key_managed:
            - bits: 4096
            - new: True
            {% if salt['file.file_exists']('/etc/pki/www.key') -%}
            - prereq:
              - x509: /etc/pki/www.crt
            {%- endif %}
    F)r*r$r+r,rz(?:RSA )?PRIVATE KEY�Zpem_type�contentsTzx509.create_private_key)�textr*r$�cipher�verbose�file.managed�changesr+zNew private key generatedNr	)r"r-rrr�stringutilsZto_str�
__states__)rr*r$r2r+r,r3rrZnew_key�retr	r	r
�private_key_manageds":
��

�r9cKs�ztd|�}Wntjjy|�d�}Ynwt|fi|��\}}tddddi|��|d<tddi|��}|drPtd|d�}||krP||d	�|d<|S)a�
    Manage a Certificate Signing Request

    name:
        Path to the CSR

    properties:
        The properties to be added to the certificate request, including items like subject, extensions
        and public key. See above for valid properties.

    kwargs:
        Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.

    Example:

    .. code-block:: yaml

        /etc/pki/mycert.csr:
          x509.csr_managed:
             - private_key: /etc/pki/mycert.key
             - CN: www.example.com
             - C: US
             - ST: Utah
             - L: Salt Lake City
             - keyUsage: 'critical dataEncipherment'
    z
x509.read_csrz is not a valid csr.zx509.create_csrr1Tr0r4r5�ZOldZNewNr	)rrr(r)r"r7)rr�oldrr8r+r	r	r
�csr_managedks�r<c
	Cs�t�|�}t�|�}gd�}tddur|�d�|D]}|�|d�|�|d�q|sb|�dd�|�dd�z t�dd|d	d
�|d	d
<t�dd|d	d
�|d	d
<Wn	tyaYnwg}|��D]�\}}t	|t
�rxtjj
�|�}zk|||kr�|dkr�|d|dkr�|�|�nQ|d
kr�|d|dkr�|�|�n?|d	kr�|��}||��}	zt�dd|d
�|d
<t�dd|	d
�|	d
<Wn	ty�Ynw||	kr�|�|�n|�|�Wqhty�|�|�Yqhwt|�dk|fS)af
    Return true if the provided certificate information matches the
    required certificate information, i.e. it has the required common
    name, subject alt name, organization, etc.

    cert_info should be a dict as returned by x509.read_certificate.
    required_cert_info should be a dict as returned by x509.create_certificate with testrun=True.
    )z
Not Before�	Not AfterzSHA1 Finger PrintzSHA-256 Finger Print�Issuer Public KeyZ	fips_modeFzMD5 Finger PrintNz
Serial Numberz!serial:([0-9A-F]{2}:)*[0-9A-F]{2}z	serial:--zX509v3 ExtensionsZauthorityKeyIdentifierzSubject HashZSubjectzIssuer HashZIssuerzDirName:([^\n]+)z
Dirname:--r)�copy�deepcopyrr�pop�re�sub�KeyErrorrr�strrrr6�to_bytes�len)
�	cert_info�required_cert_info�check_serialZignored_keys�key�diffr r!Zv_extZ
cert_info_extr	r	r
�_certificate_info_matches�s�




�
��

�
����
�
��rMcCs:z|d}tj�|d�tj��jWStyYdSw)zV
    Get the days remaining on a certificate, defaulting to 0 if an error occurs.
    r=rr)r�strptime�now�daysrD)rHZexpiryr	r	r
�_certificate_days_remaining�s���rQc
Ks`tj�|�sd|�d�ifSz�td|d�}tddddi|��}t|t�s/tj�d�	|���z|d	}td
||�sJd|vrAdnd
}d||fWWSWnt
yZdd|fYWSwt||d|vd�\}}	|stdd�	d�|	��|fWSt
|�}
|dkr�|
|kr�dd�	|
|�|fWSdd|fWStjjy�}zd|�dt|���ifWYd}~Sd}~ww)z�
    Return True if the given certificate file exists, is a certificate, matches the given specification,
    and has the required days remaining.

    If False, also provide a message explaining why.
    Fz does not exist�x509.read_certificate�Zcertificate�x509.create_certificateZtestrunTz7Unable to create new certificate: x509 module error: {}r>zx509.verify_signature�signing_private_keyz0Certificate is not signed by private_signing_keyz1Certificate is not signed by the requested issuerz4New certificate does not include signing informationZ
serial_number)rJz(Certificate properties are different: {}z, rzKCertificate needs renewal: {} days remaining but it needs to be at least {}�z is not a valid certificate: Nr	)r%r&r'rr�dictrr(r)�formatrDrM�joinrQrE)r�days_remaining�append_certsZ	cert_specrHrIZissuer_public_key�errmsg�matchesrLZactual_days_remaining�er	r	r
�_certificate_is_validsd
��
�����
��

���$��r_cCsbtdd	i|��}|d|d<|drd�|d�|d<n|d|d<|dr/d|di|d<|S)
z�
    Run file.managed and merge the result with an existing return dict.
    The overall True/False result will be the result of the file.managed call.
    r4�resultz&Certificate {} is valid and up to dater�commentr5ZFileNr	)r7rX)r8rZfile_retr	r	r
�_certificate_file_managed?srb�ZcKsFd|vr	|�d�}d|vrd|vrtj�d��d|vr)d|vr)d|vr)tj�d��|d	id
d�}t|||fi|��\}}}|rNt|fi|��\}}	t||�Stdr|t|fi|��\}}	d
|d
<t||�}d|d<d|�d�|d<|dd�|dd<|Stdd#ddi|��}
ztd|
�Wn$tjjy�}zd	|d<d�	|t
|��|d<|WYd}~Sd}~ww|s�g}|D]7}ztd|dd�}
|
|
7}
Wq�tjjy�}zd	|d<d�	||t
|��|d<|WYd}~Sd}~wwt|fi|��\}}	|
|d
<t||�}|d�r!|td|d �d�|dd!<|d"d�|dd<|S)$a�
    Manage a Certificate

    name
        Path to the certificate

    days_remaining : 90
        Recreate the certificate if the number of days remaining on it
        are less than this number. The value should be less than
        ``days_valid``, otherwise the certificate will be recreated
        every time the state is run. A value of 0 disables automatic
        renewal.

    append_certs:
        A list of certificates to be appended to the managed file.
        They must be valid PEM files, otherwise an error will be thrown.

    kwargs:
        Any arguments supported by :py:func:`x509.create_certificate
        <salt.modules.x509.create_certificate>` or :py:func:`file.managed
        <salt.states.file.managed>` are supported.

    not_before:
        Initial validity date for the certificate. This date must be specified
        in the format '%Y-%m-%d %H:%M:%S'.

        .. versionadded:: 3001
    not_after:
        Final validity date for the certificate. This date must be specified in
        the format '%Y-%m-%d %H:%M:%S'.

        .. versionadded:: 3001

    Examples:

    .. code-block:: yaml

        /etc/pki/ca.crt:
          x509.certificate_managed:
            - 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,issuer:always
            - days_valid: 3650
            - days_remaining: 0
            - backup: True


    .. code-block:: yaml

        /etc/ssl/www.crt:
          x509.certificate_managed:
            - ca_server: pki
            - signing_policy: www
            - public_key: /etc/ssl/www.key
            - CN: www.example.com
            - days_valid: 90
            - days_remaining: 30
            - backup: True

    r&Z	ca_serverZsigning_policyz1signing_policy must be specified if ca_server is.Z
public_keyrUZcsrz:public_key, signing_private_key, or csr must be specified.FrV)rr`r5ra�testr0Nr`zCertificate z will be createdraz(Certificate will be valid and up to dater:r5ZStatusrTr1TrRz{An error occurred creating the certificate {}. The result returned from x509.create_certificate is not a valid PEM file:
{}r�CERTIFICATEr/zy{} is not a valid certificate file, cannot append it to the certificate {}.
The error returned by the x509 module was:
{}rS�Certificatez#Certificate is valid and up to dater	)rArr(r)r_r"rbrrrXrE)rrZr[rr8Zis_validZinvalid_reasonZcurrent_cert_inforrr0r^Zappend_fileZappend_file_contentsr	r	r
�certificate_managedRs�C
����

�����
����


��rg�drV�c	
Ks||durg}t|�}d}
i}tj�|�rQz,td|d�}|��}|�d�|�d�}
tj�|
d�tj�	�j
}
|dkr?|
d}Wntjj
yP|�d	�}Ynw|�d
�}tdd|||||||d
�}td|d�}|��}|�d�|�d�t|fi|	��\}}	d}||kr�|
|kr�td||�r�td|dd�|d<nd}||d<tddi|��}|r�|td|d�d�|d<|S)a�
    Manage a Certificate Revocation List

    name
        Path to the certificate

    signing_private_key
        The private key that will be used to sign the CRL. This is
        usually your CA's private key.

    signing_private_key_passphrase
        Passphrase to decrypt the private key.

    signing_cert
        The certificate of the authority that will be used to sign the CRL.
        This is usually your CA's certificate.

    revoked
        A list of certificates to revoke. Must include either a serial number or a
        the certificate itself. Can optionally include the revocation date and
        notAfter date from the certificate. See example below for details.

    days_valid : 100
        The number of days the certificate should be valid for.

    digest
        The digest to use for signing the CRL. This has no effect on versions
        of pyOpenSSL less than 0.14.

    days_remaining : 30
        The CRL should be automatically recreated if there are less than
        ``days_remaining`` days until the CRL expires. Set to 0 to disable
        automatic renewal.

    include_expired : False
        If ``True``, include expired certificates in the CRL.

    kwargs
        Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.

    Example:

    .. code-block:: yaml

        /etc/pki/ca.crl:
          x509.crl_managed:
            - signing_private_key: /etc/pki/myca.key
            - signing_cert: /etc/pki/myca.crt
            - revoked:
              - compromized_Web_key:
                - certificate: /etc/pki/certs/badweb.crt
                - revocation_date: 2015-03-01 00:00:00
                - reason: keyCompromise
              - terminated_vpn_user:
                - serial_number: D6:D2:DC:D8:4D:5C:C0:F4
                - not_after: 2016-01-01 00:00:00
                - revocation_date: 2015-02-25 00:00:00
                - reason: cessationOfOperation
    Nrz
x509.read_crl)ZcrlzLast UpdatezNext Updater�z is not a valid CRL.z does not exist.zx509.create_crlT)r1rU�signing_private_key_passphrase�signing_cert�revoked�
days_valid�digest�include_expiredFzx509.verify_crlrzX509 CRLr/r0r4r:r5r	)rr%r&r'rr?rArrNrOrPrr(r)r"r7)rrUrkrlrmrnrorZrprZcurrent_days_remainingZcurrent_comp�currentZcurrent_notafterZnew_crlr+Znew_comprZnew_crl_createdr8r	r	r
�crl_managed�shG

����
�

��rrcKs8t|fi|��\}}td|d�|d<tddi|��S)aC
    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:
        Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
    r)r1r0r4Nr	)r"rr7)rr1rrrr	r	r
�pem_managedxs
rs)r#NFF)r#Nr.FFT)F)rcN)NNNrhrVriF)�__doc__r?r�loggingr%rBZsalt.exceptionsrZsalt.utils.versionsZM2Crypto.RSAr�ImportError�	getLogger�__name__�logrrr"r-r9r<rMrQr_rbrgrrrsr	r	r	r
�<module>sV:�


�R
,[?
&
�