
    VhR                        d dl mZmZmZ eZddgdd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 d dlmZ d dlmZ d dlmZmZ d dlmZmZ d d	lZd d	lmc mc mc mc m Z! d dl"m#Z# d dl$m%Z% d dl&m'Z' d dl(m)Z) d dl*m+Z+ 	 d dl,m-Z- d dl.m/Z/ d	Z0 e+       Z3d	a4d Z5d Z6d Z7d Z8d Z9d Z:d Z;d Z<d Z= e=dd !      d(d"       Z>d# Z?d$ Z@d% ZA G d& d'e%      ZBy	# e1$ r  ejd                         Z0Y bw xY w))    )absolute_importdivisionprint_functionz1.1preview	community)metadata_versionstatussupported_bya  
    name: conjur_variable
    version_added: "1.0.2"
    short_description: Fetch credentials from CyberArk Conjur.
    author:
      - CyberArk BizDev (@cyberark-bizdev)
    description:
      Retrieves credentials from Conjur using the controlling host's Conjur identity,
      environment variables, or extra-vars.
      Environment variables could be CONJUR_ACCOUNT, CONJUR_APPLIANCE_URL, CONJUR_CERT_FILE, CONJUR_CERT_CONTENT,
      CONJUR_AUTHN_LOGIN, CONJUR_AUTHN_API_KEY, CONJUR_AUTHN_TOKEN_FILE
      Extra-vars could be conjur_account, conjur_appliance_url, conjur_cert_file, conjur_cert_content,
      conjur_authn_login, conjur_authn_api_key, conjur_authn_token_file
      Conjur info - U(https://www.conjur.org/).
    requirements:
      - 'The controlling host running Ansible has a Conjur identity.
        (More: U(https://docs.conjur.org/latest/en/Content/Get%20Started/key_concepts/machine_identity.html))'
    options:
      _terms:
        description: Variable path
        required: True
      validate_certs:
        description: Flag to control SSL certificate validation
        type: boolean
        default: True
      as_file:
        description: >
          Store lookup result in a temporary file and returns the file path. Thus allowing it to be consumed as an ansible file parameter
          (eg ansible_ssh_private_key_file).
        type: boolean
        default: False
      identity_file:
        description: Path to the Conjur identity file. The identity file follows the netrc file format convention.
        type: path
        default: /etc/conjur.identity
        required: False
        ini:
          - section: conjur,
            key: identity_file_path
        env:
          - name: CONJUR_IDENTITY_FILE
      config_file:
        description: Path to the Conjur configuration file. The configuration file is a YAML file.
        type: path
        default: /etc/conjur.conf
        required: False
        ini:
          - section: conjur,
            key: config_file_path
        env:
          - name: CONJUR_CONFIG_FILE
      conjur_appliance_url:
        description: Conjur appliance url
        type: string
        required: False
        ini:
          - section: conjur,
            key: appliance_url
        vars:
          - name: conjur_appliance_url
        env:
          - name: CONJUR_APPLIANCE_URL
      conjur_authn_login:
        description: Conjur authn login
        type: string
        required: False
        ini:
          - section: conjur,
            key: authn_login
        vars:
          - name: conjur_authn_login
        env:
          - name: CONJUR_AUTHN_LOGIN
      conjur_account:
        description: Conjur account
        type: string
        required: False
        ini:
          - section: conjur,
            key: account
        vars:
          - name: conjur_account
        env:
          - name: CONJUR_ACCOUNT
      conjur_authn_api_key:
        description: Conjur authn api key
        type: string
        required: False
        ini:
          - section: conjur,
            key: authn_api_key
        vars:
          - name: conjur_authn_api_key
        env:
          - name: CONJUR_AUTHN_API_KEY
      conjur_cert_file:
        description: Path to the Conjur cert file
        type: path
        required: False
        ini:
          - section: conjur,
            key: cert_file
        vars:
          - name: conjur_cert_file
        env:
          - name: CONJUR_CERT_FILE
      conjur_cert_content:
        description: Content of the Conjur cert
        type: string
        required: False
        ini:
          - section: conjur,
            key: cert_content
        vars:
          - name: conjur_cert_content
        env:
          - name: CONJUR_CERT_CONTENT
      conjur_authn_token_file:
        description: Path to the access token file
        type: path
        required: False
        ini:
          - section: conjur,
            key: authn_token_file
        vars:
          - name: conjur_authn_token_file
        env:
          - name: CONJUR_AUTHN_TOKEN_FILE
z
---
- hosts: localhost
  collections:
    - cyberark.conjur
  tasks:
    - name: Lookup variable in Conjur
      debug:
        msg: "{{ lookup('cyberark.conjur.conjur_variable', '/path/to/secret') }}"
z:
  _raw:
    description:
      - Value stored in Conjur.
N)	b64encode)netrc)sleep)S_IRUSRS_IWUSR)
gettempdirNamedTemporaryFile)AnsibleError)
LookupBasequoteopen_url)Display)load_pem_x509_certificate)default_backendc                    d| v r!| j                  dd      j                         } n$d| v r | j                  dd      j                         } t        j                  dd| t        j                        } t        j                  dd| t        j                        } t        j                  dd|       } t        j
                  d	| t        j                        st        d
      	 t        | j                         t                      | S # t        $ r}t        dt        |       d      |d }~wt        j                  $ r}t        dt        |       d      |d }~wt        $ r}t        dt        |       d      |d }~ww xY w)Nz

z^[ \t]+ )flagsz[ \t]+$z\n+z8^-----BEGIN CERTIFICATE-----.+-----END CERTIFICATE-----$zInvalid Certificate format.z&Invalid certificate content provided: z&. Please check the certificate format.z,SSL error while validating the certificate: z.. The certificate may be corrupted or invalid.z4An error occurred while validating the certificate: z5. Please verify the certificate format and try again.)replacestripresubMmatchDOTALLr   r   encoder   
ValueErrorstrsslSSLError	Exception)cert_contenterrs     r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/cyberark/conjur/plugins/lookup/conjur_variable.py_validate_pem_certificater0      ss   #++FD9??A		#++D$7==?66*b,bddCL66*b,bddCL66&$5L88OQ]_a_h_hi899!,"5"5"79JK 4SXJ ?3 3
 	 << :3s8* E; ;
 	  B3s8* MB B
 	s0    #D 	E?D&&E?<EE?!E::E?c           	      @   | r#	 t         j                  d       t        |       } | S |rqt        j                  j                  |      st        d| d      	 t        |d      5 }|j                         j                  d      }t        |      }|cd d d        S t        d
      # t        $ r,}t         j	                  dt        |       d       Y d }~d }~ww xY w# 1 sw Y   nxY w	 t        d
      # t        $ r }t        d| d	t        |             |d }~ww xY w)Nz'Validating provided certificate contentzInvalid certificate content: z%. Attempting to use certificate file.zCertificate file `z$` does not exist or cannot be found.rbutf-8z-Failed to load or validate certificate file ``: ziBoth certificate content and certificate file are invalid or missing. Please provide a valid certificate.)displayvvvr0   r   warningr)   ospathexistsopenreaddecoder,   )r-   	cert_filer.   filecert_file_contents        r/   _get_valid_certificaterA      sC   	mKKAB4\BL
 ww~~i(!3I;>bcdd	ri& )$$(IIK$6$6w$?!$=>O$P!() )   C  D  D!  	mOO;CH:Ejkll	m) ) )   C  D  D	  	r!NykY\]`ad]e\fghnqq	rsG   !B$ C4 #,C	C4 $	C-"CCC%!C4 4	D=DDc                    t        | |      } | rJ	 t        ddd      at        j                  |        t        j	                          t        j
                  }|S |S # t        $ r}t        dt        |             |d }~ww xY w)NFwr3   )deletemodeencodingz-Failed to create temporary certificate file: )	rA   r   TEMP_CERT_FILEwriteclosenamer,   r   r)   )r-   r>   r.   s      r/   _get_certificate_filerK      s    ),	BL	d/u3QXYN  .  "&++I 9  	d!NsSVxjYZ`cc	ds   AA 	B$A<<Bc                 4   t         j                  d|         t        j                  j	                  |       si S t         j                  d|         t        | d      5 }t        j                  |j                               }|cd d d        S # 1 sw Y   y xY w)Nzconf file: zLoading configuration from: r3   )rF   )
r5   r6   r8   r9   r:   vvvvr;   yaml	safe_loadr<   )	conf_pathr?   configs      r/   _load_conf_from_filerR     sx    KK+i[)*77>>)$	 LL/	{;<	i'	* d		,  s   %BBc                 H   t         j                  d|         t        j                  j	                  |       si S t         j                  d|  d|        | d}t        |       }|j                  |      t        d|       |j                  |      \  }}}|r|si S ||dS )Nzidentity file: zLoading identity from: z for z/authnzFThe netrc file on the controlling host does not contain an entry for: idapi_key)r5   rM   r8   r9   r:   r   authenticatorsr   )identity_pathappliance_urlconjur_authn_urlidentityhost_idunusedrV   s          r/   _load_identity_from_filer^     s    LL?=/2377>>-(	 LL*=/}oNO'/]#H/08cdtcuvww'667GHGVW'	g..    c                  :    i }| D ]  }|j                  |        |S N)update)argretitems      r/   _merge_dictionariesrf   -  s'    
C 

4Jr_   c                     t        | d      S )Nr   )safer   )	input_strs    r/   _encode_strrj   9  s    $$r_   c                     |  d| dt        |       d} t        j                  d|  dt        |              t        | |d||      }|j	                         }|dk7  rt        d	| d
| d      |j                         S )Nz/authn//z/authenticatez%Authentication request to Conjur at: z, with user: POST)datamethodvalidate_certsca_path   zFailed to authenticate as 'z' (got z
 response))rj   r5   rM   r   getcoder   r<   )
conjur_urlaccountusernamerV   rp   r>   responsecodes           r/   _fetch_conjur_tokenry   >  s    <wwiqX1F0G}UJLL8MR]^fRgQhij
$%'5 )	+H
 Ds{9(8D6Q[\]]==?r_   c                       fd}|S )z
    Custom retry decorator

    Args:
        retries (int, optional): Number of retries. Defaults to 5.
        retry_interval (int, optional): Time to wait between intervals. Defaults to 10.
    c                       fd}|S )Nc                  (   d}	 |dz  }	  | i |}|S # t         j                  $ r&}|k\  r|t        j                  d       Y d }~n?d }~wt        j
                  $ r&}|k\  r|t        j                  d       Y d }~nd }~ww xY wt               )Nr      zError encountered. Retrying..z&Socket timeout encountered. Retrying..)urllib_error	HTTPErrorr5   vsockettimeoutr   )argskwargsretry_countreturn_valuer.   retriesretry_intervaltargets        r/   	decoratorz4retry.<locals>.parameters_wrapper.<locals>.decoratorW  s    Kq 
H#)4#:6#:L''#-- ?"g-!	II=>>~~ H"g-!	IIFGGH n% s    	 BA		BB  B )r   r   r   r   s   ` r/   parameters_wrapperz!retry.<locals>.parameters_wrapperV  s    	&  r_   r   )r   r   r   s   `` r/   retryr   N  s    $ r_      
   )r   r   c                 "    t        | ||||      S )Nheadersro   rp   rq   r   )urlr   ro   rp   rq   s        r/   _repeat_open_urlr   k  s    C#!#1#	% %r_   c                    t        |      }dd|j                  d       di}| d| dt        |        }t        j	                  d|        t        ||d||	      }|j                         d
k(  r;t        j	                  d|  d       |j                         j                  d      }	|	gS |j                         dk(  rt        d      |j                         dk(  rt        d|        |j                         dk(  rt        d|  d      i S )NAuthorizationzToken token="r3   "z	/secrets/z
/variable/zConjur Variable URL: GETr   rr   zConjur variable z was successfully retrievedi  z4Conjur request has invalid authorization credentialsi  zOThe controlling host's Conjur identity does not have authorization to retrieve i  zThe variable z does not exist)	r   r=   rj   r5   rM   r   rs   r<   r   )
conjur_variabletokenrt   ru   rp   r>   r   r   rw   values
             r/   _fetch_conjur_variabler   u  s-   eE-W0E/Fa HIGL	'*[5Q4R
SCLL(./(/',/=(1	3H S ''88STU&&w/wS QRRS mn}m~  A  	AS ]?*;?KLLIr_   c                  `    t        j                  dt         j                        ryt               S )Nz/dev/shm)r8   accessW_OKr   r   r_   r/   _default_tmp_pathr     s    	yyRWW%<r_   c                     t        dt               d      }t        j                  |j                  t
        t        z         |j                  | d          |j                  gS )NrC   F)rE   dirrD   r   )r   r   r8   chmodrJ   r   r   rH   )r   secrets_files     r/   _store_secret_in_filer     sO    %34E4GPUVLHH\' 12uQx r_   c                       e Zd ZddZd Zy)LookupModuleNc                    |g k(  rt        d      |d   r|d   j                         rt        d      | j                  ||       | j                  d      }| j                  d      }| j                  d      }| j                  d      }| j                  d	      }| j                  d
      }	| j                  d      }
| j	                  d      }| j	                  d      }| j	                  d      }|du rt
        j                  d       dt        |      v rt        d      |du rt        |	|      }t        t        |      ||||dni |d|ini |
d|
ini       }d|vsd|vrt        d      d|vrF| j	                  d      }t        t        ||d         ||||dni       }d|vsd|vrt        d      d }d|v r t
        j                  d|d           |d   }	 d }d|vrt        |d   |d   d   |d   ||      }n\t        j                  j!                  |d         st        d |d    d!      t#        |d   d"      5 }|j%                         }d d d        t'        |d   ||d   |d   ||      }t(        rQ	 t        j                  j!                  t(        j*                        r#t        j,                  t(        j*                         |rt3        |      S |S # 1 sw Y   xY w# t.        t0        f$ r.}t        d#t(        j*                   d$t        |             |d }~ww xY w# t(        r	 t        j                  j!                  t(        j*                        r$t        j,                  t(        j*                         w w # t.        t0        f$ r.}t        d#t(        j*                   d$t        |             |d }~ww xY ww xY w)%Nz-Invalid secret path: no secret path provided.r   z4Invalid secret path: empty secret path not accepted.)var_optionsdirectconjur_appliance_urlconjur_accountconjur_authn_loginconjur_authn_api_keyconjur_cert_fileconjur_cert_contentconjur_authn_token_filerp   config_fileas_fileFzSCertificate validation has been disabled. Please enable with validate_certs option.zhttp://zL[WARNING]: Conjur URL uses insecure connection. Please consider using HTTPS.T)ru   rY   r>   authn_token_fileru   rY   a  Configuration must define options `conjur_account` and `conjur_appliance_url`.
                This config can be set by any of the following methods, listed in order of priority:
                - Ansible variables of the same name, set either in the parent playbook or passed to
                  the ansible-playbook command with the --extra-vars flag
                - Environment variables `CONJUR_ACCOUNT` and `CONJUR_APPLIANCE_URL`
                - A configuration file on the controlling host with fields `account` and `appliance_url`identity_filerT   rU   rV   a4  Configuration must define options `conjur_authn_login` and `conjur_authn_api_key`.
                    This config can be set by any of the following methods, listed in order of priority:
                    - Ansible variables of the same name, set either in the parent playbook or passed to
                      the ansible-playbook command with the --extra-vars flag
                    - Environment variables `CONJUR_AUTHN_LOGIN` and `CONJUR_AUTHN_API_KEY`
                    - An identity file on the controlling host with the fields `login` and `password`zUsing cert file path zConjur authn token file `z` was not found on the hostr2   z-Failed to delete temporary certificate file `r4   )r   isspaceset_optionsget_var_value
get_optionr5   r7   r)   rK   rf   rR   r^   r6   ry   r8   r9   r:   r;   r<   r   rG   rJ   unlinkOSErrorPermissionErrorr   )selfterms	variablesr   rY   ru   authn_loginauthn_api_keyr>   r-   r   rp   	conf_filer   confr   r[   r   r?   r   r.   s                        r/   runzLookupModule.run  sS   B;NOOQx58++-UVV 	Yv>**+AB$$%56(()=>**+AB&&'9:	))*?@--.GH)9:OOM2	//),U"OOqrM** nppT!-lIFI" +
 #!-	 #!.  ' Y  "- #$4 #
( D O4$?l  T) OOO<M*(_8MN !,!- &,
 H 8#y'@"i  	$KK/[0A/BCD[)I	DE!-+)OTNY'" ww~~d+=&>?&)B4HZC[B\\w'xyy$12D9 (T IIKE( 5a_%YO Dww~~n&9&9:		."5"56 (99-( (   1 D&)VWeWjWjVkknorsvownx'yz  AD  DD	 Dww~~n&9&9:		."5"56 ;1 D&)VWeWjWjVkknorsvownx'yz  AD  DD	 sc   "A&L, K !L, AK,  K)%L, ,L);)L$$L),O4ANOO)N>>OOc                 j    	 | j                  |      }|S # t        $ r}t        | d      |d }~ww xY w)Nz! was not defined in configuration)r   KeyErrorr   )r   keyvariable_valuer.   s       r/   r   zLookupModule.get_var_value'  sG    	S!__S1N   	S#&GHIsR	Ss    	2-2ra   )__name__
__module____qualname__r   r   r   r_   r/   r   r     s    DLr_   r   )NNTN)C
__future__r   r   r   type__metaclass__ANSIBLE_METADATADOCUMENTATIONEXAMPLESRETURNr8   r   	tracebackr*   r"   base64r   r   timer   statr   r   tempfiler   r   rN   +ansible.module_utils.six.moves.urllib.errormodule_utilssixmovesurlliberrorr~   ansible.errorsr   ansible.plugins.lookupr   +ansible.module_utils.six.moves.urllib.parser   ansible.module_utils.urlsr   ansible.utils.displayr   cryptography.x509r   cryptography.hazmat.backendsr   CRYPTOGRAPHY_IMPORT_ERRORImportError
format_excr5   rG   r0   rA   rK   rR   r^   rf   rj   ry   r   r   r   r   r   r   r   r_   r/   <module>r      s!   C B(-(k$/1 @D	
 
   
 	    ! 3  B B B ' - = . )%;< !%
)BD2"
/0%
 : q$% %%6N: NY  7 4	 4 4 67s   C C65C6