Beispiel #1
0
    def test_get_analysis_by_id_raises_when_analysis_is_queued(self):
        # Arrange
        analysis_id = 'analysis_id'

        with responses.RequestsMock() as mock:
            mock.add('GET',
                     url='{}/analyses/{}'.format(self.full_url, analysis_id),
                     status=202,
                     json={'status': AnalysisStatusCode.QUEUED.value})

            # Act
            with self.assertRaises(errors.AnalysisIsStillRunningError):
                FileAnalysis.from_analysis_id(analysis_id)
Beispiel #2
0
def get_analysis_sub_analyses_command(intezer_api: IntezerApi,
                                      args: dict) -> CommandResults:
    analysis_id = args.get('analysis_id')

    try:
        analysis = FileAnalysis.from_analysis_id(analysis_id, api=intezer_api)
        if not analysis:
            return _get_missing_analysis_result(analysis_id=str(analysis_id))
    except AnalysisIsStillRunning:
        return _get_analysis_running_result(analysis_id=str(analysis_id))

    sub_analyses: List[SubAnalysis] = analysis.get_sub_analyses()

    all_sub_analyses_ids = [sub.analysis_id for sub in sub_analyses]
    sub_analyses_table = tableToMarkdown('Sub Analyses',
                                         all_sub_analyses_ids,
                                         headers=['Analysis IDs'])

    context_json = {
        'ID': analysis.analysis_id,
        'SubAnalysesIDs': all_sub_analyses_ids
    }

    return CommandResults(outputs_prefix='Intezer.Analysis',
                          outputs_key_field='ID',
                          readable_output=sub_analyses_table,
                          outputs=context_json,
                          raw_response=all_sub_analyses_ids)
Beispiel #3
0
def check_analysis_status_and_get_results_command(
        intezer_api: IntezerApi, args: dict) -> List[CommandResults]:
    analysis_type = args.get('analysis_type', 'File')
    analysis_ids = argToList(args.get('analysis_id'))
    indicator_name = args.get('indicator_name')

    command_results = []

    for analysis_id in analysis_ids:
        try:
            if analysis_type == 'Endpoint':
                response = intezer_api.get_url_result(
                    f'/endpoint-analyses/{analysis_id}')
                analysis_result = response.json()['result']
            elif analysis_type == 'Url':
                analysis = UrlAnalysis.from_analysis_id(analysis_id,
                                                        api=intezer_api)
                if not analysis:
                    command_results.append(
                        _get_missing_url_result(analysis_id))
                    continue
                else:
                    analysis_result = analysis.result()
            else:
                analysis = FileAnalysis.from_analysis_id(analysis_id,
                                                         api=intezer_api)
                if not analysis:
                    command_results.append(
                        _get_missing_analysis_result(analysis_id))
                    continue
                else:
                    analysis_result = analysis.result()

            if analysis_result and analysis_type == 'Endpoint':
                command_results.append(
                    enrich_dbot_and_display_endpoint_analysis_results(
                        analysis_result, indicator_name))
            elif analysis_result and analysis_type == 'Url':
                command_results.append(
                    enrich_dbot_and_display_url_analysis_results(
                        analysis_result, intezer_api))
            elif analysis_result:
                command_results.append(
                    enrich_dbot_and_display_file_analysis_results(
                        analysis_result))

        except HTTPError as http_error:
            if http_error.response.status_code == HTTPStatus.CONFLICT:
                command_results.append(
                    _get_analysis_running_result(analysis_id=analysis_id))
            elif http_error.response.status_code == HTTPStatus.NOT_FOUND:
                command_results.append(
                    _get_missing_analysis_result(analysis_id))
            else:
                raise http_error
        except AnalysisIsStillRunning:
            command_results.append(
                _get_analysis_running_result(analysis_id=analysis_id))

    return command_results
Beispiel #4
0
def get_analysis_iocs_command(intezer_api: IntezerApi,
                              args: dict) -> CommandResults:
    analysis_id = args.get('analysis_id')

    try:
        analysis = FileAnalysis.from_analysis_id(analysis_id, api=intezer_api)
    except HTTPError as error:
        if error.response.status_code == HTTPStatus.CONFLICT:
            return _get_analysis_running_result(analysis_id=str(analysis_id))
        raise

    if not analysis:
        return _get_missing_analysis_result(analysis_id=str(analysis_id))

    iocs = analysis.iocs
    readable_output = ''
    if iocs:
        if network_iocs := iocs.get('network'):
            readable_output += tableToMarkdown('Network IOCs', network_iocs)
        if files_iocs := iocs.get('files'):
            readable_output += tableToMarkdown('Files IOCs', files_iocs)
Beispiel #5
0
    def test_get_analysis_by_id_analysis_object_when_latest_analysis_found(
            self):
        # Arrange
        analysis_id = 'analysis_id'
        analysis_report = {'analysis_id': analysis_id, 'sha256': 'hash'}

        with responses.RequestsMock() as mock:
            mock.add('GET',
                     url='{}/analyses/{}'.format(self.full_url, analysis_id),
                     status=200,
                     json={
                         'result': analysis_report,
                         'status': 'succeeded'
                     })

            # Act
            analysis = FileAnalysis.from_analysis_id(analysis_id)

        self.assertIsNotNone(analysis)
        self.assertEqual(analysis_id, analysis.analysis_id)
        self.assertEqual(consts.AnalysisStatusCode.FINISH, analysis.status)
        self.assertDictEqual(analysis_report, analysis.result())
Beispiel #6
0
def enrich_dbot_and_display_url_analysis_results(intezer_result, intezer_api):
    summary = intezer_result.pop('summary')
    _refine_gene_counts(summary)

    intezer_result.update(summary)
    verdict = summary['verdict_type']
    submitted_url = intezer_result['submitted_url']
    analysis_id = intezer_result['analysis_id']

    dbot = {
        'Vendor': 'Intezer',
        'Type': 'Url',
        'Indicator': submitted_url,
        'Score': dbot_score_by_verdict.get(verdict, 0)
    }

    url = {
        'URL': submitted_url,
        'Metadata': intezer_result,
        'ExistsInIntezer': True
    }

    if verdict == 'malicious':
        url['Malicious'] = {'Vendor': 'Intezer'}

    if 'redirect_chain' in intezer_result:
        redirect_chain = ' → '.join(
            f'{node["response_status"]}: {node["url"]}'
            for node in intezer_result['redirect_chain'])
        intezer_result['redirect_chain'] = redirect_chain

    if 'indicators' in intezer_result:
        indicators: Dict[str, List[str]] = defaultdict(list)
        for indicator in intezer_result['indicators']:
            indicators[indicator['classification']].append(indicator['text'])
        indicators_text = [
            get_indicator_text('malicious', indicators),
            get_indicator_text('suspicious', indicators),
            get_indicator_text('informative', indicators),
        ]

        intezer_result['indicators'] = '\n'.join(
            indicator_text for indicator_text in indicators_text
            if indicator_text)

    presentable_result = '## Intezer Url analysis result\n'
    presentable_result += f' Url: {submitted_url}\n'
    presentable_result += f' Verdict: **{verdict}** ({summary["verdict_name"]})\n'
    presentable_result += f'[Analysis Link]({intezer_result["analysis_url"]})\n'

    downloaded_file_presentable_result = ''
    if 'downloaded_file' in intezer_result:
        downloaded_file = intezer_result.pop('downloaded_file')
        presentable_result += f'Downloaded file SHA256: {downloaded_file["sha256"]}\n'
        presentable_result += f'Downloaded file Verdict: **{downloaded_file["analysis_summary"]["verdict_type"]}**\n'
        downloaded_file_analysis = FileAnalysis.from_analysis_id(
            downloaded_file['analysis_id'], intezer_api)
        intezer_result['downloaded_file'] = downloaded_file_analysis.result()
        downloaded_file_presentable_result = _file_analysis_presentable_code(
            downloaded_file_analysis.result())

    md = tableToMarkdown('Analysis Report',
                         intezer_result,
                         url_keys=['analysis_url'])
    presentable_result += md + downloaded_file_presentable_result

    return CommandResults(readable_output=presentable_result,
                          raw_response=intezer_result,
                          outputs={
                              outputPaths['dbotscore']: dbot,
                              outputPaths['url']: url,
                              'Intezer.Analysis(val.ID && val.ID == obj.ID)': {
                                  'ID': analysis_id,
                                  'Status': 'Done'
                              }
                          })