
    Vh:                        d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlmZmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZ dZdZ	 d dlZd dlZd dlZd dlZd dl Z eejB                        Z"dZ# G d de&      Z' G d de(      Z) G d de)      Z* G d de)      Z+ G d de)      Z,d Z-e.dk(  r e-        yy# e$$ r  ejJ                         ZdZ#Y bw xY w)    )absolute_importdivisionprint_functiona7  
module: openssl_dhparam
short_description: Generate OpenSSL Diffie-Hellman Parameters
description:
  - This module allows one to (re)generate OpenSSL DH-params.
  - This module uses file common arguments to specify generated file permissions.
  - Please note that the module regenerates existing DH params if they do not match the module's options. If you are concerned
    that this could overwrite your existing DH params, consider using the O(backup) option.
  - The module can use the cryptography Python library, or the C(openssl) executable. By default, it tries to detect which
    one is available. This can be overridden with the O(select_crypto_backend) option.
requirements:
  - Either cryptography >= 2.0
  - Or OpenSSL binary C(openssl)
author:
  - Thom Wiggers (@thomwiggers)
extends_documentation_fragment:
  - ansible.builtin.files
  - community.crypto.attributes
  - community.crypto.attributes.files
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
  safe_file_operations:
    support: full
  idempotent:
    support: partial
    details:
      - The module is not idempotent if O(force=true).
options:
  state:
    description:
      - Whether the parameters should exist or not, taking action if the state is different from what is stated.
    type: str
    default: present
    choices: [absent, present]
  size:
    description:
      - Size (in bits) of the generated DH-params.
    type: int
    default: 4096
  force:
    description:
      - Should the parameters be regenerated even it it already exists.
    type: bool
    default: false
  path:
    description:
      - Name of the file in which the generated parameters will be saved.
    type: path
    required: true
  backup:
    description:
      - Create a backup file including a timestamp so you can get the original DH params back if you overwrote them with new
        ones by accident.
    type: bool
    default: false
  select_crypto_backend:
    description:
      - Determines which crypto backend to use.
      - The default choice is V(auto), which tries to use C(cryptography) if available, and falls back to C(openssl).
      - If set to V(openssl), will try to use the OpenSSL C(openssl) executable.
      - If set to V(cryptography), will try to use the L(cryptography,https://cryptography.io/) library.
    type: str
    default: auto
    choices: [auto, cryptography, openssl]
    version_added: "1.0.0"
  return_content:
    description:
      - If set to V(true), will return the (current or generated) DH parameter's content as RV(dhparams).
    type: bool
    default: false
    version_added: "1.0.0"
seealso:
  - module: community.crypto.x509_certificate
  - module: community.crypto.openssl_csr
  - module: community.crypto.openssl_pkcs12
  - module: community.crypto.openssl_privatekey
  - module: community.crypto.openssl_publickey
a  
---
- name: Generate Diffie-Hellman parameters with the default size (4096 bits)
  community.crypto.openssl_dhparam:
    path: /etc/ssl/dhparams.pem

- name: Generate DH Parameters with a different size (2048 bits)
  community.crypto.openssl_dhparam:
    path: /etc/ssl/dhparams.pem
    size: 2048

- name: Force regenerate an DH parameters if they already exist
  community.crypto.openssl_dhparam:
    path: /etc/ssl/dhparams.pem
    force: true
aq  
size:
  description: Size (in bits) of the Diffie-Hellman parameters.
  returned: changed or success
  type: int
  sample: 4096
filename:
  description: Path to the generated Diffie-Hellman parameters.
  returned: changed or success
  type: str
  sample: /etc/ssl/dhparams.pem
backup_file:
  description: Name of backup file created.
  returned: changed and if O(backup) is V(true)
  type: str
  sample: /path/to/dhparams.pem.2019-03-09@11:22~
dhparams:
  description: The (current or generated) DH params' content.
  returned: if O(state) is V(present) and O(return_content) is V(true)
  type: str
  version_added: "1.0.0"
N)AnsibleModulemissing_required_lib)	to_native)
count_bits)load_file_if_exists
write_file)LooseVersionz2.0TFc                       e Zd Zy)DHParameterErrorN)__name__
__module____qualname__     t/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/crypto/plugins/modules/openssl_dhparam.pyr   r      s    r   r   c                   x    e Zd Zd Zej
                  d        Zd Zd Zd Z	ej
                  d        Z
d Zd Zy	)
DHParameterBasec                    |j                   d   | _        |j                   d   | _        |j                   d   | _        |j                   d   | _        d| _        |j                   d   | _        |j                   d   | _        d | _        y )NstatepathsizeforceFreturn_contentbackup)	paramsr   r   r   r   changedr   r   backup_fileselfmodules     r   __init__zDHParameterBase.__init__   ss    ]]7+
MM&)	MM&)	]]7+
$mm,<=mmH-r   c                      y Actually generate the DH params.Nr   r!   s     r   _do_generatezDHParameterBase._do_generate        	r   c                     d}| j                   s| j                  |      s| j                  |       d}| j                  |      sd}|| _        y)zGenerate DH params.FTN)r   _check_params_validr(   _check_fs_attributesr   )r"   r#   r   s      r   generatezDHParameterBase.generate   sN     ::T55f=f%G ((0 Gr   c                    | j                   r |j                  | j                        | _        	 t	        j
                  | j                         d| _        y # t        $ r%}|j                  t        |             Y d }~y d }~ww xY w)NTmsg)
r   backup_localr   r    osremover   OSError	fail_jsonr   )r"   r#   excs      r   r3   zDHParameterBase.remove   sd    ;;%22499=D	1IIdii DL 	1300	1s   &A 	BA>>Bc                 d    | j                   ry| j                  |      xr | j                  |      S )z,Ensure the resource is in its desired state.F)r   r+   r,   r!   s     r   checkzDHParameterBase.check   s-    ::''/UD4M4Mf4UUr   c                      y,Check if the params are in the correct stateNr   r!   s     r   r+   z#DHParameterBase._check_params_valid   r)   r   c                     |j                  |j                        }|j                  |d         ry|j                  |d       S )z8Checks (and changes if not in check mode!) fs attributesr   F)load_file_common_argumentsr   check_file_absent_if_check_modeset_fs_attributes_if_different)r"   r#   	file_argss      r   r,   z$DHParameterBase._check_fs_attributes   sB    55fmmD	11)F2CD88EJJJr   c                     | j                   | j                  | j                  d}| j                  r| j                  |d<   | j                  r/t        | j                  d      }|r|j                  d      nd|d<   |S )z'Serialize the object into a dictionary.)r   filenamer   r    T)ignore_errorszutf-8Ndhparams)r   r   r   r    r   r
   decode)r"   resultcontents      r   dumpzDHParameterBase.dump   sp     II		||

 $($4$4F=!)$))4HG<C!8F:r   N)r   r   r   r$   abcabstractmethodr(   r-   r3   r8   r+   r,   rH   r   r   r   r   r      sV    	  	 "1V 	 Kr   r   c                   *     e Zd Z fdZd Zd Z xZS )DHParameterAbsentc                 ,    t         t        |   |       y N)superrL   r$   r"   r#   	__class__s     r   r$   zDHParameterAbsent.__init__  s    /7r   c                      yr&   r   r!   s     r   r(   zDHParameterAbsent._do_generate      r   c                      yr:   r   r!   s     r   r+   z%DHParameterAbsent._check_params_valid
  rS   r   r   r   r   r$   r(   r+   __classcell__rQ   s   @r   rL   rL     s    8r   rL   c                   *     e Zd Z fdZd Zd Z xZS )DHParameterOpenSSLc                 Z    t         t        |   |       |j                  dd      | _        y )NopensslT)rO   rY   r$   get_bin_pathopenssl_binrP   s     r   r$   zDHParameterOpenSSL.__init__  s(     $08!..y$?r   c           	         t        j                         \  }}t        j                  |       |j	                  |       | j
                  dd|t        | j                        g}|j                  |d      \  }}}|dk7  rt        t        |            | j                  r |j                  | j                        | _        	 |j                  t        j                  j!                  |      t        j                  j!                  | j                               y	# t"        $ r5}|j%                  d| j                  dt        |             Y d	}~y	d	}~ww xY w)
r'   dhparamz-outFcheck_rcr   zFailed to write to file z: r/   N)tempfilemkstempr2   closeadd_cleanup_filer]   strr   run_commandr   r   r   r1   r   r    atomic_moveabspath	Exceptionr5   )	r"   r#   fdtmpsrccommandrcdummyerres	            r   r(   zDHParameterOpenSSL._do_generate  s    %%'
F
'##YDIIO++Ge+DE37"9S>22;;%22499=D	Yrwwv6		8RS 	YTYYPSTUPV!WXX	Ys   ?AD 	E+EEc                 4   | j                   ddddd| j                  g}|j                  |d      \  }}}t        |      }|dk7  ryt	        j
                  d	|      }|syt        |j                  d
            }d|v sdt        |      v ry|| j                  k(  S )r;   r_   z-checkz-textz-nooutz-inFr`   r   zParameters:\s+\((\d+) bit\).*   WARNING)	r]   r   rg   r   researchintgroupr   )	r"   r#   rm   rn   outrp   rF   matchbitss	            r   r+   z&DHParameterOpenSSL._check_params_valid'  s     II
 ))'E)BC37 		:FC5;;q>" )y~"=tyy  r   rU   rW   s   @r   rY   rY     s    @Y$!r   rY   c                   *     e Zd Z fdZd Zd Z xZS )DHParameterCryptographyc                     t         t        |   |       t        j                  j
                  j                         | _        y rN   )rO   r}   r$   cryptographyhazmatbackendsdefault_backendcrypto_backendrP   s     r   r$   z DHParameterCryptography.__init__H  s0    %t5f=*11::JJLr   c                    t         j                  j                  j                  j                  j                  d| j                  | j                        }|j                  t         j                  j                  j                  j                  j                  t         j                  j                  j                  j                  j                        }| j                  r |j                  | j                         | _        t%        ||       y)r'      )	generatorkey_sizebackend)encodingformatN)r   r   
primitives
asymmetricdhgenerate_parametersr   r   parameter_bytesserializationEncodingPEMParameterFormatPKCS3r   r1   r   r    r   )r"   r#   r   rF   s       r   r(   z$DHParameterCryptography._do_generateL  s     $$//::==QQYY'' R 
 ''!((33AAJJNN&&11??OOUU ( 

 ;;%22499=D66"r   c                 z   	 t        | j                  d      5 }|j                         }ddd       t        j                  j
                  j                  j                  | j                        }t        |j                         j                        }|| j                  k(  S # 1 sw Y   zxY w# t        $ r Y yw xY w)r;   rbN)r   F)openr   readr   r   r   r   load_pem_parametersr   rj   r	   parameter_numberspr   )r"   r#   fdatar   r{   s         r   r+   z+DHParameterCryptography._check_params_valid^  s    	dii&  !vvx !((33AAUUd11 V F &224667tyy     
  		s(   B. B"AB. "B+'B. .	B:9B:rU   rW   s   @r   r}   r}   F  s    M#$!r   r}   c                     t        t        t        ddddg      t        dd      t        dd	      t        d
d      t        dd	      t        ddg d      t        dd	            dd      } t        j                  j	                  | j
                  d
         xs d}t        j                  j                  |      s| j                  |d|z         | j
                  d   dk(  rF| j
                  d   }|dk(  ret        xr t        t        t              k\  }| j                  dd	      du}|rd}n|rd}|dk(  r%| j                  dj                  t                     |dk(  rt        |       }nU|dk(  rEt        s3| j                  t        dj                  t                    t                t#        |       }nt%        d      | j&                  rH|j)                         }| j
                  d   xs |j+                  |        |d<    | j,                  d i | 	 |j/                  |        nt5        |       }| j&                  rQ|j)                         }t        j                  j7                  | j
                  d
         |d<    | j,                  d i | t        j                  j7                  | j
                  d
         r	 |j9                  |        |j)                         } | j,                  d i | y# t0        $ r%}| j                  t3        |             Y d}~Ld}~ww xY w# t:        $ r%}| j                  t3        |             Y d}~}d}~ww xY w)!zMain functionrf   presentabsent)typedefaultchoicesrw   i   )r   r   boolFr   T)r   requiredauto)r   r   r[   )r   r   r   r   r   select_crypto_backendr   )argument_specsupports_check_modeadd_file_common_args.z@The directory '%s' does not exist or the file is not a directory)namer0   r   r   r[   Nr   zdCannot detect either the required Python library cryptography (>= {0}) or the OpenSSL binary opensslr/   zcryptography >= {0})r0   	exceptionzInternal error: unknown backendr   r   r   )r   dictr2   r   dirnamer   isdirr5   CRYPTOGRAPHY_FOUNDCRYPTOGRAPHY_VERSIONr   MINIMAL_CRYPTOGRAPHY_VERSIONr\   r   rY   r   CRYPTOGRAPHY_IMP_ERRr}   AssertionError
check_moderH   r8   	exit_jsonr-   r   r   rL   existsr3   rj   )r#   base_dirr   can_use_cryptographycan_use_opensslr_   rF   r6   s           r   mainr   n  s    E9x>ST5$/FE26D1VU3"&F4W#  VU;

 !!F  wwv}}V45<H77=="R 	 	
 }}W*-- 78f # W(L9U,VV ! %11)UC4OO $( # &   8f9:	 !  i(0G&%  ,-445QR 3	 !  .f5G !BCC\\^F &g 6 SgmmF>S:SF9F&v&	1V$ $F+\\^F "v}}V/D EF9F&v&77>>&--/05v& \\^FFv%   	1300	1  5  Ys^ 445s0   K9 L* 9	L'L""L'*	M3MM__main__)/
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNrI   r2   ru   rb   	tracebackansible.module_utils.basicr   r   +ansible.module_utils.common.text.convertersr   Eansible_collections.community.crypto.plugins.module_utils.crypto.mathr	   <ansible_collections.community.crypto.plugins.module_utils.ior
   r   Aansible_collections.community.crypto.plugins.module_utils.versionr   r   r   r   cryptography.exceptionscryptography.hazmat.backends,cryptography.hazmat.primitives.asymmetric.dh,cryptography.hazmat.primitives.serialization__version__r   r   ImportError
format_excrj   r   objectr   rL   rY   r}   r   r   r   r   r   <module>r      s   A @ Pd"
.  	 	   J A
  %  "'77'(@(@A
 	y 	Lf L^ 4! 4!n%!o %!P[| zF K	  /9//1s   &B> >CC