
\\r                 @   s  d  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	 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 d d	 l m 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 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 d l m" Z" d d l m# Z# d d l$ m% Z& d d l$ m' Z' d d l( m) Z* e j+ e,  Z- d d d  Z. d d   Z/ d d   Z0 Gd d   d e1  Z2 d  d!   Z3 d d" d#  Z4 d$ d%   Z5 Gd& d'   d' e1  Z6 d d( d)  Z7 d* d+   Z8 d d, d-  Z9 d. d/   Z: d0 d1   Z; d S)2zCertbot client API.    N)default_backend)generate_private_key)client)crypto_util)errors)messages)Optional)account)auth_handler)cli)compat)	constants)eff)error_handler)
interfaces)reverter)storage)util)ops)enhancements)	selectionc          	   C   sA   t  j | d | d |  j d t |   } t  j | | |  j  S)z Wrangle ACME client constructionr	   Z
verify_ssl
user_agent)acme_clientZClientNetworkZno_verify_ssldetermine_user_agentZBackwardsCompatibleClientV2server)configkeyregrnet r   0/usr/lib/python3/dist-packages/certbot/client.pyacme_from_config_key.   s    r!   c             C   s   |  j  d k r d } t j j d  d k rB d } d } d } n! t j } t j   } t j	   } | j
 t j | | |  j |  j |  j t |   | |  j r d |  j n d	 	 } n	 |  j  } | S)
z
    Set a user_agent string in the config based on the choice of plugins.
    (this wasn't knowable at construction time)

    :returns: the client's User-Agent string
    :rtype: `str`
    Nz\CertbotACMEClient/{0} ({1}; {2}{8}) Authenticator/{3} Installer/{4} ({5}; flags: {6}) Py/{7}ZCERTBOT_DOCS1zcertbot(-auto)zOS_NAME OS_VERSIONzmajor.minor.patchlevelz;  )r   osenvirongetr   cli_commandr   Zget_os_info_uaplatformpython_versionformatcertbot__version__authenticator	installerverbua_flagsZuser_agent_comment)r   Zuar'   Zos_infor)   r   r   r    r   6   s    		"	r   c                s   t    t  r d Sg  }   j r/ | j d    j rE | j d    j r[ | j d    j rq | j d  d }   f d d   | D } t |  r | j d  d j |  S)z@Turn some very important CLI flags into clues in the user agent.FLAGSdupZfrnZasnnprepostrenewmanual_authmanual_cleanupc                s#   g  |  ] } t    | d    q S)Z_hook)getattr).0h)r   r   r    
<listcomp>c   s   	 zua_flags.<locals>.<listcomp>hook )r4   r5   r6   r7   r8   )	
isinstanceDummyConfigZ	duplicateappendZrenew_by_defaultallow_subset_of_namesnoninteractive_modeanyjoin)r   flagsZ
hook_namesZhooksr   )r   r    r0   U   s     				r0   c               @   s.   e  Z d  Z d Z d d   Z d d   Z d S)r@   z'Shim for computing a sample user agent.c             C   s(   d |  _  d |  _ d  |  _ d |  _ d  S)NZXXXZYYYZ
SUBCOMMAND)r-   r.   r   r/   )selfr   r   r    __init__j   s    			zDummyConfig.__init__c             C   s   d S)z-Any config properties we might have are None.Nr   )rG   namer   r   r    __getattr__p   s    zDummyConfig.__getattr__N)__name__
__module____qualname____doc__rH   rJ   r   r   r   r    r@   h   s   r@   c               C   s   t  t    S)z<Document what this Certbot's user agent string will be like.)r   r@   r   r   r   r    sample_user_agentt   s    rO   c       	      C   s$  | j    r t j d |  j  |  j d k ro |  j sY d } t j |  t j |   |  j	 so t j d  |  j	 r d |  _ t
 d d d |  j d t    } t j d	 t j |   } t |  |  } t | |  |  } t j | |  } t j |   | j | |  t j |   | | f S)
a  Register new account with an ACME CA.

    This function takes care of generating fresh private key,
    registering the account, optionally accepting CA Terms of Service
    and finally saving the account. It should be called prior to
    initialization of `Client`, unless account has already been created.

    :param .IConfig config: Client configuration.

    :param .AccountStorage account_storage: Account storage where newly
        registered account will be saved to. Save happens only after TOS
        acceptance step, so any account private keys or
        `.RegistrationResource` will not be persisted if `tos_cb`
        returns ``False``.

    :param tos_cb: If ACME CA requires the user to accept a Terms of
        Service before registering account, client action is
        necessary. For example, a CLI tool would prompt the user
        acceptance. `tos_cb` must be a callable that should accept
        `.RegistrationResource` and return a `bool`: ``True`` iff the
        Terms of Service present in the contained
        `.Registration.terms_of_service` is accepted by the client, and
        ``False`` otherwise. ``tos_cb`` will be called only if the
        client action is necessary, i.e. when ``terms_of_service is not
        None``. This argument is optional, if not supplied it will
        default to automatic acceptance!

    :raises certbot.errors.Error: In case of any client problems, in
        particular registration failure, or unaccepted Terms of Service.
    :raises acme.errors.Error: In case of any protocol problems.

    :returns: Newly registered and saved account, as well as protocol
        API handle (should be used in `Client` initialization).
    :rtype: `tuple` of `.Account` and `acme.client.Client`

    z*There are already existing accounts for %sNzLNo email was provided and --register-unsafely-without-email was not present.zRegistering without email!Zpublic_exponenti  Zkey_sizeZbackendr   )Zfind_allloggerinfor   emailZregister_unsafely_without_emailwarningr   Errordry_runr   rsa_key_sizer   joseZJWKRSAZComparableRSAKeyr!   perform_registrationr	   ZAccountZreport_new_accountsaver   Zhandle_subscription)	r   Zaccount_storagetos_cbmsgZrsa_keyr   acmer   Zaccr   r   r    registerz   s.    &					r]   c       	      C   sb  | j  o | j } | rc |  j j j j   } t j j d | d | j  d | j d |  j j	  } n d } |  j
   r | s d } t j |   y2 t j j d | j d |  } |  j | |  SWn t j k
 r]} zv | j d	 k s | j d
 k rH| j r d | j } t j |   qKt j d d  | _ t |  | |  Sn   WYd d } ~ Xn Xd S)aj  
    Actually register new account, trying repeatedly if there are email
    problems

    :param acme.client.Client client: ACME client object.
    :param .IConfig config: Client configuration.
    :param Callable tos_cb: a callback to handle Term of Service agreement.

    :returns: Registration Resource.
    :rtype: `acme.messages.RegistrationResource`
    account_public_keyZkidZhmac_key	directoryNzRServer requires external account binding. Please use --eab-kid and --eab-hmac-key.rR   Zexternal_account_bindingZinvalidEmailZinvalidContactzzThe ACME server believes %s is an invalid email address. Please ensure it is a valid email and attempt registration again.ZinvalidT)Zeab_kidZeab_hmac_keyr   r   r   Z
public_keyr   ZExternalAccountBindingZ	from_datar_   Zexternal_account_requiredr   rT   ZNewRegistrationrR   Znew_account_and_toscoderC   display_opsZ	get_emailrX   )	r\   r   rZ   Zeab_credentials_suppliedr^   Zeabr[   Znewreger   r   r    rX      s2    				
rX   c               @   s   e  Z d  Z d Z d d d  Z d d d  Z d d d  Z d	 d
   Z d d   Z d d   Z	 d d   Z
 d d   Z d d d  Z d d d  Z d d   Z d d   Z d S)Clientaq  Certbot's client.

    :ivar .IConfig config: Client configuration.
    :ivar .Account account: Account registered with `register`.
    :ivar .AuthHandler auth_handler: Authorizations handler that will
        dispatch DV challenges to appropriate authenticators
        (providing `.IAuthenticator` interface).
    :ivar .IAuthenticator auth: Prepared (`.IAuthenticator.prepare`)
        authenticator that can solve ACME challenges.
    :ivar .IInstaller installer: Installer.
    :ivar acme.client.BackwardsCompatibleClientV2 acme: Optional ACME
        client API handle. You might already have one from `register`.

    Nc             C   s   | |  _  | |  _ | |  _ | |  _ | d k r] |  j d k	 r] t | |  j j |  j j  } | |  _ | d k	 r t j	 | |  j |  j |  j  j
  |  _ n	 d |  _ d S)zInitialize a client.N)r   r	   authr.   r!   r   r   r\   r
   ZAuthHandlerZpref_challs)rG   r   Zaccount_rd   r.   r\   r   r   r    rH     s    					$zClient.__init__c             C   s   |  j  d k r1 d } t j |  t j |   |  j j d k rR t j d   t j d |  | d k r |  j | j	 d d } t
 j
 j   t
 j d d  } |  j j | |  } t j | j  \ } } | j   | j   f S)	aW  Obtain certificate.

        :param .util.CSR csr: PEM-encoded Certificate Signing
            Request. The key used to generate this CSR can be different
            than `authkey`.
        :param acme.messages.OrderResource orderr: contains authzrs

        :returns: certificate and chain as PEM byte strings
        :rtype: tuple

        Nz>Unable to obtain certificate because authenticator is not set.z+Please register with the ACME server first.zCSR: %sbest_effortFZsecondsZ   )r
   rP   rS   r   rT   r	   r   debug_get_order_and_authorizationsdatadatetimeZnowZ	timedeltar\   Zfinalize_orderr   Zcert_and_chain_from_fullchainZfullchain_pemencode)rG   csrorderrr[   Zdeadlinecertchainr   r   r    obtain_certificate_from_csr  s    z"Client.obtain_certificate_from_csrc                s  | d k	 rb t  | d   } | } | j   } Wd QRXt j d | d |  } t j d |  n d } |  j j r | p t j d d d t j	 |  j j
   } t j d d d d d t j | j | |  j j   } n? | p t j |  j j
 |  j j  } t j | | |  j j  } |  j | j |  j j  } | j }	 t d d	   |	 D      f d
 d   | D }
 |  j j r|
 | k r|  j j st j | j  t j | j  |  j |
  S|  j | |  \ } } | | | | f Sd S)a  Obtains a certificate from the ACME server.

        `.register` must be called before `.obtain_certificate`

        :param list domains: domains to get a certificate

        :returns: certificate as PEM string, chain as PEM string,
            newly generated private key (`.util.Key`), and DER-encoded
            Certificate Signing Request (`.util.CSR`).
        :rtype: tuple

        Nrbfilepemz%Reusing existing private key from %s.formri   c             s   s   |  ] } | j  j j Vq d  S)N)ZbodyZ
identifiervalue)r:   ar   r   r    	<genexpr>c  s    z,Client.obtain_certificate.<locals>.<genexpr>c                s"   g  |  ] } |   k r |  q Sr   r   )r:   d)auth_domainsr   r    r<   d  s   	 z-Client.obtain_certificate.<locals>.<listcomp>)openreadr   ZKeyrP   rQ   r   rU   r   Zmake_keyrV   CSRacme_crypto_utilZmake_csrrs   Zmust_stapleZinit_save_keyZkey_dirZinit_save_csrZcsr_dirrh   ri   rB   authorizationssetr$   removerr   obtain_certificaterp   )rG   domainsZold_keypathfZkeypathZkeypemr   rl   rm   authzrZsuccessful_domainsrn   ro   r   )ry   r    r   1  s6    	zClient.obtain_certificatec             C   sb   y |  j  j |  } Wn$ t j k
 r< t j d   Yn X|  j j | |  } | j d |  S)a`  Request a new order and complete its authorizations.

        :param str csr_pem: A CSR in PEM format.
        :param bool best_effort: True if failing to complete all
            authorizations should not raise an exception

        :returns: order resource containing its completed authorizations
        :rtype: acme.messages.OrderResource

        zWThe currently selected ACME CA endpoint does not support issuing wildcard certificates.r~   )	r\   Z	new_orderacme_errorsZWildcardUnsupportedErrorr   rT   r
   Zhandle_authorizationsupdate)rG   Zcsr_pemre   rm   r   r   r   r    rh   u  s    z$Client._get_order_and_authorizationsc             C   s   |  j  |  \ } } } } |  j j t j d k sM |  j j t j d k rZ t j d  |  j | |  } |  j j	 r t j
 d |  d St j j | | | j | |  j  Sd S)aq  Obtain and enroll certificate.

        Get a new certificate for the specified domains using the specified
        authenticator and installer, and then create a new renewable lineage
        containing it.

        :param domains: domains to request a certificate for
        :type domains: `list` of `str`
        :param certname: requested name of lineage
        :type certname: `str` or `None`

        :returns: A new :class:`certbot.storage.RenewableCert` instance
            referred to the enrolled cert lineage, False if the cert could not
            be obtained, or None if doing a successful dry run.

        
config_dirwork_dirzdNon-standard path(s), might not work with crontab installed by your operating system package managerz-Dry run: Skipping creating new lineage for %sN)r   r   r   r   ZCLI_DEFAULTSr   rP   rQ   _choose_lineagenamerU   rg   r   ZRenewableCertZnew_lineagers   )rG   r   certnamern   ro   r   _new_namer   r   r    obtain_and_enroll_certificate  s    			z$Client.obtain_and_enroll_certificatec             C   s;   | r
 | St  j | d  r/ | d d d  S| d Sd S)a/  Chooses a name for the new lineage.

        :param domains: domains in certificate request
        :type domains: `list` of `str`
        :param certname: requested name of lineage
        :type certname: `str` or `None`

        :returns: lineage name that should be used
        :rtype: str

        r      N)r   Zis_wildcard_domain)rG   r   r   r   r   r    r     s
    zClient._choose_lineagenamec             C   s   xE | | | f D]4 } t  j t j j |  d t j   |  j j  q Wt	 d |  \ } } z | j
 |  Wd | j   Xt j d |  t	 d |  \ }	 }
 t	 d |  \ } } t | |	  t | | |  | |
 | f S)a   Saves the certificate received from the ACME server.

        :param str cert_pem:
        :param str chain_pem:
        :param str cert_path: Candidate path to a certificate.
        :param str chain_path: Candidate path to a certificate chain.
        :param str fullchain_path: Candidate path to a full cert chain.

        :returns: cert_path, chain_path, and fullchain_path as absolute
            paths to the actual files
        :rtype: `tuple` of `str`

        :raises IOError: If unable to find room to write the cert files

        i  	cert_pathNz4Server issued certificate; certificate written to %s
chain_pathfullchain_path)r   Zmake_or_verify_dirr$   pathdirnamer   Z
os_geteuidr   Zstrict_permissions_open_pem_filewritecloserP   rQ   _save_chain)rG   Zcert_pem	chain_pemr   r   r   r   Z	cert_fileZabs_cert_path
chain_fileZabs_chain_pathZfullchain_fileZabs_fullchain_pathr   r   r    save_certificate  s    	zClient.save_certificatec             C   s  |  j  d k r+ t j d  t j d   | d k r= d n t j j |  } d } t j	 |  j
 |  v x^ | D]V } |  j  j d | d t j j |  d t j j |  d | d	 |  |  j  j   qr W|  j  j d
  Wd QRXd } t j	 |  j |   |  j  j   Wd QRXd S)a  Install certificate

        :param list domains: list of domains to install the certificate
        :param str privkey_path: path to certificate private key
        :param str cert_path: certificate file path (optional)
        :param str chain_path: chain file path

        NzANo installer specified, client is unable to deploythe certificatezNo installer availablez!Unable to install the certificateZdomainr   Zkey_pathr   r   zDeployed ACME CertificatezuWe were unable to install your certificate, however, we successfully restored your server to its prior configuration.)r.   rP   rS   r   rT   r$   r   abspathr   ErrorHandler_recovery_routine_with_msgZdeploy_certrY   _rollback_and_restartrestart)rG   r   Zprivkey_pathr   r   r   r[   domr   r   r    deploy_certificate  s"    
$zClient.deploy_certificateTc          	   C   s2  |  j  d k r+ t j d  t j d   d } d d d	 d
 | f d f } |  j  j   } x | D] \ } } }	 t |  j |  }
 | | k r | r | d k r |
 d k r t j	 |  }
 |
 r |  j
 | | |	  d } qb |
 rb t j d |  qb Wd } | r.t j |  j |   |  j  j   Wd QRXd S)a  Enhance the configuration.

        :param list domains: list of domains to configure
        :param chain_path: chain file path
        :type chain_path: `str` or `None`

        :raises .errors.Error: if no installer is specified in the
            client.

        NzDNo installer is specified, there isn't any configuration to enhance.zNo installer availableFhstsensure-http-headerStrict-Transport-SecurityredirectZstaplezstaple-ocspuirUpgrade-Insecure-RequestsTzKOption %s is not supported by the selected installer. Skipping enhancement.z$We were unable to restart web server)r   r   r   )r   r   N)r   r   r   )r.   rP   rS   r   rT   Zsupported_enhancementsr9   r   r   Zaskapply_enhancementr   r   r   r   )rG   r   r   Zask_redirectZenhancedZenhancement_infoZ	supportedZconfig_nameZenhancement_nameZoptionZconfig_valuer[   r   r   r    enhance_config  s4    		zClient.enhance_configc             C   s   d | } t  j |  j |   x | D] } y |  j j | | |  Wq' t j k
 r | d k ry t j d |  n t j d |  Yq' t j	 k
 r t j d | |    Yq' Xq' W|  j j
 d |  Wd QRXd S)a  Applies an enhancement on all domains.

        :param list domains: list of ssl_vhosts (as strings)
        :param str enhancement: name of enhancement, e.g. ensure-http-header
        :param str options: options to enhancement, e.g. Strict-Transport-Security

            .. note:: When more `options` are needed, make options a list.

        :raises .errors.PluginError: If Enhancement is not supported, or if
            there is any other problem with the enhancement.


        zmWe were unable to set up enhancement %s for your server, however, we successfully installed your certificate.zensure-http-headerzEnhancement %s was already set.z#Unable to set enhancement %s for %szAdd enhancement %sN)r   r   r   r.   Zenhancer   ZPluginEnhancementAlreadyPresentrP   rS   ZPluginErrorrY   )rG   r   ZenhancementZoptionsr[   r   r   r   r    r   ;  s"    	
		
zClient.apply_enhancementc             C   s9   |  j  j   t j j t j  } | j | | j  d S)zCalls the installer's recovery routine and prints success_msg

        :param str success_msg: message to show on successful recovery

        N)	r.   recovery_routinezope	component
getUtilityr   	IReporteradd_messageHIGH_PRIORITY)rG   success_msgreporterr   r   r    r   ^  s    z!Client._recovery_routine_with_msgc          	   C   sx   t  j d  t j j t j  } y |  j j   |  j j	   Wn | j
 d | j    Yn X| j
 | | j  d S)zRollback the most recent checkpoint and restart the webserver

        :param str success_msg: message to show on successful rollback

        z0Rolling back to previous server configuration...zAn error occurred and we failed to restore your config and restart your server. Please post to https://community.letsencrypt.org/c/server-config with details about your configuration and this error you received.N)rP   Zcriticalr   r   r   r   r   r.   rollback_checkpointsr   r   r   )rG   r   r   r   r   r    r   h  s    
zClient._rollback_and_restart)rK   rL   rM   rN   rH   rp   r   rh   r   r   r   r   r   r   r   r   r   r   r   r    rc      s   D%*$+#
rc   c             C   s   |  j  r+ t j |  j   r+ t j d   | r | j d k r t j j t j j	 | j
  } t j j t j j |  } t j | j | d  } | j
 r t j | j
  r t j d   | j
 r |  j  r t j | j
 |  j   s t j d   d S)a  Validate Key and CSR files.

    Verifies that the client key and csr arguments are valid and correspond to
    one another. This does not currently check the names in the CSR due to
    the inability to read SANs from CSRs in python crypto libraries.

    If csr is left as None, only the key will be validated.

    :param privkey: Key associated with CSR
    :type privkey: :class:`certbot.util.Key`

    :param .util.CSR csr: CSR

    :raises .errors.Error: when validation fails

    z#The provided key is not a valid keyZderrs   z#The provided CSR is not a valid CSRzThe key and CSR do not matchN)rs   r   Zvalid_privkeyr   rT   rt   OpenSSLZcryptoZload_certificate_requestZFILETYPE_ASN1ri   Zdump_certificate_requestZFILETYPE_PEMr   r|   rr   Z	valid_csrZcsr_matches_pubkey)Zprivkeyrl   Zcsr_objZcert_bufferr   r   r    validate_key_csr~  s    		r   c             C   sB   t  j | |  | d d } | d k	 r> | j |  | j   d S)zRevert configuration the specified number of checkpoints.

    :param int checkpoints: Number of checkpoints to revert.

    :param config: Configuration.
    :type config: :class:`certbot.interfaces.IConfig`

    Zquestionz,Which installer should be used for rollback?N)plugin_selectionZpick_installerr   r   )Zdefault_installerZcheckpointsr   Zpluginsr.   r   r   r    rollback  s
    
r   c             C   s*   t  j |   } | j   | j |  d S)zView checkpoints and associated configuration changes.

    .. note:: This assumes that the installation is using a Reverter object.

    :param config: Configuration.
    :type config: :class:`certbot.interfaces.IConfig`

    N)r   ZReverterr   view_config_changes)r   ZnumZrevr   r   r    r     s    	
r   c             C   sq   t  j |   r: t j | d d d d t j j |  f St j | d d  } | d t j j | d  f Sd S)a'  Open a pem file.

    If cli_arg_path was set by the client, open that.
    Otherwise, uniquify the file path.

    :param str cli_arg_path: the cli arg name, e.g. cert_path
    :param str pem_path: the pem file path to open

    :returns: a tuple of file object and its absolute file path

    chmodi  modewbr      N)r   Z
set_by_clir   Z	safe_openr$   r   r   Zunique_file)Zcli_arg_pathZpem_pathZuniqr   r   r    r     s
    r   c             C   s6   z | j  |   Wd | j   Xt j d | j  d S)zSaves chain_pem at a unique path based on chain_path.

    :param str chain_pem: certificate chain in PEM format
    :param str chain_file: chain file object

    NzCert chain written to %s)r   r   rP   rQ   rI   )r   r   r   r   r    r     s    r   )<rN   rj   Zloggingr$   r(   Zcryptography.hazmat.backendsr   Z-cryptography.hazmat.primitives.asymmetric.rsar   ZjosepyrW   r   Zzope.componentr   r\   r   r   r   r}   r   r   r   Zacme.magic_typingr   r+   r	   r
   r   r   r   r   r   r   r   r   r   Zcertbot.displayr   ra   r   Zcertbot.pluginsr   r   Z	getLoggerrK   rP   r!   r   r0   objectr@   rO   r]   rX   rc   r   r   r   r   r   r   r   r   r    <module>   s\   H/ .