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

�N�gA��
@s�dZddlZddlZddlZddlZddlZddlZddlZddlmZddl	Z
ddlZ
ddlZ
ddl
mZddlmZdZdazddlZdZeej�dd	��ZWn	eyZYnwe�e�Zd
ZdZdd
�Zdd�Zdd�Zd]dd�Z d]dd�Z!dd�Z"dd�Z#dd�Z$d]dd�Z%d^dd �Z&d_d!d"�Z'd_d#d$�Z(d]d%d&�Z)d`d'd(�Z*	dad*d+�Z+	dad,d-�Z,d.d/�Z-d0d1�Z.d2d3�Z/dbd5d6�Z0d7d8�Z1	9	:	)	;	<	=	>						?			dcd@dA�Z2dBdC�Z3	9	)	;	<	=	>								?		D	dddEdF�Z4	G	9	:	)	;	<	=	>					?	dedHdI�Z5	:					?			dfdJdK�Z6dgdMdN�Z7dhdOdP�Z8	?didQdR�Z9						?djdSdT�Z:edUk�rOe4dVdWd;d<dXd>ddYdZ�e6dVdW�e7dVdWd[d\�dSdS)kaX
A salt module for SSL/TLS.  Can create a Certificate Authority (CA)
or use Self-Signed certificates.

:depends: PyOpenSSL Python module (0.10 or later, 0.14 or later for X509
    extension support)

:configuration: Add the following values in /etc/salt/minion for the CA module
    to function properly:

    .. code-block:: yaml

        ca.cert_base_path: '/etc/pki'


CLI Example #1:
Creating a CA, a server request and its signed certificate:

.. code-block:: bash

    # salt-call tls.create_ca my_little \
    days=5 \
    CN='My Little CA' \
    C=US \
    ST=Utah \
    L=Salt Lake City \
    O=Saltstack \
    emailAddress=pleasedontemail@example.com

    Created Private Key: "/etc/pki/my_little/my_little_ca_cert.key"
    Created CA "my_little_ca": "/etc/pki/my_little_ca/my_little_ca_cert.crt"

    # salt-call tls.create_csr my_little CN=www.example.com
    Created Private Key: "/etc/pki/my_little/certs/www.example.com.key
    Created CSR for "www.example.com": "/etc/pki/my_little/certs/www.example.com.csr"

    # salt-call tls.create_ca_signed_cert my_little CN=www.example.com
    Created Certificate for "www.example.com": /etc/pki/my_little/certs/www.example.com.crt"

CLI Example #2:
Creating a client request and its signed certificate

.. code-block:: bash

    # salt-call tls.create_csr my_little CN=DBReplica_No.1 cert_type=client
    Created Private Key: "/etc/pki/my_little/certs//DBReplica_No.1.key"
    Created CSR for "DBReplica_No.1": "/etc/pki/my_little/certs/DBReplica_No.1.csr"

    # salt-call tls.create_ca_signed_cert my_little CN=DBReplica_No.1
    Created Certificate for "DBReplica_No.1": "/etc/pki/my_little/certs/DBReplica_No.1.crt"

CLI Example #3:
Creating both a server and client req + cert for the same CN

.. code-block:: bash

    # salt-call tls.create_csr my_little CN=MasterDBReplica_No.2  \
        cert_type=client
    Created Private Key: "/etc/pki/my_little/certs/MasterDBReplica_No.2.key"
    Created CSR for "DBReplica_No.1": "/etc/pki/my_little/certs/MasterDBReplica_No.2.csr"

    # salt-call tls.create_ca_signed_cert my_little CN=MasterDBReplica_No.2
    Created Certificate for "DBReplica_No.1": "/etc/pki/my_little/certs/DBReplica_No.1.crt"

    # salt-call tls.create_csr my_little CN=MasterDBReplica_No.2 \
        cert_type=server
    Certificate "MasterDBReplica_No.2" already exists

    (doh!)

    # salt-call tls.create_csr my_little CN=MasterDBReplica_No.2 \
        cert_type=server type_ext=True
    Created Private Key: "/etc/pki/my_little/certs/DBReplica_No.1_client.key"
    Created CSR for "DBReplica_No.1": "/etc/pki/my_little/certs/DBReplica_No.1_client.csr"

    # salt-call tls.create_ca_signed_cert my_little CN=MasterDBReplica_No.2
    Certificate "MasterDBReplica_No.2" already exists

    (DOH!)

    # salt-call tls.create_ca_signed_cert my_little CN=MasterDBReplica_No.2 \
        cert_type=server type_ext=True
    Created Certificate for "MasterDBReplica_No.2": "/etc/pki/my_little/certs/MasterDBReplica_No.2_server.crt"


CLI Example #4:
Create a server req + cert with non-CN filename for the cert

.. code-block:: bash

    # salt-call tls.create_csr my_little CN=www.anothersometh.ing \
        cert_type=server type_ext=True
    Created Private Key: "/etc/pki/my_little/certs/www.anothersometh.ing_server.key"
    Created CSR for "DBReplica_No.1": "/etc/pki/my_little/certs/www.anothersometh.ing_server.csr"

    # salt-call tls_create_ca_signed_cert my_little CN=www.anothersometh.ing \
        cert_type=server cert_filename="something_completely_different"
    Created Certificate for "www.anothersometh.ing": /etc/pki/my_little/certs/something_completely_different.crt
�N)�datetime)�CommandExecutionError)�VersionFT�__version__z0.0z
%y%m%d%H%M%SZ�
%Y%m%d%H%M%SZcCsPtr$ttd�kr$ttd�krdat�d�dSttd�kr"t�d�dSdadS)	z@
    Only load this module if the ca config options are set
    z0.10z0.14FzfYou should upgrade pyOpenSSL to at least 0.14.1 to enable the use of X509 extensions in the tls modulez0.15zkYou should upgrade pyOpenSSL to at least 0.15.1 to enable the full use of X509 extensions in the tls moduleT)FzQPyOpenSSL version 0.10 or later must be installed before this module can be used.)�HAS_SSL�OpenSSL_versionr�X509_EXT_ENABLED�log�debug�rr�D/opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/tls.py�__virtual__�s���rcCs(t�t���\}}t|�}|d�|��S)zD
    Return a Unix timestamp as a string of digits
    :return:
    �f)�math�modf�time�int)�val1Zval2rrr
�
_microtime�srcCst�|td|��S)zt
    Return the value corresponding to the key in __context__ or if not present,
    fallback to config.option.
    z
config.option)�__context__�get�__salt__)�keyrrr
�_context_or_config�srcCs|p	td�p	td�S)z�
    Return the base path for certs from CLI or from options

    cacert_path
        absolute path to ca certificates root directory

    CLI Example:

    .. code-block:: bash

        salt '*' tls.cert_base_path
    �ca.contextual_cert_base_pathzca.cert_base_path)r��cacert_pathrrr
�cert_base_path�s
��rcCst|�S)z!
    Retrocompatible wrapper
    )rrrrr
�_cert_base_path�srcCs|r|td<t�S)z�
    If wanted, store the aforementioned cacert_path in context
    to be used as the basepath for further operations

    CLI Example:

    .. code-block:: bash

        salt '*' tls.set_ca_path /etc/certs
    r)rrrrrr
�set_ca_path�sr c	Cs�tt�d�tjj�t��t	�
d�f��d�}t�d|�t
d}t�d|�|�d|�d�}t	j�|�s9t	�|�t	j�|�sBd	}nd
}tjj�||��}|�t|��Wd�|S1s_wY|S)z�
    Return a serial number in hex using os.urandom() and a Unix timestamp
    in microseconds.

    ca_name
        name of the CA
    CN
        common name in the request
    �_��zHashnum: %s�cachedirzcachedir: %s�/z.serial�w�a+N)r�binascii�hexlify�join�salt�utils�stringutils�to_bytesr�os�urandomr
rZ__opts__�path�exists�makedirs�files�fopen�write�str)�ca_nameZhashnumr$Zserial_file�mode�ofilerrr
�_new_serial�s2
����

��r;cCs
|�t�S�N)�strftime�two_digit_year_fmt)ZdatetimeObjrrr
�_four_digit_year_to_two_digit	s
r?cCs||durt��d|��}|�d�}t|�}tt|��}t|��d�}d}|d�dd�|����D��7}|d7}||||fS)z6
    Get basic info to write out to the index.txt
    Nr%z
/index.txt�XcSsg|]\}}|�d|���qS)�=r)�.0�x�yrrr
�
<listcomp>sz#_get_basic_info.<locals>.<listcomp>�
)	r�
_read_certr?�_get_expiration_date�format�get_serial_numberr*�get_subject�get_components)r8�cert�ca_dir�
index_file�expire_date�
serial_number�subjectrrr
�_get_basic_info
s
 rS�VcCs�t|�t��d|��}t|||�\}}}}d�||||�}	tjj�|d��}
|
�tjj	�
|	��Wd�dS1s<wYdS)z�
    write out the index.txt database file in the appropriate directory to
    track certificates

    ca_name
        name of the CA
    cert
        certificate to be recorded
    r%z{}	{}		{}	unknown	{}r'N)r rrSrIr+r,r4r5r6r-�to_str)r8rMr�statusrNrOrPrQrRZ
index_datar:rrr
�_write_cert_to_database$s
��"�rWcCs�t|�|s|�d�}t��d|�d|�d�}t��d|�d|�d�}tjj�|���}tj�tjj	|�
��}|��dkr�t�
d|�tjj�|��\}ztj�tjj	|�
��}|��}	Wntyfd}	Ynwzt�|��d�t��j}
Wn
ttfy�d	}
Ynw|��}t||	|
|j|j|j|j|j|j|j d
d�Wd�n1s�wYWd�dSWd�dSWd�dS1s�wYdS)
a�
    Check that the X509 version is correct
    (was incorrectly set in previous salt versions).
    This will fix the version if needed.

    ca_name
        ca authority name
    cacert_path
        absolute path to ca certificates root directory
    ca_filename
        alternative filename for the CA

        .. versionadded:: 2015.5.3

    CLI Example:

    .. code-block:: bash

        salt '*' tls.maybe_fix_ssl_version test_ca /etc/certs
    �_ca_certr%�.crt�.key�z2Regenerating wrong x509 version for certificate %s�r�mT)
�bits�days�CN�C�ST�L�O�OU�emailAddress�fixmodeN)!r rr+r,r4r5�OpenSSL�crypto�load_certificate�FILETYPE_PEM�readZget_versionr
�info�load_privatekeyr^�	Exceptionr�strptime�get_notAfter�utcnowr_�
ValueError�	TypeErrorrK�	create_car`rarbrcrdrerf)r8r�ca_filename�certp�ca_keyp�ficrM�fic2rr^r_Zsubjrrr
�maybe_fix_ssl_version<s^
���������"�r{cCsPt|�|s|�d�}t��d|�d|�d�}tj�|�r&t|||d�dSdS)ak
    Verify whether a Certificate Authority (CA) already exists

    ca_name
        name of the CA
    cacert_path
        absolute path to ca certificates root directory
    ca_filename
        alternative filename for the CA

        .. versionadded:: 2015.5.3

    CLI Example:

    .. code-block:: bash

        salt '*' tls.ca_exists test_ca /etc/certs
    rXr%rY�rrvTF)r rr/r1r2r{)r8rrvrwrrr
�	ca_existszs
r}cCs
t||�S)zRetrocompatible wrapper)r})r8rrrr
�
_ca_exists�s
r~cCszt|�d�t�|�}tj�|�std|����|r;tjj	�
|��}tjj�|�
��}Wd�|S1s6wY|S)a_
    Get the certificate path or content

    ca_name
        name of the CA
    as_text
        if true, return the certificate content instead of the path
    cacert_path
        absolute path to ca certificates root directory

    CLI Example:

    .. code-block:: bash

        salt '*' tls.get_ca test_ca as_text=False cacert_path=/etc/certs
    �{0}/{1}/{1}_ca_cert.crtzCertificate does not exist for N)r rIrr/r1r2rsr+r,r4r5r-�
to_unicoderl)r8�as_textrrwryrrr
�get_ca�s
��r��	localhostcC�t|�|s|}t��d|�d|�d�}tj�|�s!td|����|rDtjj�	|��}tjj
�|���}Wd�|S1s?wY|S)a:
    Get the certificate path or content

    ca_name
        name of the CA
    CN
        common name of the certificate
    as_text
        if true, return the certificate content instead of the path
    cacert_path
        absolute path to certificates root directory
    cert_filename
        alternative filename for the certificate, useful when using special characters in the CN

        .. versionadded:: 2015.5.3

    CLI Example:

    .. code-block:: bash

        salt '*' tls.get_ca_signed_cert test_ca CN=localhost as_text=False cacert_path=/etc/certs
    r%�/certs/rY� Certificate does not exists for N�
r rr/r1r2rsr+r,r4r5r-r�rl)r8r`r�r�
cert_filenamerwryrrr
�get_ca_signed_cert�s
��r�cCr�)ai
    Get the certificate path or content

    ca_name
        name of the CA
    CN
        common name of the certificate
    as_text
        if true, return the certificate content instead of the path
    cacert_path
        absolute path to certificates root directory
    key_filename
        alternative filename for the key, useful when using special characters

        .. versionadded:: 2015.5.3

        in the CN

    CLI Example:

    .. code-block:: bash

        salt '*' tls.get_ca_signed_key                 test_ca CN=localhost                 as_text=False                 cacert_path=/etc/certs
    r%r�rZr�Nr�)r8r`r�rZkey_filenameZkeypryrrr
�get_ca_signed_key�s
��r�cCs�t|t�r<z&tjj�|��}tj�tjj	|�
��Wd�WS1s$wYWdSty;t�
d|�YdSwt|d�sIt�d|�dS|S)Nz Failed to read cert from path %srqz"%s is not a valid cert path/object)�
isinstancer7r+r,r4r5rhrirjrkrlror
�	exception�hasattr�error)rMZrfhrrr
rGs
�(��
rGc

CsFtj��}t|�}|durtd|�d���t��d|��}t|�d|�d��}|�|�tjj}|�|j	|j
B�|durCtj��}n"tj
j�|��}	tj�tjj|	���}Wd�n1s`wY|�|�tj�||�}
i}z|
��d|d<W|Stjjy�}zt|�|d<|j|d	<d
|d<WYd}~|Sd}~ww)z�
    .. versionadded:: 3000

    Validate a certificate against a given CA/CRL.

    cert
        path to the certifiate PEM file or string

    ca_name
        name of the CA

    crl_file
        full path to the CRL file
    N�Failed to read cert from �, see log for detailsr%z_ca_cert.crtTZvalidr�Z
error_certF)rhriZ	X509StorerGrrZadd_cert�X509StoreFlagsZ	set_flagsZ	CRL_CHECKZ
CRL_CHECK_ALL�CRLr+r,r4r5Zload_crlrkrlZadd_crlZX509StoreContextZverify_certificateZX509StoreContextErrorr7Zcertificate)
rMr8�crl_file�store�cert_objrN�ca_certr��crl�fhr�context�ret�errr
�validates<

�
�

�
��r�cCs:t|�}|durtd|�d���t�tjj�|���t	�S)z,
    Returns a datetime.datetime object
    Nr�r�)
rGrrrpr+r,r-rUrq�four_digit_year_fmt)rMr�rrr
rHKs
��rH�%Y-%m-%dcCst|��|�S)a

    .. versionadded:: 2019.2.0

    Get a certificate's expiration date

    cert
        Full path to the certificate

    date_format
        By default this will return the expiration date in YYYY-MM-DD format,
        use this to specify a different strftime format string. Note that the
        expiration time will be in UTC.

    CLI Examples:

    .. code-block:: bash

        salt '*' tls.get_expiration_date /path/to/foo.crt
        salt '*' tls.get_expiration_date /path/to/foo.crt date_format='%d/%m/%Y'
    )rHr=)rMZdate_formatrrr
�get_expiration_date[sr�cCs�d}td}|dur,t|t�s|sddd�}nt|t�r,||�dkr,ddd�}t�d�|durSt|t�s>|r<ddd�}|St|t�rS||�dkrSddd�}t�d�|S)Nzcmd.retcodezonlyif condition is falseT)�comment�resultrzunless condition is true)rr�r7r
r)�onlyif�unlessr��retcoderrr
�_check_onlyif_unlessss*

�





�

r�r\r]�US�Utah�Salt Lake City�	SaltStack�sha256c"Cs�t||�}|durdSt|�|s|�d�}t��d|�d|�d�}t��d|�d|�d�}|s>|
s>t||d�r>d|�d�S|
rMtj�|�sMt|�d	���tj�t��d|���sdt�t��d|���d}tj�|�r�t	j
j�|��H}z
t
j�t
jj|���}Wn2t
jjy�}z$t�d
||�d�|t���d��}t�d
|�t�||�WYd}~nd}~wwWd�n1s�wY|s�t
j��}|�t
jj|�t
j��}|�d�|� t!|��||�"�_#||�"�_$||�"�_%||�"�_&|r�||�"�_'||�"�_(|	�r|	|�"�_)|�*d�|�+t,|�ddd�|�-|�"��|�.|�t/�rV|�0t
j�1ddd�t
j�1ddd�t
jj1ddd|d�g�|�0t
jj1ddd|d�g�|�2|t	j
j3�4|
��t
j�5t
jj|�}d}tj�|��r�d�|t���d��}t	j
j�|��N}t	j
j3�6|����7�}|�7�|�7�k�r�d}n/t�d|�t�8|tj9tj:Bd �}t	j
j�|d!��
}|�;|�Wd�n	1�s�wYWd�n	1�s�wY|�r
t�8|tj9tj:Bd �}t	j
j�|d"��}|�;t	j
j3�<|��Wd�n	1�swYt	j
j�|d"��} | �;t	j
j3�<t
j�=t
jj|���Wd�n	1�s2wYt>||�d#�t�||�}!|!d$�|t�|�7}!|!S)%a}
    Create a Certificate Authority (CA)

    ca_name
        name of the CA
    bits
        number of RSA key bits, default is 2048
    days
        number of days the CA will be valid, default is 365
    CN
        common name in the request, default is "localhost"
    C
        country, default is "US"
    ST
        state, default is "Utah"
    L
        locality, default is "Centerville", the city where SaltStack originated
    O
        organization, default is "SaltStack"
    OU
        organizational unit, default is None
    emailAddress
        email address for the CA owner, default is None
    cacert_path
        absolute path to ca certificates root directory
    ca_filename
        alternative filename for the CA

        .. versionadded:: 2015.5.3

    digest
        The message digest algorithm. Must be a string describing a digest
        algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically).
        For example, "md5" or "sha1". Default: 'sha256'
    replace
        Replace this certificate even if it exists

        .. versionadded:: 2015.5.1

    Writes out a CA certificate based upon defined config values. If the file
    already exists, the function just returns assuming the CA certificate
    already exists.

    If the following values were set::

        ca.cert_base_path='/etc/pki'
        ca_name='koji'

    the resulting CA, and corresponding key, would be written in the following
    location with appropriate permissions::

        /etc/pki/koji/koji_ca_cert.crt
        /etc/pki/koji/koji_ca_cert.key

    CLI Example:

    .. code-block:: bash

        salt '*' tls.create_ca test_ca
    NrXr%rYrZ�rvzCertificate for CA named "�" already existsz does not exists, can't fixz?Error loading existing private key %s, generating a new key: %sz{}.unloadable.{}z%Y%m%d%H%M%Sz"Saving unloadable CA ssl key in %s�r��<sbasicConstraintsTsCA:TRUE, pathlen:0skeyUsageskeyCertSign, cRLSignssubjectKeyIdentifierFshash)rRsauthorityKeyIdentifiersissuer:always,keyid:always)�issuerz{}.{}zSaving old CA ssl key in %s�r&�wbz$Created Private Key: "{}/{}/{}.key" z#Created CA "{0}": "{1}/{0}/{2}.crt")?r�r rr}r/r1r2rsr3r+r,r4r5rhrirnrkrl�Errorr
�warningrIrrrr=rm�rename�PKey�generate_key�TYPE_RSA�X509�set_version�set_serial_numberr;rKrarbrcrdrer`rf�gmtime_adj_notBefore�gmtime_adj_notAfterr�
set_issuer�
set_pubkeyr	�add_extensions�
X509Extension�signr-rU�dump_privatekeyr��strip�open�O_CREAT�O_RDWRr6r.�dump_certificaterW)"r8r^r_r`rarbrcrdrerfrgrrv�digestr�r��replacerVrwrxrrz�errZbck�caZ
keycontentZ	write_keyryZold_key�fpZbckf�ca_keyZca_crtr�rrr
ru�s�
O
�������











��������
���	����
��ruc
Cs�ts	Jd�t���i}|dkrt�d�d}ztddd�|d<Wnty8}zt�|�WYd	}~nd	}~ww|drC|ddkrOd
didd
d�d�|d<ztddd�|d<Wntyq}zt�|�WYd	}~nd	}~ww|dr||ddkr�ddd�id�|d<ztddd�|d<Wnty�}zt�|�WYd	}~nd	}~ww|dr�|ddkr�ddd�id�|d<||vr�z
tdd|���||<Wnty�}z
t�d||�WYd	}~nd	}~ww|d}|D]
}||�|||�q�|S)aO
    Fetch X509 and CSR extension definitions from tls:extensions:
    (common|server|client) or set them to standard defaults.

    .. versionadded:: 2015.8.0

    cert_type:
        The type of certificate such as ``server`` or ``client``.

    CLI Example:

    .. code-block:: bash

        salt '*' tls.get_extensions client

    zXX509 extensions are not supported in pyOpenSSL prior to version 0.15.1. Your version: {}�zKcert_type set to empty in tls_ca.get_extensions(); defaulting to ``server``�serverz
pillar.getztls.extensions:commonF�commonNZbasicConstraintszCA:FALSEzkeyid,issuer:always�hash)ZauthorityKeyIdentifierZsubjectKeyIdentifier)�csrrMztls.extensions:serverZ
serverAuthz!digitalSignature, keyEncipherment)ZextendedKeyUsageZkeyUsageztls.extensions:client�clientZ
clientAuthz1nonRepudiation, digitalSignature, keyEnciphermentztls.extensions:zMpillar, tls:extensions:%s not available or not operating in a salt context
%s)	r	rIrr
r�r�	NameErrorr�update)�	cert_type�extr�r��retvalZUserrr
�get_extensionsXsz�����
����
����
�	���r�r�c Cs$t|
�|s|�d�}t||d�sd�|�S|s!t��d|�d�}tj�|�s,t�|�|r3d|��nd}|
s=|�|��}
|�d|
�d�}|sStj�|�rSd	|�d
�Stj	�
�}|�tj	j|�tj	�
�}||��_||��_||��_||��_|r�||��_||��_|r�||��_z/t|�d}g}|��D] \}}t|t�r�tjj�|�}|�tj	�tjj�|�d|��q�Wnt y�}z
t!�"|�g}WYd
}~nd
}~ww|	r�t#r�t|	t�r�|	g}	|�tj	�ddd�$tjj%�&|	����nt'd�t(���t#�r|�)|�|�*|�|�+|tjj�,|��|�d|
�d�}t�-|tj.tj/Bd�}tjj0�1|d��}|�2tjj�tj	�3tj	j4|���Wd
�n	1�sLwYtjj0�1|d��}|�2tjj�tj	�5tj	j4|���Wd
�n	1�svwYd|�|
�d�}|d|�d|�|
�d�7}|S)aI
    Create a Certificate Signing Request (CSR) for a
    particular Certificate Authority (CA)

    ca_name
        name of the CA
    bits
        number of RSA key bits, default is 2048
    CN
        common name in the request, default is "localhost"
    C
        country, default is "US"
    ST
        state, default is "Utah"
    L
        locality, default is "Centerville", the city where SaltStack originated
    O
        organization, default is "SaltStack"
        NOTE: Must the same as CA certificate or an error will be raised
    OU
        organizational unit, default is None
    emailAddress
        email address for the request, default is None
    subjectAltName
        valid subjectAltNames in full form, e.g. to add DNS entry you would call
        this function with this value:

        examples: ['DNS:somednsname.com',
                'DNS:1.2.3.4',
                'IP:1.2.3.4',
                'IP:2001:4801:7821:77:be76:4eff:fe11:e51',
                'email:me@i.like.pie.com']

    .. note::
        some libraries do not properly query IP: prefixes, instead looking
        for the given req. source with a DNS: prefix. To be thorough, you
        may want to include both DNS: and IP: entries if you are using
        subjectAltNames for destinations for your TLS connections.
        e.g.:
        requests to https://1.2.3.4 will fail from python's
        requests library w/out the second entry in the above list

    .. versionadded:: 2015.8.0

    cert_type
        Specify the general certificate type. Can be either `server` or
        `client`. Indicates the set of common extensions added to the CSR.

        .. code-block:: cfg

            server: {
               'basicConstraints': 'CA:FALSE',
               'extendedKeyUsage': 'serverAuth',
               'keyUsage': 'digitalSignature, keyEncipherment'
            }

            client: {
               'basicConstraints': 'CA:FALSE',
               'extendedKeyUsage': 'clientAuth',
               'keyUsage': 'nonRepudiation, digitalSignature, keyEncipherment'
            }

    type_ext
        boolean.  Whether or not to extend the filename with CN_[cert_type]
        This can be useful if a server and client certificate are needed for
        the same CN. Defaults to False to avoid introducing an unexpected file
        naming pattern

        The files normally named some_subject_CN.csr and some_subject_CN.key
        will then be saved

    replace
        Replace this signing request even if it exists

        .. versionadded:: 2015.5.1

    Writes out a Certificate Signing Request (CSR) If the file already
    exists, the function just returns assuming the CSR already exists.

    If the following values were set::

        ca.cert_base_path='/etc/pki'
        ca_name='koji'
        CN='test.egavas.org'

    the resulting CSR, and corresponding key, would be written in the
    following location with appropriate permissions::

        /etc/pki/koji/certs/test.egavas.org.csr
        /etc/pki/koji/certs/test.egavas.org.key

    CLI Example:

    .. code-block:: bash

        salt '*' tls.create_csr test
    rXr�zECertificate for CA named "{}" does not exist, please create it first.r%r��_r��.csrzCertificate Request "r�r�FNssubjectAltNames, zysubjectAltName cannot be set as X509 extensions are not supported in pyOpenSSL prior to version 0.15.1. Your version: {}.rZr��wb+zCreated Private Key: "z.key" zCreated CSR for "z": "z.csr")6r r}rIrr/r1r2r3rhrir�r�r�ZX509ReqrKrarbrcrdrer`rfr��itemsr�r7r+r,r-r.�appendr��AssertionErrorr
r�r	r*�data�encodersrr�r�r�rUr�r�r�r4r5r6r�rkZdump_certificate_request) r8r^r`rarbrcrdrerf�subjectAltNamerrv�csr_path�csr_filenamer��type_extr�r��CN_extZcsr_fr�req�
extensionsZextension_addsr��valuer�Z	priv_keypr��priv_keyr�r�rrr
�
create_csr�s�u
�










���
��
���

�������	r��tlsc	Csdt|
�tj�t��d|�d��st�t��d|�d��|s!|}|
s9tj�t��d|�d|�d��r9d|�d�Stj��}|�	tjj
|�tj��}|�d�|�
d�|�t|�dd	d	�||��_||��_||��_||��_|r}||��_||��_|	r�|	|��_|�t|��|�|���|�|�|�|tjj� |��d
�!t�||�}t�"|tj#tj$Bd�}tjj%�&|d��}|�'tjj�(tj�)tjj*|���Wd
�n1s�wYt��d|�d|�d�}tjj%�&|d��}|�'tjj�(tj�+tjj*|���Wd
�n	1�swYt,||�d�!t�||�}|d�!t�||�7}|S)a�
    Create a Self-Signed Certificate (CERT)

    tls_dir
        location appended to the ca.cert_base_path, default is 'tls'
    bits
        number of RSA key bits, default is 2048
    CN
        common name in the request, default is "localhost"
    C
        country, default is "US"
    ST
        state, default is "Utah"
    L
        locality, default is "Centerville", the city where SaltStack originated
    O
        organization, default is "SaltStack"
        NOTE: Must the same as CA certificate or an error will be raised
    OU
        organizational unit, default is None
    emailAddress
        email address for the request, default is None
    cacert_path
        absolute path to ca certificates root directory
    digest
        The message digest algorithm. Must be a string describing a digest
        algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically).
        For example, "md5" or "sha1". Default: 'sha256'
    replace
        Replace this certificate even if it exists

        .. versionadded:: 2015.5.1

    Writes out a Self-Signed Certificate (CERT). If the file already
    exists, the function just returns.

    If the following values were set::

        ca.cert_base_path='/etc/pki'
        tls_dir='koji'
        CN='test.egavas.org'

    the resulting CERT, and corresponding key, would be written in the
    following location with appropriate permissions::

        /etc/pki/koji/certs/test.egavas.org.crt
        /etc/pki/koji/certs/test.egavas.org.key

    CLI Example:

    .. code-block:: bash

        salt '*' tls.create_self_signed_cert

    Passing options from the command line:

    .. code-block:: bash

        salt 'minion' tls.create_self_signed_cert CN='test.mysite.org'
    r%r�rY�
Certificate "r�r�rr�r�z{}/{}/certs/{}.keyr�r�Nz*Created Private Key: "{}/{}/certs/{}.key" z)Created Certificate: "{}/{}/certs/{}.crt")-r r/r1r2rr3rhrir�r�r�r�r�r�r�rrKrarbrcrdrer`rfr�r;r�r�r�r+r,r-rUrIr�r�r�r4r5r6r.r�rkr�rW)Ztls_dirr^r_r`rarbrcrdrerfrr�r�r�rrMZ
priv_key_pathr�r�Zcrt_path�crtr�rrr
�create_self_signed_cert�snL
�











�������
��r�cCs�i}t|�|s
|�d�}|st��d|�d�}|	r+|s#t�d�|S|r*d|��}nd}|�|��}
|s;|�|��}|
s[tj�tj�tjj�d�	t�||��
d����r[d|�d	�Szat|||d
�tj
j�t��d|�d|�d���}tj�tjj|���}Wd�n1s�wYtj
j�t��d|�d|�d
���}tj�tjj|���}Wd�n1s�wYWnty�d|d<d|�d�|d<|YSwz,|�d|
�d�}tj
j�|��}tj�tjj|���}Wd�n1s�wYWnt�yd|d<d�	|�|d<|YSwg}z	|�|���WnOt�yrz4t�dt�tjj�|j �}t!tjj�"|��D]}tjj#�$tjj#�}tjj�%||�|_&|�'|��qCWnt(�yot�dt�YnwYnwtj�)�}|�*d�|�+|�,��|�-d�|�.t/|�ddd�|�0t1|��|�2|�,��|�3|�4��|�5|�|�6|tj
j7�8|��|�d|�d�}tj
j�|d��}|�9tj
j7�:tj�;tjj|���Wd�n	1�s�wYt<||�d�	|||�S)a

    Create a Certificate (CERT) signed by a named Certificate Authority (CA)

    If the certificate file already exists, the function just returns assuming
    the CERT already exists.

    The CN *must* match an existing CSR generated by create_csr. If it
    does not, this method does nothing.

    ca_name
        name of the CA
    CN
        common name matching the certificate signing request
    days
        number of days certificate is valid, default is 365 (1 year)

    cacert_path
        absolute path to ca certificates root directory

    ca_filename
        alternative filename for the CA

        .. versionadded:: 2015.5.3


    cert_path
        full path to the certificates directory

    cert_filename
        alternative filename for the certificate, useful when using special
        characters in the CN. If this option is set it will override
        the certificate filename output effects of ``cert_type``.
        ``type_ext`` will be completely overridden.

        .. versionadded:: 2015.5.3


    digest
        The message digest algorithm. Must be a string describing a digest
        algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically).
        For example, "md5" or "sha1". Default: 'sha256'
    replace
        Replace this certificate even if it exists

        .. versionadded:: 2015.5.1

    cert_type
        string. Either 'server' or 'client' (see create_csr() for details).

        If create_csr(type_ext=True) this function **must** be called with the
        same cert_type so it can find the CSR file.

    .. note::
        create_csr() defaults to cert_type='server'; therefore, if it was also
        called with type_ext, cert_type becomes a required argument for
        create_ca_signed_cert()

    type_ext
        bool. If set True, use ``cert_type`` as an extension to the CN when
        formatting the filename.

        e.g.: some_subject_CN_server.crt or some_subject_CN_client.crt

        This facilitates the context where both types are required for the same
        subject

        If ``cert_filename`` is `not None`, setting ``type_ext`` has no
        effect

    If the following values were set:

    .. code-block:: text

        ca.cert_base_path='/etc/pki'
        ca_name='koji'
        CN='test.egavas.org'

    the resulting signed certificate would be written in the following
    location:

    .. code-block:: text

        /etc/pki/koji/certs/test.egavas.org.crt

    CLI Example:

    .. code-block:: bash

        salt '*' tls.create_ca_signed_cert test localhost
    rXr%�/certsz@type_ext = True but cert_type is unset. Certificate not written.r�r�z{}/{}/certs/{}.crtr�r�r|rYNrZ�r��There is no CA named "�"r�r�z(There is no CSR that matches the CN "{}"zzreq.get_extensions() not supported in pyOpenSSL versions prior to 0.15. Processing extensions internally. Your version: %sz|X509 extensions are unsupported in pyOpenSSL versions prior to 0.14. Upgrade required to use extensions. Current version: %sr�rr�r�r�z)Created Certificate for "{}": "{}/{}.crt")=r rr
r�r/r1r2r*�seprI�splitr{r+r,r4r5rhrirjrkrlrn�OSErrorZload_certificate_request�extendr��AttributeErrorrmrZ_util�libZX509_REQ_get_extensionsZ_req�rangeZsk_X509_EXTENSION_numr��__new__Zsk_X509_EXTENSION_valueZ
_extensionr�ror�r�Zset_subjectrKr�r�rr�r;r�r�Z
get_pubkeyr�r�r-rUr6r.r�rW)r8r`r_rrv�	cert_pathr�r�r�r�r�r�r�r�r�r�r�r�r�ZextsZnative_exts_obj�ir�rMZcert_full_pathr�rrr
�create_ca_signed_cert*s�g
�
�
����	��������������������



���
�r�r�cCst|�|stj�t��d|�d|�d��rd|�d�Sz)tjj�d�	t�|���}t
j�t
jj
|���}Wd�n1s?wYWntyTd|�d	�YSwzZtjj�t��d|�d|�d
���}t
j�t
jj
|���}Wd�n1s}wYtjj�t��d|�d|�d���}t
j�t
jj
|���}Wd�n1s�wYWnty�d|�d	�YSwt
j��}	|	�|�|	�|g�|	�|�tjj�t��d|�d|�d�d
��}
|
�|	jtjj�|�d��Wd�n1s�wYd�	|t�|�S)a'
    Create a PKCS#12 browser certificate for a particular Certificate (CN)

    ca_name
        name of the CA
    CN
        common name matching the certificate signing request
    passphrase
        used to unlock the PKCS#12 certificate when loaded into the browser
    cacert_path
        absolute path to ca certificates root directory
    replace
        Replace this certificate even if it exists

        .. versionadded:: 2015.5.1

    If the following values were set::

        ca.cert_base_path='/etc/pki'
        ca_name='koji'
        CN='test.egavas.org'

    the resulting signed certificate would be written in the
    following location::

        /etc/pki/koji/certs/test.egavas.org.p12

    CLI Example:

    .. code-block:: bash

        salt '*' tls.create_pkcs12 test localhost
    r%r�z.p12r�r�rNr�r�rYrZz-There is no certificate that matches the CN "r���
passphrasez>Created PKCS#12 Certificate for "{0}": "{1}/{2}/certs/{0}.p12")r r/r1r2rr+r,r4r5rIrhrirjrkrlr�rnZPKCS12Zset_certificateZset_ca_certificatesZset_privatekeyr6�exportr-r.)r8r`rrr�r�r�rMrZpkcs12r:rrr
�
create_pkcs12sl"$�������������


����rcCs�d}d|vr!tjj�|��}|��}Wd�n1swYtj�tjj|�}i}|�	��
�D] \}}t|t�rBtjj
�|�}t|t�rNtjj
�|�}|||<q2i}|���
�D] \}}t|t�rktjj
�|�}t|t�rwtjj
�|�}|||<q[tjj
�|�tjj
�|���|||��t�t�t|���t��|��t�t�|���t�|��d�}t|d�r�i|d<t|���D]%}	z|�|	�}
tjj
�|
� ��}t|
��!�|d|<Wq�t"y�Yq�wd|�#di�v�r%d}t$�}t|dd��%d	�D]"}
|
�%d
d�\}}
||v�rt&�'d|d
|
d�(|��q�|�)|
�q�t*|�|d<t|d��rOz|�+�}t|t��r=tjj
�|�}||d<W|St"�yNY|Sw|S)a:
    Return information for a particular certificate

    cert
        path to the certifiate PEM file or string

        .. versionchanged:: 2018.3.4

    digest
        what digest to use for fingerprinting

    CLI Example:

    .. code-block:: bash

        salt '*' tls.cert_info /dir/for/certs/cert.pem

    rz
-----BEGINN)ZfingerprintrRr�rQZ
not_beforeZ	not_after�get_extension_countr�r�)�DNSz
IP Addressz, �:r�z6Cert %s has an entry (%s) which does not start with %srRr%Zsubject_alt_names�get_signature_algorithmZsignature_algorithm),r+r,r4r5rlrhrirjrkZ
get_issuerrLr��bytesr-r�rKr�rUrJ�calendar�timegmrrpr7Z
get_notBefore�decodeZ__salt_system_encoding__rqr�r�rZ
get_extensionZget_short_namer�r�r�setr�r
r�r*�add�listr)rMr�Zdate_fmt�	cert_filer�rr�rRr�r�r�Z
valid_entriesZvalid_names�name�entryrrr
�	cert_infofs�
�





������

�
�
��rcCs�t|�|s|�d�}|st��d|�d�}tj�|��r#d|�d�SzZtjj�t	��d|�d|�d���}t
j�t
jj
|���}Wd�n1sKwYtjj�t	��d|�d|�d���}t
j�t
jj
|���}Wd�n1swwYWnty�d	|�d
�YSwt
j��}|j||tjj�|�d�}	tjj�|d��}
|
�tjj�|	��Wd�n1s�wYd
|�d
�S)a�
    Create an empty Certificate Revocation List.

    .. versionadded:: 2015.8.0

    ca_name
        name of the CA
    cacert_path
        absolute path to ca certificates root directory
    ca_filename
        alternative filename for the CA

        .. versionadded:: 2015.5.3

    crl_file
        full path to the CRL file

    digest
        The message digest algorithm. Must be a string describing a digest
        algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically).
        For example, "md5" or "sha1". Default: 'sha256'

    CLI Example:

    .. code-block:: bash

        salt '*' tls.create_empty_crl ca_name='koji'                 ca_filename='ca'                 crl_file='/etc/openvpn/team1/crl.pem'
    rXr%�/crl.pemzCRL "r�rYNrZr�r��r�r&zCreated an empty CRL: ")r rr/r1r2r+r,r4r5rrhrirjrkrlrnr�r�rr-r.r6rU)r8rrvr�r��fp_r�r�r��crl_textrrrr
�create_empty_crl�sL"
��������
��rc
Cs t|�t��d|��}|dur|�d�}|dur"t��d|�d�}|dur)|�}zZtjj�t��d|�d|�d���}	tj�	tjj
|	���}
Wd�n1sQwYtjj�t��d|�d|�d���}	tj�tjj
|	���}Wd�n1s}wYWnt
y�d|�d�YSwt|�d|�d��}|dur�d	|�d�St|||�\}
}}}|�d
|��}d|�d|��}t�d
|dt�|��}d�|tt���|�}i}tjj�|
��k}	|	D]`}tjj�|�}|�|��r4|�d�d}zt�|t�d�|||�WWd�St�y3d|d<d�|t�|d<|YWd�Sw||v�rEtd|
||dd�nq�Wd�n	1�sQwYtj��}tjj�|
��K}	|	D]@}tjj�|�}|� d��r�|�d�}tj�!�}|�"tjj�#|d��t�|dt�}|�$tjj�#|�%t&���|�'|��qeWd�n	1�s�wY|j(|
|tjj�#|�d�}|du�r�t��d|�d�}t)j*�+|��r�d|d<d|�d�|d<|Stjj�|d ��}	|	�,tjj�-|��Wd�n	1�swYd!�|||�S)"a�
    Revoke a certificate.

    .. versionadded:: 2015.8.0

    ca_name
        Name of the CA.

    CN
        Common name matching the certificate signing request.

    cacert_path
        Absolute path to ca certificates root directory.

    ca_filename
        Alternative filename for the CA.

    cert_path
        Path to the cert file.

    cert_filename
        Alternative filename for the certificate, useful when using special
        characters in the CN.

    crl_file
        Full path to the CRL file.

    digest
        The message digest algorithm. Must be a string describing a digest
        algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically).
        For example, "md5" or "sha1". Default: 'sha256'

    CLI Example:

    .. code-block:: bash

        salt '*' tls.revoke_cert ca_name='koji'                 ca_filename='ca'                 crl_file='/etc/openvpn/team1/crl.pem'

    r%NrXr�rYrZr�r�z&There is no client certificate named "z		unknown	zV	z		zR\tz\t\d{12}Z\tz
R	{}	{}	{}�	r�z2"{}/{}.crt" was already revoked, serial number: {}r�r�z.Revocation date '{}' does not matchformat '{}'r�zfile.replaceF)Zbackup�Rr[rrz
crl_file "z" is an existing directoryr&z3Revoked Certificate: "{}/{}.crt", serial number: {}).r rrr+r,r4r5rhrirjrkrlrnr�rGrS�re�compile�escaperIr?rrrr-r��matchr�rpr>rsrr��
startswithZRevokedZ
set_serialr.Zset_rev_dater=r�Zadd_revokedrr/r1�isdirr6rU)r8r`rrvr�r�r�r�rNrr�r�Zclient_certrOrPrQrRZindex_serial_subjectZindex_v_dataZindex_r_data_patternZindex_r_datar��lineZrevoke_dater��fieldsZrevokedZrevoke_date_2_digitrrrr
�revoke_certs�4
����������
���
��
�

����


��
����
��r"�__main__ZkojiZtest_systemZCentervilleztest_system@saltproject.io)r`rarbrcrdrerf�testrr<)NrT)NN)FN)r�FNN)r�)r\r]r�r�r�r�r�NNFNNr�NNF)r\r�r�r�r�r�NNNNNNNr�Fr�F)r�r\r]r�r�r�r�r�NNNNr�F)	r]NNNNr�NFF)r�NF)r�)NNNr�)NNNNNr�);�__doc__r(r	�loggingrr/rrrZsalt.utils.datar+Zsalt.utils.filesZsalt.utils.stringutilsZsalt.exceptionsrZsalt.utils.versionsrrr	rh�__dict__rr�ImportError�	getLogger�__name__r
r>r�rrrrrr r;r?rSrWr{r}r~r�r�r�rGr�rHr�r�rur�r�r�r�rrrr"rrrr
�<module>sd�



'



>


�(
�,.

�P`
�d
�
�
i
Tg
�M
�
"�

�