
    0                         d Z ddlm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mZ g dZg dZg dZdZd Zd Zd Zd Zd Zd Zd Z d Z!y)z/Utility for interacting with vex command group.    )absolute_import)division)unicode_literalsN)
exceptions)util)apis)docker_util)log)
FileReader)component_not_presentvulnerable_code_not_present1vulnerable_code_cannot_be_controlled_by_adversary#vulnerable_code_not_in_execute_path inline_mitigations_already_exist)known_affectedknown_not_affectedfixedunder_investigation)
mitigationno_fix_plannednone_available
vendor_fix
workaroundz
^[^:@\/]+$c                    t        j                  dd      }	 t        |       5 }t        j                  |      }ddd       t               d}d}|j                  d      }|5|j                  d      }	|	"|	j                  d      }|	j                  d	      }|j                  ||
      }	|r|n|}
i }|d   d   D ]O  }|d   }t        |      }||k7  r|d   }|d   }dj                  |
      }
|j                  |d   ||
      }|||<   Q g }|d   D ]  }|d   D ]  }|d   |   D ]t  }|j                  |      }|t        ||||	||      \  }}|dj                  |      }|j                  j                   j#                  ||      }|j%                  |       v   ||
fS # 1 sw Y   oxY w# t
        $ r t        j                  d      w xY w)a  Reads a vex file and extracts notes.

  Args:
    filename: str, path to the vex file.
    image_uri: uri of the whole image
    version_uri: uri of a specific version

  Returns:
    A list of notes.

  Raises:
    ar_exceptions.InvalidInputValueError if user input is invalid.
  containeranalysisv1NzReading json file has failed document	publishername	namespace)r    publisherNamespaceproduct_treebranchesproduct
product_idz
https://{})r    id
genericUrivulnerabilitiesproduct_statuszimage-{})keyvalue)r   GetMessagesModuler   jsonload
ValueErrorar_exceptionsInvalidInputValueError	_Validateget	PublisherRemoveHTTPSformatProduct	_MakeNoteBatchCreateNotesRequest
NotesValueAdditionalPropertyappend)filename	image_uriversion_urica_messagesfilevexr    r!   r   r   generic_uriproductid_to_product_proto_mapproduct_infoartifact_urir%   r&   product_protonotesvulnstatusnoteidnotes                         4lib/googlecloudsdk/command_lib/artifacts/vex_util.pyParseVexFilerO   8   s;    &&':DA+	H	IIdOc 
 C.	$)WWZ ([)I]]6"d--,i##" $ )
  +	+#% .)*5l'L|,LL 9%G&J%%k2K''V_ ( M
 2?":. 6 %#$d'(-.v6*044Z@?
 &'9h
 $$V,&//::MM$ N  	
 	T 7 ) %" 
	q 
		 

.
.& s!   F3 F&F3 &F0+F3 3Gc                 f   | j                  d      }|t        j                  d      |j                  d      }|t        j                  d      t        |      dk  rt        j                  d      |D ]\  }|j                  d      }|t        j                  d	      t        |j	                  d
            dk  sIt        j                  d       | j                  d      }|t        j                  d      t        |      dk  rt        j                  d       |D ]  }t        |        y)zValidates vex file has all needed fields.

  Args:
    vex: json representing a vex document

  Raises:
    ar_exceptions.InvalidInputValueError if user input is invalid.
  r#   Nz)product_tree is required in csaf documentr$   z6branches are required in product tree in csaf document   z@at least one branch is expected in product tree in csaf documentr    z1name is required in product tree in csaf document/   zWname of product should be artifact path, showing repository, project, and package/imager)   z-vulnerabilities are required in csaf documentz7at least one vulnerability is expected in csaf document)r4   r1   r2   lensplitr
   warning_ValidateVulnerability)rC   r#   r$   r%   r    r)   rJ   s          rN   r3   r3      s?    (,

.
.3  j)(

.
.@  	]Q

.
.J  g;;vD|00
=  4::c?a00(   GG-./

.
.7  	AKKIJd4      c                    | j                  d      }|t        j                  d      | j                  d      }|t        j                  d      t        |      dk  rt        j                  d      |D ]3  }|t        vst        j                  dj                  |t                     | j                  d	      }|I|D ]D  }|j                  d
      }|t        vst        j                  dj                  |t                     | j                  d      }|J|D ]D  }|j                  d      }	|	t        vst        j                  dj                  |	t                     yy)zValidates vulnerability is structured correctly.

  Args:
    vuln: a vulnerability from vex document

  Raises:
    ar_exceptions.InvalidInputValueError if user input is invalid.
  cveNz7cve is required in all vulnerabilities in csaf documentr*   zBproduct_status is required in all vulnerabilities in csaf documentrQ   z5at least one status is expected in each vulnerabilityzHInvalid product status passed in {}.  Product status should be one of {}flagslabelz;Invalid flag label passed in {}.  Label should be one of {}remediationscategoryzEInvalid remediation category passed in {}.  Label should be one of {})r4   r1   r2   rT   POSSIBLE_PRODUCT_STATUSr7   POSSIBLE_JUSTIFICATION_FLAGSPOSSIBLE_REMEDIATION_CATEGORIES)
rJ   cve_namer*   rK   r[   flagr\   r]   remediationr^   s
             rN   rW   rW      st    XXe_(

.
.A  88,-.

.
.L  	1

.
.?  f,,006&"9:   ((7
%
hhwe	2	222IVE78
 	
  .),#,h	8	822VH&EF
 	
 $ rX   c                 J   d}g }d}d}	| j                  d      }
|
|
D ]  }|d   dk(  s|} |dk(  r.|j                  j                  j                  }t	        | ||      }n~|dk(  r.|j                  j                  j
                  }t        | ||      }	nK|dk(  r!|j                  j                  j                  }n%|dk(  r |j                  j                  j                  }|j                  |j                  |d	   |||j                  | d
   ||d	   nd||d   nd|||	                  }|j                  j                  j                  |j                  j                  j                  z   }t!        j"                  |j%                               }|j'                         }||fS )a  Makes a note.

  Args:
    vuln: vulnerability proto
    status: string of status of vulnerability
    product: product proto
    publisher: publisher proto.
    document: document proto.
    msgs: container analysis messages

  Returns:
    noteid, and note
  NrI   r^   descriptionr   r   r   r   titlerZ   text)vulnerabilityIdshortDescriptionlongDescriptionstater]   justification)rg   r   r%   
assessment)vulnerabilityAssessment)r4   
AssessmentStateValueValuesEnumAFFECTED_GetRemediationsNOT_AFFECTED_GetJustificationsFIXEDUNDER_INVESTIGATIONNoteVulnerabilityAssessmentNotero   r%   r(   rn   ri   hashlibmd5encode	hexdigest)rJ   rK   r%   r   r   msgsrl   r]   	desc_noterm   rI   rM   r+   resultrL   s                  rN   r9   r9      s    %,)-
((7
%
	j	]	*	  OO0099E#D'48L%%OO00==E&tWd;MOO0066E&&OO00DDE	">>!__"5k&  )1& (/') % 	 ?  
 
$( ""**55$$//??@  ;;szz|$&&	rX   c                 8   g }| j                  d      }||S |D ]}  }|d   }|d   }|j                  j                  j                  |j	                               }|d   D ]6  }	|	|j
                  k(  s|j                  ||      }|j                  |       8  |S )zGet remediations.

  Args:
    vuln: vulnerability proto
    product: product proto
    msgs: container analysis messages

  Returns:
    remediations proto
  r]   r^   detailsproduct_ids)remediationTyper   )r4   RemediationRemediationTypeValueValuesEnumlookup_by_nameupperr'   r=   )
rJ   r%   r~   r]   vuln_remediationsrd   remediation_typeremediation_detailremediation_enumr&   s
             rN   rs   rs   !  s     ,hh~.&k":.$Y/77FF""$	
 
 "-0
	wzz	!&&,6H ' 
 	K( 1 ' 
rX   c                    d}| j                  d      }||j                         S |D ];  }|j                  d      }|j                  d      D ]  }||j                  k(  s|} = |j                  j                  j	                         }||j                            }	|j                  j                  |	      }
|j                  |
      }|S )zGet justifications.

  Args:
    vuln: vulnerability proto
    product: product proto
    msgs: container analysis messages

  Returns:
    justification proto
  justification_type_unspecifiedr[   r\   r   )justificationType)r4   Justificationr'    JustificationTypeValueValuesEnumto_dictr   )rJ   r%   r~   justification_type_as_stringr[   rc   r\   r&   	enum_dictnumberjustification_typerm   s               rN   ru   ru   A  s     "B
((7
%
]dHHWEhh}-
	wzz	!',$ .  99AAC  1779:&
99&A  $$* % - 
rX   c                    ddddd}d}d}d}t        j                  t        j                  |       }|r6||j	                  d         }|j	                  d      }|j	                  d      }t        j                  t        j
                  |       }|rG||j	                  d         }|j	                  d      j                  d	d
d      }|j	                  d      }|r|r|st        j                  d      t        j                  t        |      }|r|| dfS 	 t        j                  |       }t        t        |      |?         }||t!        |      fS # t        j                  $ r}t        j                  d      |d}~ww xY w)zParse GCR URL.

  Args:
    url: gcr url for version, tag or whole image

  Returns:
    strings of project, image url and version url

  Raises:
    ar_exceptions.InvalidInputValueError: If user input is invalid.
  useuropeasia)z	us.gcr.iozgcr.ioz	eu.gcr.iozasia.gcr.ioNrepoprojectimagerR   :rQ   zFailed to parse the GCR image.z)Failed to resolve digest of the GCR image)rematchr	   GCR_DOCKER_REPO_REGEXgroup#GCR_DOCKER_DOMAIN_SCOPED_REPO_REGEXreplacer1   r2   WHOLE_IMAGE_REGEXgcr_utilGetDigestFromNameInvalidImageNameErrorsupertype__str__str)	urllocation_maplocationr   r   matchesdocker_digeste	image_urls	            rN   ParseGCRUrlr   b  su    	, ('
%HH[66<'GMM&12HmmI&GMM'"EHH[DDcJ'GMM&12HmmI&..sC;GMM'"E	

.
.(  HH&.'C..s3M
 D'?A)	)S/	// 
	'	' 

.
.3s   E E<!E77E<c                 H    d}| j                  |      r| t        |      d  S | S )Nzhttps://)
startswithrT   )uriprefixs     rN   r6   r6     s)    &^^Fs6{|	*rX   )"__doc__
__future__r   r   r   rz   r.   r    googlecloudsdk.api_lib.artifactsr   r1   'googlecloudsdk.api_lib.container.imagesr   r   googlecloudsdk.api_lib.utilr   $googlecloudsdk.command_lib.artifactsr	   googlecloudsdk.corer
   googlecloudsdk.core.util.filesr   r`   r_   ra   r   rO   r3   rW   r9   rs   ru   r   r6    rX   rN   <module>r      s~    6 &  '   	 H D , < # 5  2 
#  " JZ+!\.
b:z@B.0brX   