U
    ]6                     @   s  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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 ddlmZ ddlmZ dd	lmZ dd
lmZ eeZG dd deZdd Z G dd dej!Z"G dd dej#Z$G dd dej!Z%dS )z!Creates ACME accounts for server.    N)serialization)fields)messages)	constants)errors)
interfaces)util)osc                   @   sH   e Zd ZdZG dd dejZdddZedd Z	d	d
 Z
dd ZdS )AccountzACME protocol registration.

    :ivar .RegistrationResource regr: Registration Resource
    :ivar .JWK key: Authorized Account Key
    :ivar .Meta: Account metadata
    :ivar str id: Globally unique account identifier.

    c                   @   s$   e Zd ZdZedZedZ	dS )zAccount.Metaa+  Account metadata

        :ivar datetime.datetime creation_dt: Creation date and time (UTC).
        :ivar str creation_host: FQDN of host, where account has been created.

        .. note:: ``creation_dt`` and ``creation_host`` are useful in
            cross-machine migration scenarios.

        creation_dtcreation_hostN)
__name__
__module____qualname____doc__acme_fieldsZRFC3339Fieldr   joseFieldr    r   r   1/usr/lib/python3/dist-packages/certbot/account.pyMeta&   s   	
r   Nc                 C   sn   || _ || _|d kr:| jtjjtjdjddt	 dn|| _
t| j j  jtjjtjjd | _d S )N)Ztzr   )Zmicrosecond)r   r   )encodingformat)keyregrr   datetimeZnowpytzZUTCreplacesocketZgetfqdnmetahashlibZmd5Z
public_keyZpublic_bytesr   ZEncodingZPEMZPublicFormatZSubjectPublicKeyInfoZ	hexdigestid)selfr   r   r   r   r   r   __init__3   s&    zAccount.__init__c                 C   s&   d t| jj| jj| jdd S )z3Short account identification string, useful for UI.z{1}@{0} ({2})N   )r   	pyrfc3339Zgenerater   r   r   r!   r"   r   r   r   slugG   s     zAccount.slugc                 C   s   d | jj| j| j| jS )Nz<{0}({1}, {2}, {3})>)r   	__class__r   r   r!   r   r&   r   r   r   __repr__M   s       zAccount.__repr__c                 C   s0   t || jo.| j|jko.| j|jko.| j|jkS N)
isinstancer(   r   r   r   )r"   otherr   r   r   __eq__Q   s    


zAccount.__eq__)N)r   r   r   r   r   ZJSONObjectWithFieldsr   r#   propertyr'   r)   r-   r   r   r   r   r
      s   	

r
   c                 C   s4   t jtj}|dkrdS |d| j|j dS )z.Informs the user about their new ACME account.Na   Your account credentials have been saved in your Certbot configuration directory at {0}. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal.)	zopeZ	componentZqueryUtilityr   Z	IReporterZadd_messager   Z
config_dirZMEDIUM_PRIORITY)configZreporterr   r   r   report_new_accountW   s    r1   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )AccountMemoryStoragezIn-memory account storage.Nc                 C   s   |d k	r|ni | _ d S r*   )accounts)r"   Zinitial_accountsr   r   r   r#   i   s    zAccountMemoryStorage.__init__c                 C   s   t t| jS r*   )listsixZ
itervaluesr3   r&   r   r   r   find_alll   s    zAccountMemoryStorage.find_allc                 C   s*   |j | jkrtd|j  || j|j < d S )NzOverwriting account: %s)r!   r3   loggerdebugr"   accountZclientr   r   r   saveo   s    zAccountMemoryStorage.savec                 C   s0   z| j | W S  tk
r*   t|Y nX d S r*   )r3   KeyErrorr   AccountNotFoundr"   
account_idr   r   r   loadt   s    zAccountMemoryStorage.load)N)r   r   r   r   r#   r6   r;   r@   r   r   r   r   r2   f   s
   
r2   c                   @   s   e Zd ZdZedZdS )$RegistrationResourceWithNewAuthzrURIaf  A backwards-compatible RegistrationResource with a new-authz URI.

       Hack: Certbot versions pre-0.11.1 expect to load
       new_authzr_uri as part of the account. Because people
       sometimes switch between old and new versions, we will
       continue to write out this field for some time so older
       clients don't crash in that scenario.
    new_authzr_uriN)r   r   r   r   r   r   rB   r   r   r   r   rA   z   s   rA   c                   @   s   e Zd ZdZdd Zdd Zdd Zedd	 Zed
d Z	edd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(S ))AccountFileStoragezMAccounts file storage.

    :ivar .IConfig config: Client configuration

    c                 C   s   || _ t|jd| j j d S )N  )r0   r   make_or_verify_diraccounts_dirstrict_permissions)r"   r0   r   r   r   r#      s    zAccountFileStorage.__init__c                 C   s   |  || jjS r*   )!_account_dir_path_for_server_pathr0   server_pathr>   r   r   r   _account_dir_path   s    z$AccountFileStorage._account_dir_pathc                 C   s   | j |}tj||S r*   )r0   accounts_dir_for_server_pathr	   pathjoin)r"   r?   rI   rF   r   r   r   rH      s    z4AccountFileStorage._account_dir_path_for_server_pathc                 C   s   t j|dS )Nz	regr.jsonr	   rL   rM   clsaccount_dir_pathr   r   r   
_regr_path   s    zAccountFileStorage._regr_pathc                 C   s   t j|dS )Nzprivate_key.jsonrN   rO   r   r   r   	_key_path   s    zAccountFileStorage._key_pathc                 C   s   t j|dS )Nz	meta.jsonrN   rO   r   r   r   _metadata_path   s    z!AccountFileStorage._metadata_pathc              	   C   s   | j |}zt|}W n tk
r2   g  Y S X g }|D ]@}z|| || W q< tjk
rz   t	j
ddd Y q<X q<|s|tjkrtj| }| |}|rz| || W n tk
r   g  Y S X |}|S )NzAccount loading problemT)exc_info)r0   rK   r	   listdirOSErrorappend_load_for_server_pathr   AccountStorageErrorr7   r8   r   LE_REUSE_SERVERS_find_all_for_server_path_symlink_to_accounts_dir)r"   rI   rF   Z
candidatesr3   r?   prev_server_pathZprev_accountsr   r   r   r\      s*    



z,AccountFileStorage._find_all_for_server_pathc                 C   s   |  | jjS r*   )r\   r0   rI   r&   r   r   r   r6      s    zAccountFileStorage.find_allc                 C   s(   |  ||}|  ||}t|| d S r*   )rH   r	   symlink)r"   r^   rI   r?   prev_account_dirZnew_account_dirr   r   r   _symlink_to_account_dir   s    z*AccountFileStorage._symlink_to_account_dirc                 C   sJ   | j |}tj|r$t| n
t| | j |}t|| d S r*   )r0   rK   r	   rL   islinkunlinkrmdirr_   )r"   r^   rI   rF   r`   r   r   r   r]      s    
z+AccountFileStorage._symlink_to_accounts_dirc              
   C   s:  |  ||}tj|s||tjkrntj| }| ||}| j|}t	|r^| 
||| n| || |S td| zt| |}tj| }W 5 Q R X t| |}	tj|	 }
W 5 Q R X t| |}tj| }W 5 Q R X W n. tk
r, } zt|W 5 d }~X Y nX t||
|S )NAccount at %s does not exist)rH   r	   rL   isdirr   r[   rY   r0   rK   rV   ra   r]   r   r=   openrR   r   RegistrationResourceZ
json_loadsreadrS   r   ZJWKrT   r
   r   IOErrorrZ   )r"   r?   rI   rQ   r^   Zprev_loaded_accountrF   	regr_filer   key_filer   metadata_filer   errorr   r   r   rY      s.    


z(AccountFileStorage._load_for_server_pathc                 C   s   |  || jjS r*   )rY   r0   rI   r>   r   r   r   r@      s    zAccountFileStorage.loadc                 C   s   | j ||dd d S )NF	regr_only_saver9   r   r   r   r;      s    zAccountFileStorage.savec                 C   s   | j ||dd dS )zmSave the registration resource.

        :param Account account: account whose regr should be saved

        Tro   Nrq   )r"   r:   acmer   r   r   	save_regr   s    zAccountFileStorage.save_regrc                 C   sT   |  |}tj|s$td| | || jj t	| jj
sP| | jj dS )znDelete registration info from disk

        :param account_id: id of account which should be deleted

        re   N)rJ   r	   rL   rf   r   r=   #_delete_account_dir_for_server_pathr0   rI   rV   rF   $_delete_accounts_dir_for_server_path)r"   r?   rQ   r   r   r   delete   s    
zAccountFileStorage.deletec                 C   s(   t | j|}| ||}t| d S r*   )	functoolspartialrH   !_delete_links_and_find_target_dirshutilZrmtree)r"   r?   rI   	link_funcnonsymlinked_dirr   r   r   ru     s    z6AccountFileStorage._delete_account_dir_for_server_pathc                 C   s"   | j j}| ||}t| d S r*   )r0   rK   rz   r	   rd   )r"   rI   r|   r}   r   r   r   rv     s    z7AccountFileStorage._delete_accounts_dir_for_server_pathc           
      C   s   ||}i }t jD ]}||t j| < qd}|rrd}||kr*|| }||}tj|r*t||kr*d}|}|}q*tj|rt|}	t| |	}qr|S )a/  Delete symlinks and return the nonsymlinked directory path.

        :param str server_path: file path based on server
        :param callable link_func: callable that returns possible links
            given a server_path

        :returns: the final, non-symlinked target
        :rtype: str

        TF)r   r[   r	   rL   rb   readlinkrc   )
r"   rI   r|   Zdir_pathZreused_serverskZpossible_next_linkZnext_server_pathZnext_dir_pathtargetr   r   r   rz     s&    


z4AccountFileStorage._delete_links_and_find_target_dirc           
   
   C   s  |  |j}t|d| jj zt| |dL}|j}t	|j
drZt|j
ji |jd}ntji |jd}||  W 5 Q R X |stj| |ddd}||j  W 5 Q R X t| |d}||j  W 5 Q R X W n. tk
r }	 zt|	W 5 d }	~	X Y nX d S )NrD   wz	new-authz)rB   bodyuri)r   r      )chmod)rJ   r!   r   rE   r0   rG   rg   rR   r   hasattrZ	directoryrA   Z	new_authzr   r   rh   writeZ
json_dumpsZ	safe_openrS   r   rT   r   rj   r   rZ   )
r"   r:   rs   rp   rQ   rk   r   rl   rm   rn   r   r   r   rr   <  s@     zAccountFileStorage._saveN)r   r   r   r   r#   rJ   rH   classmethodrR   rS   rT   r\   r6   ra   r]   rY   r@   r;   rt   rw   ru   rv   rz   rr   r   r   r   r   rC      s.   


	'rC   )&r   r   rx   r    Zloggingr{   r   Zjosepyr   r%   r   r5   Zzope.componentr/   Zcryptography.hazmat.primitivesr   rs   r   r   r   Zcertbotr   r   r   r   Zcertbot.compatr	   Z	getLoggerr   r7   objectr
   r1   ZAccountStorager2   rh   rA   rC   r   r   r   r   <module>   s2   
;