o
    K&bR                     @   s:  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	m
Z
mZmZmZmZmZ d dlmZmZmZmZmZmZ d dlmZmZmZ d dlmZ d dlmZmZ d d	l m!Z! d
Z"dZ#dZ$dZ%dZ&dZ'dZ(dZ)edde*fdee+ fdee+ fde*fgZ,ej-G dd dej.Z/G dd dej0Z1G dd dZ2G dd dZ3G dd  d Z4d!e
e+e
e+e+f f fd"d#Z5d$ee4 d%e
e+e*f d!e
e+e
e+e
e+e+f f f fd&d'Z6d(d) Z7d*ed+e+d!e/fd,d-Z8d.d/ Z9d0d1 Z:d2e4d3e
e+e
e+e+f f d!e
e+e2f fd4d5Z;d6e3d3e
e+e
e+e+f f d!e
e+e2f fd7d8Z<d+e+d9e
e+e2f fd:d;Z=d<e2d=e
e+e
e+e+f f d!e2fd>d?Z>d@dA Z?dBeee+e2f  dCe@dDe@d!e+fdEdFZAdGe+d*efdHdIZBdGe+d*ed!e*fdJdKZCd*edLe
e+eee+e2f  f dMe
e+ee+ f dCe@dDe@d!e,fdNdOZDdee+ d!e+fdPdQZEd*ed+e+d9e
e+e2f d3e
e+e
e+e+f f dRe
e+e
e+e
e+e+f f f d!e/fdSdTZFdldUdVZGd*edWe+d!e*fdXdYZHd*ed!e*fdZd[ZId*ed\e+d!e*fd]d^ZJdGe+d*ed!e*fd_d`ZKd*ed!e*fdadbZLd*ed!e*fdcddZMd*edeee+ dGe+d!e*fdfdgZNdhe+die+d!e*fdjdkZOdS )m    N)defaultdict)datetime)AnyDictList
NamedTupleOptionalSetTuple)apt
exceptionsmessagesserviceclientstatusutil)CLOUD_TYPE_TO_TITLE
PRO_CLOUDSget_cloud_type)UAConfig)BASE_UA_URLPRINT_WRAP_WIDTH)entitlement_factoryz=((CVE|cve)-\d{4}-\d{4,7}$|(USN|usn|LSN|lsn)-\d{1,5}-\d{1,2}$)z	cves.jsonzcves/{cve}.jsonznotices.jsonznotices/{notice}.jsonzUbuntu standard updateszUA InfrazUA AppsReleasedPackagesInstallResult
fix_statusunfixed_pkgsinstalled_pkgsall_already_installedc                   @   s   e Zd ZdZdZdZdZdS )	FixStatuszD
    An enum to represent the system status after fix operation
    r         N)__name__
__module____qualname____doc__SYSTEM_NON_VULNERABLESYSTEM_STILL_VULNERABLESYSTEM_VULNERABLE_UNTIL_REBOOT r'   r'   3/usr/lib/python3/dist-packages/uaclient/security.pyr   -   s
    r   c                       s6  e Zd ZdZdZejZdee	e
f dee	e
f fddZejejg dd		d# fd
d	Z																d$dee	 dee	 dee	 dee dee dee	 dee	 deee	  ded fddZde	ddfddZ										d%dee	 dee	 dee dee dee	 ded fddZd e	ddfd!d"Z  ZS )&UASecurityClient   Zsecurity_urlquery_paramsreturnc                 C   s.   | j j di di }|r|| |S |S )zD
        Update query params with data from feature config.
        Zfeaturesextra_security_params)cfggetupdate)selfr+   r-   r'   r'   r(   _get_query_params>   s   
z"UASecurityClient._get_query_params)r         )Zretry_sleepsNc                    s    |  |}t j|||||dS )N)pathdataheadersmethodr+   )r2   superrequest_url)r1   r5   r6   r7   r8   r+   	__class__r'   r(   r:   N   s   
zUASecurityClient.request_urlqueryprioritypackagelimitoffset	componentversionr   CVEc	              	      s:   ||||||||d}	 j t|	d\}
} fdd|
D S )znQuery to match multiple-CVEs.

        @return: List of CVE instances based on the the JSON response.
        )qr>   r?   r@   rA   rB   rC   r   r+   c                    s   g | ]}t  |d qS )clientresponse)rD   ).0Zcve_mdr1   r'   r(   
<listcomp>w   s    z-UASecurityClient.get_cves.<locals>.<listcomp>)r:   API_V1_CVES)r1   r=   r>   r?   r@   rA   rB   rC   r   r+   Zcves_response_headersr'   rK   r(   get_cves[   s   

zUASecurityClient.get_cvescve_idc                 C   "   |  tj|d\}}t| |dS )zkQuery to match single-CVE.

        @return: CVE instance for JSON response from the Security API.
        )cverG   )r:   API_V1_CVE_TMPLformatrD   )r1   rP   cve_responserN   r'   r'   r(   get_cvey      
zUASecurityClient.get_cvedetailsreleaseorderUSNc           	         sJ    ||||d}j t|d\}}t fdd|dg D dd dS )	zuQuery to match multiple-USNs.

        @return: Sorted list of USN instances based on the the JSON response.
        )rX   rY   r@   rA   rZ   rF   c                    s0   g | ]} d u s | dg v rt|dqS )Ncves_idsrG   )r/   r[   )rJ   Zusn_mdrX   r1   r'   r(   rL      s    
z0UASecurityClient.get_notices.<locals>.<listcomp>noticesc                 S      | j S Nidxr'   r'   r(   <lambda>       z.UASecurityClient.get_notices.<locals>.<lambda>key)r:   API_V1_NOTICESsortedr/   )	r1   rX   rY   r@   rA   rZ   r+   Zusns_responserN   r'   r]   r(   get_notices   s   

zUASecurityClient.get_notices	notice_idc                 C   rQ   )zbQuery to match single-USN.

        @return: USN instance representing the JSON response.
        )noticerG   )r:   API_V1_NOTICE_TMPLrT   r[   )r1   rl   Znotice_responserN   r'   r'   r(   
get_notice   rW   zUASecurityClient.get_notice)NNNN)NNNNNNNN)NNNNN)r    r!   r"   Zurl_timeoutZcfg_url_base_attrr   SecurityAPIErrorZapi_error_clsr   strr   r2   r   ZretrysocketZtimeoutr:   r   intr   rO   rV   rk   ro   __classcell__r'   r'   r;   r(   r)   8   sv    



	


r)   c                   @   s   e Zd ZdZdeeef fddZedd Z	edd Z
ed	d
 Zedd Zedd Zedd ZedefddZedd ZdS )CVEPackageStatuszAClass representing specific CVE PackageStatus on an Ubuntu seriesrU   c                 C   s
   || _ d S r`   rI   )r1   rU   r'   r'   r(   __init__   s   
zCVEPackageStatus.__init__c                 C   
   | j d S Ndescriptionrv   rK   r'   r'   r(   rz         
zCVEPackageStatus.descriptionc                 C   r_   r`   )rz   rK   r'   r'   r(   fixed_version   s   zCVEPackageStatus.fixed_versionc                 C   rx   )Npocketrv   rK   r'   r'   r(   r}      r{   zCVEPackageStatus.pocketc                 C   rx   )Nrelease_codenamerv   rK   r'   r'   r(   r~      r{   z!CVEPackageStatus.release_codenamec                 C   rx   )Nr   rv   rK   r'   r'   r(   r      r{   zCVEPackageStatus.statusc                 C   sz   | j dkrdS | j dkrdS | j dkrdS | j dv rdS | j d	kr#d
S | j dkr*dS | j dkr7tjj| jdS d| j S )NZneededzSorry, no fix is available yet.zneeds-triagez7Ubuntu security engineers are investigating this issue.Zpendingz)A fix is coming soon. Try again tomorrow.)ignoreddeferredzSorry, no fix is available.ZDNEz.Source package does not exist on this release.not-affectedz/Source package is not affected on this release.released)Z
fix_streamzUNKNOWN: {})r   r   ZSECURITY_FIX_RELEASE_STREAMrT   pocket_sourcerK   r'   r'   r(   status_message   s"   






zCVEPackageStatus.status_messager,   c                 C   s   t | jtkS )z>Return True if the package requires an active UA subscription.)boolr   UBUNTU_STANDARD_UPDATES_POCKETrK   r'   r'   r(   requires_ua      zCVEPackageStatus.requires_uac                 C   sP   | j dkr	t}|S | j dkrt}|S | j dv rt}|S d| jv r$t}|S t}|S )z>Human-readable string representing where the fix is published.	esm-infraesm-apps)ZupdatesZsecurityZesm)r}   UA_INFRA_POCKETUA_APPS_POCKETr   r|   )r1   Z
fix_sourcer'   r'   r(   r      s   

	

zCVEPackageStatus.pocket_sourceN)r    r!   r"   r#   r   rq   r   rw   propertyrz   r|   r}   r~   r   r   r   r   r   r'   r'   r'   r(   ru      s&    





ru   c                   @   s   e Zd ZdZdedeeef fddZde	fddZ
ed	d
 Zdd Zedee fddZeded fddZedd Zedeeef fddZdS )rD   z7Class representing CVE response from the SecurityClientrH   rI   c                 C      || _ || _d S r`   rI   rH   r1   rH   rI   r'   r'   r(   rw         
zCVE.__init__r,   c                 C      t |tsdS | j|jkS NF)
isinstancerD   rI   r1   otherr'   r'   r(   __eq__      
z
CVE.__eq__c                 C      | j dd S )Nrb   ZUNKNOWN_CVE_IDrI   r/   upperrK   r'   r'   r(   rb         zCVE.idc                 C   s>   | j }| jD ]}|j} dj| j|dd| jg}d|S )z2Return a string representing the URL for this cve.{issue}: {title}issuetitlehttps://ubuntu.com/security/{}
)rz   r^   r   rT   rb   join)r1   r   rm   linesr'   r'   r(   get_url_header  s   


zCVE.get_url_headerc                 C      | j dg S )Nnotices_idsrI   r/   rK   r'   r'   r(   r     s   zCVE.notices_idsr[   c                    <   t  dst fdd jdg D dd dd _ jS )	zReturn a list of USN instances from API response 'notices'.

        Cache the value to avoid extra work on multiple calls.
        _noticesc                       g | ]}t  j|qS r'   )r[   rH   )rJ   rm   rK   r'   r(   rL         
zCVE.notices.<locals>.<listcomp>r^   c                 S   r_   r`   ra   nr'   r'   r(   re      rf   zCVE.notices.<locals>.<lambda>Trh   reverse)hasattrrj   rI   r/   r   rK   r'   rK   r(   r^        

zCVE.noticesc                 C      | j dS ry   r   rK   r'   r'   r(   rz   %     zCVE.descriptionc                 C   sd   t | dr| jS i | _t d }| jd D ]}|d D ]}|d |kr-t|| j|d < qq| jS )zDict of package status dicts for the current Ubuntu series.

        Top-level keys are source packages names and each value is a
        CVEPackageStatus object
        _packages_statusseriesZpackagesZstatusesr~   name)r   r   r   get_platform_inforI   ru   )r1   r   r?   
pkg_statusr'   r'   r(   packages_status)  s   
zCVE.packages_statusN)r    r!   r"   r#   r)   r   rq   r   rw   r   r   r   rb   r   r   r   r^   rz   ru   r   r'   r'   r'   r(   rD      s    

rD   c                	   @   s   e Zd ZdZdedeeef fddZde	fddZ
edefd	d
Zedee fddZedee fddZedd Zedd Zdd Zedeeeeeeef f f fddZdS )r[   z7Class representing USN response from the SecurityClientrH   rI   c                 C   r   r`   r   r   r'   r'   r(   rw   @  r   zUSN.__init__r,   c                 C   r   r   )r   r[   rI   r   r'   r'   r(   r   D  r   z
USN.__eq__c                 C   r   )Nrb   ZUNKNOWN_USN_IDr   rK   r'   r'   r(   rb   I  r   zUSN.idc                 C   r   )z$List of CVE IDs related to this USN.r\   r   rK   r'   r'   r(   r\   M  r   zUSN.cves_idsc                    r   )	zList of CVE instances based on API response 'cves' key.

        Cache the values to avoid extra work for multiple call-sites.
        _cvesc                    r   r'   )rD   rH   )rJ   rR   rK   r'   r(   rL   Z  r   zUSN.cves.<locals>.<listcomp>cvesc                 S   r_   r`   ra   r   r'   r'   r(   re   ^  rf   zUSN.cves.<locals>.<lambda>Tr   )r   rj   rI   r/   r   rK   r'   rK   r(   r   R  r   zUSN.cvesc                 C   r   )Nr   r   rK   r'   r'   r(   r   c  r   z	USN.titlec                 C   r   )N
referencesr   rK   r'   r'   r(   r   g  r   zUSN.referencesc                 C   sr   dj | j| jdg}| jr!|d | jD ]
}|d | qn| jr4|d | jD ]}|| q,d|S )z5Return a string representing the URL for this notice.r   r   zFound CVEs:r   zFound Launchpad bugs:r   )rT   rb   r   r\   appendr   r   )r1   r   rR   Z	referencer'   r'   r(   r   k  s   




zUSN.get_url_headerc                 C   sJ  t | dr| jS t d }i | _| jdi |g D ]}|drW|d | jv rMd| j|d  v rCtjdj| j	|d d| j	d	|| j|d  d< qd|i| j|d < q|d
sltjdj| j	|d d| j	d	d|d
 vrtjdj| j	|d |d
 d| j	d	|d
 
dd }|| jvri | j|< || j| |d < q| jS )aW  Binary package information available for this release.


        Reformat the USN.release_packages response to key it based on source
        package name and related binary package names.

        :return: Dict keyed by source package name. The second-level key will
            be binary package names generated from that source package and the
            values will be the dict response from USN.release_packages for
            that binary package. The binary metadata contains the following
            keys: name, version.
            Optional additional keys: pocket and component.
        _release_packagesr   release_packagesZ	is_sourcer   sourcez6{usn} metadata defines duplicate source packages {pkg})usnpkgissue_idZsource_linkzL{issue} metadata does not define release_packages source_link for {bin_pkg}.)r   bin_pkg/zX{issue} metadata has unexpected release_packages source_link value for {bin_pkg}: {link})r   r   link)r   r   r   r   rI   r/   r   SecurityAPIMetadataErrorrT   rb   split)r1   r   r   source_pkg_namer'   r'   r(   r   z  sN   



	

zUSN.release_packagesN)r    r!   r"   r#   r)   r   rq   r   rw   r   r   r   rb   r   r\   rD   r   r   r   r   r   r'   r'   r'   r(   r[   =  s"    

,r[   r,   c            
      C   s   t  d } | dkrd}nd}t dd| d dg\}}i }| D ]%}|d	\}}}}	|s2|}d
|	vr7q#||v rB||| |< q#||i||< q#|S )zReturn a dict of all source packages installed on the system.

    The dict keys will be source package name: "krb5". The value will be a dict
    with keys binary_pkg and version.
    r   Ztrustyz	${Status}z${db:Status-Status}z
dpkg-queryz#-f=${Package},${Source},${Version},r   z-W,Z	installed)r   r   subp
splitlinesr   )
r   Zstatus_fieldoutZ_errinstalled_packagesZpkg_linepkg_namer   Zpkg_versionr   r'   r'   r(   #query_installed_source_pkg_versions  s*   
r   usnsbeta_pocketsc                    s   i }| D ]O}|j  D ]G\}} fdd| D }||vr%|r%|||< q||v rR|| }| D ] \}}	||vr>|	||< q1|| d }
|	d }t||
sQ|	||< q1qq|S )a  Walk related USNs, merging the released binary package versions.

    For each USN, iterate over release_packages to collect released binary
        package names and required fix version. If multiple related USNs
        require different version fixes to the same binary package, track the
        maximum version required across all USNs.

    :param usns: List of USN response instances from which to calculate merge.
    :param beta_pockets: Dict keyed on service name: esm-infra, esm-apps
        the values of which will be true of USN response instances
        from which to calculate merge.

    :return: Dict keyed by source package name. Under each source package will
        be a dict with binary package name as keys and binary package metadata
        as the value.
    c              	      s.   i | ]\}}d   | ddd u r||qS )Fr}   Noner/   )rJ   Zbin_pkg_nameZ
bin_pkg_mdr   r'   r(   
<dictcomp>  s    z>merge_usn_released_binary_package_versions.<locals>.<dictcomp>rC   )r   itemsversion_cmp_le)r   r   Zusn_pkg_versionsr   src_pkgZbinary_pkg_versionsZpublic_bin_pkg_versionsZusn_src_pkgr   Zbinary_pkg_mdZprev_versionZcurrent_versionr'   r   r(   *merge_usn_released_binary_package_versions  s(   



r   c                 C   sX   | j s| gS i }| j D ]}|jD ]}||vr|j|d||< qqtt| dd dS )zFor a give usn, get the related USNs for it.

    For each CVE associated with the given USN, we capture
    other USNs that are related to the CVE. We consider those
    USNs related to the original USN.
    rl   c                 S   r_   r`   ra   rc   r'   r'   r(   re     rf   z"get_related_usns.<locals>.<lambda>rg   )r   r   ro   listrj   values)r   rH   Zrelated_usnsrR   Zrelated_usn_idr'   r'   r(   get_related_usns	  s   


r   r.   r   c              
   C   sr  |  }t| d}t }tt| tt| d}d|v r_z|j|d}|j|d}W n# tj	yL } zt
|}d| v rCtjj|d}t|d }~ww t||d}	t|  t||}
nQz|j|d	}t||}W n# tj	y } zt
|}d| v rtjj|d}t|d }~ww t||d
}	t||}
t|  |jd stjd||dt| ||	||
dS )N)r.   )r   r   rD   )rP   )rX   z	not foundr   )rR   r   r   r   r   r   z.{} metadata defines no fixed package versions.)r.   r   affected_pkg_statusr   usn_released_pkgs)r   r)   r   _is_pocket_used_by_beta_servicer   r   rV   rk   r   rp   rq   lowerr   ZSECURITY_FIX_NOT_FOUND_ISSUErT   ZUserFacingError'get_cve_affected_source_packages_statusprintr   r   ro   r    get_usn_affected_packages_statusrI   r   prompt_for_affected_packages)r.   r   rH   r   r   rR   r   emsgr   r   r   r'   r'   r(   fix_security_issue_id"  sv   



r   c                 C   sZ   i }| D ]&}t || D ]\}}||vr|||< q|| j}t||js)|||< qq|S r`   )r   r   r|   r   )r   r   affected_pkgsrR   r   r   Zcurrent_verr'   r'   r(   get_affected_packages_from_cvesc  s   



r   c                 C   s   i }| j  D ]7\}}||vrqtt}d|d< dd | D }|s1d}tj|| j| jd| |d< t	|d||< q|S )	Nr   r   c                 S   s"   h | ]\}}| d r|d  qS )r}   r   )rJ   _Zpkg_bin_infor'   r'   r(   	<setcomp>~  s    z1get_affected_packages_from_usn.<locals>.<setcomp>zC{} metadata defines no pocket information for any release packages.r   r}   )rU   )
r   r   r   rq   r   r   rT   rb   popru   )r   r   r   r   Zpkg_inforU   Zall_pocketsr   r'   r'   r(   get_affected_packages_from_usnt  s$   r   r   r   c                 C   s   | j r	t| j |S t| |S )zWalk CVEs related to a USN and return a dict of all affected packages.

    :return: Dict keyed on source package name, with active CVEPackageStatus
        for the current Ubuntu release.
    )r   r   r   r   r'   r'   r(   r     s   
r   rR   c                 C   s8   i }| j  D ]\}}|jdkrq||v r|||< q|S )zGet a dict of any CVEPackageStatuses affecting this Ubuntu release.

    :return: Dict of active CVEPackageStatus keyed by source package names.
    r   )r   r   r   )rR   r   Zaffected_pkg_versionsZ
source_pkgZpackage_statusr'   r'   r(   r     s   
r   r   c                 C   s   t |}|dkrttjjdddd  ttjj| d dS |dkr&d	}nd}tjj||dd
 dt|  }tt	j
|tdd dS )a	  Print header strings describing affected packages related to a CVE/USN.

    :param issue_id: String of USN or CVE issue id.
    :param affected_pkg_status: Dict keyed on source package name, with active
        CVEPackageStatus for the current Ubuntu release.
    r   ZNozs are)count
plural_str.r   Nr   z isz: ,     widthsubsequent_indent)lenr   r   ZSECURITY_AFFECTED_PKGSrT   ZSECURITY_ISSUE_UNAFFECTEDr   rj   keystextwrapfillr   )r   r   r   r   r   r'   r'   r(   print_affected_packages_header  s.   	r  r   usn_src_released_pkgsc                 C   sh   t | }|r2|dr2d|jd< |d d |jd< | D ]\}}|d}|r1||jd<  |S q|S )a  Parse release status based on both pkg_status and USN.release_packages.

    Since some source packages in universe are not represented in
    CVEPackageStatus, rely on presence of such source packages in
    usn_src_released_pkgs to represent package as a "released" status.

    :param pkg_status: the CVEPackageStatus for this source package.
    :param usn_src_released_pkgs: The USN.release_packages representing only
       this source package. Normally, release_packages would have data on
       multiple source packages.

    :return: Tuple of:
        human-readable status message, boolean whether released,
        boolean whether the fix requires access to UA
    r   r   r   rC   rz   r}   )copyZdeepcopyr/   rI   r   )r   r  usn_pkg_statusr   Zusn_released_pkgr}   r'   r'   r(   #override_usn_release_package_status  s    




r  c                 C   sd   i }t |  D ]'\}}||i }t||}|jdd}||vr&g ||< || ||f q|S )Nr   r   )rj   r   r/   r  r   replacer   )r   r   Zstatus_groupsr   r   usn_released_srcr  Zstatus_groupr'   r'   r(   group_by_usn_package_status  s   r  pkg_status_list	pkg_indexnum_pkgsc                 C   s   | sdS g }g }| D ]\}}|d7 }| d|| | | q
tjddd| d dt|tdd	}d
||jS )z;Format the packages and status to an user friendly message. r   z{}/{}z{} {}:(r   )r   r   z{}
{})r   rT   r   r   r   rj   r   r   )r	  r
  r  Z	msg_indexZsrc_pkgsr   r   Z
msg_headerr'   r'   r(   _format_packages_message  s    r  r}   c                 C   s6   d}| t kr	d}n| tkrd}t|}|r||S d S )Nzno-service-neededr   r   )r   r   r   )r}   r.   Zservice_to_checkZent_clsr'   r'   r(   _get_service_for_pocket  s   r  c                 C   s6   t | |}|r| \}}|tjjkrdS |j S dS )zBCheck if the pocket where the fix is at belongs to a beta service.F)r  user_facing_statusr   UserFacingStatusACTIVEZvalid_service)r}   r.   ent
ent_statusr   r'   r'   r(   r   (  s   
r   src_pocket_pkgsbinary_pocket_pkgsc                 C   s   d}d}t  }t  }|rUtttfD ]C}	||	 }
||	 }|rBt|
||d}|r4t| |s2ttj qd}|t|
7 }|t	| ||	M }|sO|
dd |
D  q|
| qt||||dS )a%  Handle the packages that could be fixed and have a released status.

    :returns: Tuple of
        boolean whether all packages were successfully upgraded,
        list of strings containing the packages that were not upgraded,
        boolean whether all packages were already installed
    Tr	  r
  r  Fc                 S      g | ]\}}|qS r'   r'   rJ   r   r   r'   r'   r(   rL   l      z2_handle_released_package_fixes.<locals>.<listcomp>)r   r   r   r   )setr   r   r   r  r   r   ZSECURITY_UPDATE_INSTALLEDr   upgrade_packages_and_attachr0   r   )r.   r  r  r
  r  r   Zupgrade_statusr   r   r}   Zpkg_src_groupZbinary_pkgsr   r'   r'   r(   _handle_released_package_fixes8  sH   
r  c              
   C   sF   t | }tjd||dkrdnd|dkrdnddt| tdd	S )
zFormat the list of unfixed packages into an message.

    :returns: A string containing the message output for the unfixed
              packages.
    z"{} package{} {} still affected: {}r   sr  Zareisr   r   r   )r   r   r   rT   r   rj   r   )r   Znum_pkgs_unfixedr'   r'   r(   _format_unfixed_packages_msgx  s   r!  r   c                 C   sB  t |}t|| |dkrtjS tjj|d}tt}tt}d}	t	||}
g }t
|
 D ]\}}|dkrVtjj|d}tt||	|d |	t |7 }	|dd |D 7 }q.|D ]T\}}||j ||f ||  D ]?\}}||i }||vr|dd |D 7 }dj||d	}|t|7 }t|||| }|d
 }t||s||j | qlqXq.t| |||	|d}||j7 }|rtt| |jr|jrtt| |rtjS tjS tj|jdrtjjdd}t| |  d| tttjj|d tj!S tt| |rtjS tjS tttjj|d tjS )a  Process security CVE dict returning a CVEStatus object.

    Since CVEs point to a USN if active, get_notice may be called to fill in
    CVE title details.

    :returns: An FixStatus enum value corresponding to the system state
              after processing the affected packages
    r   r   r   r  c                 S   r  r'   r'   r  r'   r'   r(   rL     r  z0prompt_for_affected_packages.<locals>.<listcomp>c                 S   r  r'   r'   r  r'   r'   r(   rL     s    z5{issue} metadata defines no fixed version for {pkg}.
)r   r   rC   )r.   r  r  r
  r  )r   zfix operation)Z	operationr  )"r   r  r   r$   r   ZSECURITY_ISSUE_RESOLVEDrT   r   r   r  rj   r   ZSECURITY_ISSUE_NOT_RESOLVEDr   r  r   r   r/   r!  r   r   r   r  r   r   r   r   Zhandle_unicode_charactersr%   Zshould_rebootr   ZENABLE_REBOOT_REQUIRED_TMPLZ
add_noticer&   )r.   r   r   r   r   r   Zfix_messager  r  r
  Zpkg_status_groupsr   Zstatus_valueZpkg_status_groupr   r   Z
binary_pkgrC   r  r   Z	fixed_pkgr|   Zreleased_pkgs_install_resultZ
reboot_msgr'   r'   r(   r     s   




r   c                  C   s4   t  \} }| tv rttjjt| | d dS dS )z9Alert the user when running UA on cloud with PRO support.)r   ZcloudN)r   r   r   r   ZSECURITY_USE_PRO_TMPLrT   r   r/   )Z
cloud_typer   r'   r'   r(   *_inform_ubuntu_pro_existence_if_applicable  s   

r"  tokenc              
   C   sL   ddl }ddlm} ttdd|gg td||j|dddd| kS )	zkAttach to a UA subscription with a given token.

    :return: True if attach performed without errors.
    r   NcliuaZattachTr%  )r#  Zauto_enablerT   Zattach_config)	argparseuaclientr%  r   r   colorize_commandsr   Zaction_attach	Namespace)r.   r#  r'  r%  r'   r'   r(   _run_ua_attach  s   r+  c                 C   sp   t   ttj tjdg dd}|dkrdS |dkr$ttj td |dv r6ttj	 td	}t
| |S d
S )zZPrompt for attach to a subscription or token.

    :return: True if attach performed.
    zBChoose: [S]ubscribe at ubuntu.com [A]ttach existing token [C]ancel)r  acZvalid_choicesr-  Fr  z*Hit [Enter] when subscription is complete.)r,  r  > T)r"  r   r   Z*SECURITY_UPDATE_NOT_INSTALLED_SUBSCRIPTIONr   prompt_choicesr   ZPROMPT_UA_SUBSCRIPTION_URLinputZPROMPT_ENTER_TOKENr+  )r.   choicer#  r'   r'   r(   _prompt_for_attach.  s    



r3  servicec              	   C   s   ddl }ddlm} ttjj|d tjd|ddgd}|dkr?tt	
d	d
|gg td||j|gddd| kS dS )zLPrompt for enable a ua service.

    :return: True if enable performed.
    r   Nr$  r4  zChoose: [E]nable {} [C]ancelr   r-  r.  r&  ZenableTF)r4  
assume_yesZbeta)r'  r(  r%  r   r   ZSECURITY_SERVICE_DISABLEDrT   r   r0  r   r)  r   Zaction_enabler*  )r.   r4  r'  r%  r2  r'   r'   r(   _prompt_for_enableG  s(   
r7  c                 C   s   t | |}|r?| \}}|tjjkrdS | \}}|tjjkr5t||j	r)dS t
tjj|j	d dS t
tjj|j	d dS )z?Verify if the ua subscription has the required service enabled.Tr5  F)r  r  r   r  r  applicability_statusZApplicabilityStatusZ
APPLICABLEr7  r   r   r   ZSECURITY_UA_SERVICE_NOT_ENABLEDrT   Z SECURITY_UA_SERVICE_NOT_ENTITLED)r}   r.   r  r  r   r8  r'   r'   r(   (_check_subscription_for_required_servicee  s*   
r9  c                 C   s   ddl }ddlm} t  ttj tjd	t
ddgd}|dkrDttj td}ttd	d
gg ||jdd|  t| |S dS )zdPrompt for attach a new subscription token to the user.

    :return: True if attach performed.
    r   Nr$  z2Choose: [R]enew your subscription (at {}) [C]ancelrr-  r.  r/  r&  detachT)r6  F)r'  r(  r%  r"  r   r   Z%SECURITY_UPDATE_NOT_INSTALLED_EXPIREDr   r0  rT   r   r   ZPROMPT_EXPIRED_ENTER_TOKENr1  r)  Zaction_detachr*  r+  )r.   r'  r%  r2  r#  r'   r'   r(   _prompt_for_new_token  s"   


r<  c                 C   s(   | j }|j}|t|k rt|  S dS )znCheck if user UA subscription is expired.

    :returns: True if subscription is expired and not renewed.
    F)contract_expiry_datetimetzinfor   Znowr<  )r.   r=  r>  r'   r'   r(   _check_subscription_is_expired  s
   
r?  upgrade_packagesc                 C   s   |sdS t  dkrttj dS |tkr,| jst| sdS nt| r%dS t	|| s,dS tt
g dg d t| g tjddgtjjd tjg d	| tjjd
did dS )a   Upgrade available packages to fix a CVE.

    Upgrade all packages in upgrades_packages and, if necessary,
    prompt regarding system attach prior to upgrading UA packages.

    :return: True if package upgrade completed or unneeded, False otherwise.
    Tr   F)r   r0   z&&)r   install--only-upgrade-yapt-getr0   )cmd	error_msg)rD  rA  rB  rC  ZDEBIAN_FRONTENDZnoninteractive)rE  rF  env)osgetuidr   r   ZSECURITY_APT_NON_ROOTr   Zis_attachedr3  r?  r9  r   r)  rj   r   Zrun_apt_commandZAPT_UPDATE_FAILEDr   ZAPT_INSTALL_FAILED)r.   r@  r}   r'   r'   r(   r    sB   


	
r  version1version2c                 C   s2   zt dd| d|g W dS  tjy   Y dS w )z<Return True when version1 is less than or equal to version2.Zdpkgz--compare-versionsleTF)r   r   r   ZProcessExecutionError)rJ  rK  r'   r'   r(   r     s   r   )r,   N)Pr  enumrH  rr   r   collectionsr   r   typingr   r   r   r   r   r	   r
   r(  r   r   r   r   r   r   Zuaclient.clouds.identityr   r   r   Zuaclient.configr   Zuaclient.defaultsr   r   Zuaclient.entitlementsr   ZCVE_OR_USN_REGEXrM   rS   ri   rn   r   r   r   r   rq   r   uniqueEnumr   ZUAServiceClientr)   ru   rD   r[   r   r   r   r   r   r   r   r   r  r  r  rs   r  r  r   r  r!  r   r"  r+  r3  r7  r9  r<  r?  r  r   r'   r'   r'   r(   <module>   s   $ 


vEJ|!

/A





"
#

@

 

 
2