Code Monkey home page Code Monkey logo

sca-cleanup-tool's Introduction

Logo
License Mend projects cleanup Python 3.6 PyPI

Mend SCA Projects Cleanup CLI Tool

Warning

The following project was created for, and should be used with the Legacy Mend User Interface. The Mend Unified Platform and Cloud Native creates empty projects on the Legacy Mend User Interface to store SAST and Cloud Native scans. Removing those projects could result in broken scans and information not being published to Mend correctly. If you are using Cloud Native or the Mend Unified Platform - It is recommended to run this tool in Dry Run mode and verify the projects to be deleted do not have SAST or Cloud Native scans prior to deletion.

  • The self-hosted CLI tool features cleaning up projects and generating reports before deletion in 2 modes:
    • By stating OperationMode=FilterProjectsByUpdateTime and how many days to keep (-r/ DaysToKeep=)
    • By stating OperationMode=FilterProjectsByLastCreatedCopies and how many copies to keep (-r/ DaysToKeep=)
  • The reports are saved in the designated location as follows: [Output_DIR]/[PRODUCT NAME]/[PROJECT NAME]/[REPORT NAME]
    • The default location is the [WORKING DIRECTORY]/Mend/Reports/[PRODUCT NAME]/[PROJECT NAME]/[REPORT NAME]
  • To review the outcome before actual deletion use -y true / DryRun=True flag. It will NOT delete any project nor create reports
  • By default, the tool generates all possible project-level reports. By specifying ((-t / Reports=/) it is possible to select specific reports
    • The full list of available reports is below
  • The full parameters list is available below
  • There are two ways to configure the tool:
    • By configuring params.config on the executed dir or passing a path to the file in the same format
    • By setting command line parameters as specified in the usage below

Supported Operating Systems

  • Linux (Bash): CentOS, Debian, Ubuntu, RedHat
  • Windows (PowerShell): 10, 2012, 2016

Pre-requisites

  • Python 3.8+

Permissions

  • The user used to execute the tool has to have "Organization Administrator" or "Product Administrator" on all the maintained products and "Organization Auditor" permissions.
  • It is recommended to use a service user.

Installation and Execution from PyPi (recommended):

  1. Install by executing: pip install mend-sca-cleanup-tool
  2. Configure the appropriate parameters either by using the command line or in params.config.
  3. Execute the tool (mend_sca_cleanup_tool ...).
  4. In order to update the tool please run pip install mend-sca-cleanup-tool --upgrade

Installation and Execution from GitHub:

  1. Download and unzip mend-sca-cleanup-tool.zip from the most recent tagged release.
  2. Install requirements: pip install -r requirements.txt
  3. Configure the appropriate parameters either by using the command line or params.config.
  4. Execute: python sca_cleanup_tool.py <CONFIG_FILE>

Examples:

Perform dry run check-in to get to know which projects would have been deleted:
mend_sca_cleanup_tool -r 30 -m FilterProjectsByUpdateTime -u <USER_KEY> -k <ORG_TOKEN> -y true


Keep the last 60 days on each product, omitting a product token <PRODUCT_1> from analyzing:
mend_sca_cleanup_tool -r 60 -m FilterProjectsByUpdateTime -u <USER_KEY> -k <ORG_TOKEN> -e <PRODUCT_TOKEN_1>


Keep only two of the newest projects in each product token PRODUCT_1 and PRODUCT_2:
mend_sca_cleanup_tool -r 2 -m FilterProjectsByLastCreatedCopies -u <USER_KEY> -k <ORG_TOKEN> -i <PRODUCT_TOKEN_1>,<PRODUCT_TOKEN_2>


Analyze only the projects that have the specified Mend tag and keep the newest project in each product:
mend_sca_cleanup_tool -r 1 -m FilterProjectsByLastCreatedCopies -u <USER_KEY> -k <ORG_TOKEN> -g <KEY>:<VALUE>


Keep the last 2 weeks and analyze only the projects whose match their tag key and the tag value contains the specified value:
mend_sca_cleanup_tool -r 14 -m FilterProjectsByUpdateTime -u <USER_KEY> -k <ORG_TOKEN> -v <KEY>:<VALUE>


Keep the last 100 days for both PRODUCT_1 and PRODUCT_2, but do not delete the project PROJECT_1 (which is a project in one of the included products):
mend_sca_cleanup_tool -r 100 -m FilterProjectsByUpdateTime -u <USER_KEY> -k <ORG_TOKEN> -i <PRODUCT_TOKEN_1>,<PRODUCT_TOKEN_2> -x <PROJECT_TOKEN_1>


Keep the last month for both PRODUCT_1 and PRODUCT_2, but do not delete projects that contain provided strings in their names:
mend_sca_cleanup_tool -r 31 -m FilterProjectsByUpdateTime -u <USER_KEY> -k <ORG_TOKEN> -i <PRODUCT_TOKEN_1>,<PRODUCT_TOKEN_2> -n CI_,-test


Full Usage flags:

usage: mend_sca_cleanup_tool [-h] -u MEND_USER_KEY -k MEND_TOKEN [-a MEND_URL] [-t REPORT_TYPES] [-m {FilterProjectsByUpdateTime,FilterProjectsByLastCreatedCopies}] [-o OUTPUT_DIR] [-e EXCLUDED_PRODUCT_TOKENS] [-i INCLUDED_PRODUCT_TOKENS]
                    [-g ANALYZED_PROJECT_TAG] [-r DAYS_TO_KEEP] [-p PROJECT_PARALLELISM_LEVEL] [-y DRY_RUN] [-pr ProxyUrl]

Mend Cleanup Tool

optional arguments:
  -h, --help            show this help message and exit
  -u MEND_USER_KEY, --userKey 
                    Mend User Key
  -k MEND_API_TOKEN, --apiToken, --orgToken
                    Mend Organization Key (API Key)
  -a MEND_URL, --mendUrl, --wsURL
                    Mend URL. This value defaults to saas.whitesourcesoftware.com.
  -t REPORT_TYPES, --reportTypes
                    Report Types to generate (comma seperated list)
  -m OPERATION_MODE, --operationMode {FilterProjectsByUpdateTime,FilterProjectsByLastCreatedCopies}
                    Cleanup operation mode
  -o OUTPUT_DIR, --outputDir
                    Output directory
  -e EXCLUDED_PRODUCT_TOKENS, --excludedProductTokens
                    List of excluded products
  -i INCLUDED_PRODUCT_TOKENS, --includedProductTokens
                    List of included products
  -g ANALYZED_PROJECT_TAG, --AnalyzedProjectTag
                    Analyze only the projects whose contain the specific Mend tag (key:value). Case sensitive.
  -v ANALYZED_PROJECT_TAG_REGEX_IN_VALUE, --AnalyzedProjectTagRegexInValue
                    Analyze only the projects whose match their tag key and the tag value contains the specified value (key:value). Case sensitive.
                    Note: This was originally broken in the original ws-cleanup-tool. The functionality was adjusted to work as originally written. The naming convention is a misnomer but was kept to avoid breaking existing integrations.
  -r DAYS_TO_KEEP, --DaysToKeep
                    Number of days to keep in FilterProjectsByUpdateTime or number of copies in FilterProjectsByLastCreatedCopies
  -p PROJECT_PARALLELISM_LEVEL, --ProjectParallelismLevel
                    Project parallelism level
                    Note: This is currently not used in this version of the mend-sca-cleanup-tool. Was kept to prevent breaking existing integrations.
  -y DRY_RUN, --DryRun
                    Logging the projects that are supposed to be deleted without deleting and creating reports
                    default False
  -s SKIP_REPORT_GENERATION, --SkipReportGeneration
                    Skip report generation step
                    default False
  -j SKIP_PROJECT_DELETION, --SkipProjectDeletion
                    Skip project deletion step
                    default False                                        
  -x EXCLUDED_PROJECT_TOKENS, --excludedProjectTokens
                    List of excluded projects
  -n EXCLUDED_PROJECT_NAME_PATTERNS, --excludedProjectNamePatterns
                    List of excluded project name patterns (comma seperated list). Case sensitive.    
  -pr ProxyUrl, --proxy
                    The proxy URL. It should be provided in a format like this: < proxy_ip>:<proxy_port>.
                    In case of a proxy requires Basic Authentication 
                    the format should be like this <proxy_username>:<proxy_password>@<proxy_ip>:<proxy_port>.
                    If http:// or https:// prefix is not provided, the prefix http:// will be used by default.
                          

Available reports

The following Mend project reports are available through the clean-up tool. These values can be specified with the -t flag to generate specific reports.

  • alerts
  • alerts_rejected_by_policy
  • attribution
  • bugs
  • due_diligence
  • ignored_alerts
  • in_house_libraries
  • inventory
  • license_compatibility
  • resolved_alerts
  • request_history
  • source_files
  • source_file_inventory
  • vulnerability

SAST Clean up

If you need to run a clean up script for your SAST environment, please refer to the Mend SAST clean up kit in the Mend Toolkit

note: The optimal cleanup scope is derived from the size of the environment, Mend scope size (memory and CPU) allocated for the server, and runtime time constraints.

sca-cleanup-tool's People

Contributors

beccccaboo avatar clindseyws avatar dimarrws avatar jrmenddemo avatar kyallanum-mnd avatar mend-for-github-com[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar

Forkers

ahahu beccccaboo

sca-cleanup-tool's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Pending Approval

These branches will be created by Renovate only once you click their checkbox below.

  • [LOW] Update dependency setuptools to v70
  • [NEUTRAL] Update dependency configparser to v7
  • ๐Ÿ” Create all pending approval PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/Test and Deploy Mend.yml
  • actions/checkout v2
  • actions/setup-python v2
  • actions/cache v3
  • actions/cache v3
  • actions/cache v3
  • actions/cache v3
  • actions/checkout v2
  • ncipollo/release-action v1
pip_requirements
requirements.txt
  • configparser ==5.3.0
  • DateTime ~=4.3
  • setuptools ==68.2.2
  • requests ~=2.31.0

Action Required: Fix Mend Configuration File - .whitesource

There is an error with this repository's Mend configuration file that needs to be fixed. As a precaution, scans will stop until it is resolved.

Errors:

  • "settingsInheritedFrom" attribute provided in mend-toolkit/sca-cleanup-tool/.whitesource points to a non-existent repository or branch: 'whitesource-ps/whitesource-config@main'

requests-2.31.0-py3-none-any.whl: 1 vulnerabilities (highest severity is: 5.6)

Vulnerable Library - requests-2.31.0-py3-none-any.whl

Python HTTP for Humans.

Library home page: https://files.pythonhosted.org/packages/70/8e/0e2d847013cb52cd35b38c009bb167a1a26b2ce6cd6965bf26b47bc0bf44/requests-2.31.0-py3-none-any.whl

Path to dependency file: /tmp/ws-scm/sca-cleanup-tool

Path to vulnerable library: /tmp/ws-scm/sca-cleanup-tool,/requirements.txt

Vulnerabilities

CVE Severity CVSS Dependency Type Fixed in (requests version) Remediation Possible**
CVE-2024-35195 Medium 5.6 requests-2.31.0-py3-none-any.whl Direct requests - 2.32.2 โœ…

**In some cases, Remediation PR cannot be created automatically for a vulnerability despite the availability of remediation

Details

CVE-2024-35195

Vulnerable Library - requests-2.31.0-py3-none-any.whl

Python HTTP for Humans.

Library home page: https://files.pythonhosted.org/packages/70/8e/0e2d847013cb52cd35b38c009bb167a1a26b2ce6cd6965bf26b47bc0bf44/requests-2.31.0-py3-none-any.whl

Path to dependency file: /tmp/ws-scm/sca-cleanup-tool

Path to vulnerable library: /tmp/ws-scm/sca-cleanup-tool,/requirements.txt

Dependency Hierarchy:

  • โŒ requests-2.31.0-py3-none-any.whl (Vulnerable Library)

Found in base branch: main

Vulnerability Details

Requests is a HTTP library. Prior to 2.32.2, when making requests through a Requests Session, if the first request is made with verify=False to disable cert verification, all subsequent requests to the same host will continue to ignore cert verification regardless of changes to the value of verify. This behavior will continue for the lifecycle of the connection in the connection pool. This vulnerability is fixed in 2.32.2.

Publish Date: 2024-05-20

URL: CVE-2024-35195

CVSS 3 Score Details (5.6)

Base Score Metrics:

  • Exploitability Metrics:
    • Attack Vector: Local
    • Attack Complexity: High
    • Privileges Required: High
    • User Interaction: Required
    • Scope: Unchanged
  • Impact Metrics:
    • Confidentiality Impact: High
    • Integrity Impact: High
    • Availability Impact: None

For more information on CVSS3 Scores, click here.

Suggested Fix

Type: Upgrade version

Origin: GHSA-9wx4-h78v-vm56

Release Date: 2024-05-20

Fix Resolution: requests - 2.32.2

In order to enable automatic remediation, please create workflow rules


In order to enable automatic remediation for this issue, please create workflow rules

urllib3-2.1.0-py3-none-any.whl: 1 vulnerabilities (highest severity is: 4.4)

Vulnerable Library - urllib3-2.1.0-py3-none-any.whl

HTTP library with thread-safe connection pooling, file post, and more.

Library home page: https://files.pythonhosted.org/packages/96/94/c31f58c7a7f470d5665935262ebd7455c7e4c7782eb525658d3dbf4b9403/urllib3-2.1.0-py3-none-any.whl

Path to dependency file: /requirements.txt

Path to vulnerable library: /requirements.txt,/tmp/ws-scm/sca-cleanup-tool

Vulnerabilities

CVE Severity CVSS Dependency Type Fixed in (urllib3 version) Remediation Possible**
CVE-2024-37891 Medium 4.4 urllib3-2.1.0-py3-none-any.whl Direct 2.2.2 โœ…

**In some cases, Remediation PR cannot be created automatically for a vulnerability despite the availability of remediation

Details

CVE-2024-37891

Vulnerable Library - urllib3-2.1.0-py3-none-any.whl

HTTP library with thread-safe connection pooling, file post, and more.

Library home page: https://files.pythonhosted.org/packages/96/94/c31f58c7a7f470d5665935262ebd7455c7e4c7782eb525658d3dbf4b9403/urllib3-2.1.0-py3-none-any.whl

Path to dependency file: /requirements.txt

Path to vulnerable library: /requirements.txt,/tmp/ws-scm/sca-cleanup-tool

Dependency Hierarchy:

  • โŒ urllib3-2.1.0-py3-none-any.whl (Vulnerable Library)

Found in base branch: main

Vulnerability Details

urllib3 is a user-friendly HTTP client library for Python. When using urllib3's proxy support with ProxyManager, the Proxy-Authorization header is only sent to the configured proxy, as expected. However, when sending HTTP requests without using urllib3's proxy support, it's possible to accidentally configure the Proxy-Authorization header even though it won't have any effect as the request is not using a forwarding proxy or a tunneling proxy. In those cases, urllib3 doesn't treat the Proxy-Authorization HTTP header as one carrying authentication material and thus doesn't strip the header on cross-origin redirects. Because this is a highly unlikely scenario, we believe the severity of this vulnerability is low for almost all users. Out of an abundance of caution urllib3 will automatically strip the Proxy-Authorization header during cross-origin redirects to avoid the small chance that users are doing this on accident. Users should use urllib3's proxy support or disable automatic redirects to achieve safe processing of the Proxy-Authorization header, but we still decided to strip the header by default in order to further protect users who aren't using the correct approach. We believe the number of usages affected by this advisory is low. It requires all of the following to be true to be exploited: 1. Setting the Proxy-Authorization header without using urllib3's built-in proxy support. 2. Not disabling HTTP redirects. 3. Either not using an HTTPS origin server or for the proxy or target origin to redirect to a malicious origin. Users are advised to update to either version 1.26.19 or version 2.2.2. Users unable to upgrade may use the Proxy-Authorization header with urllib3's ProxyManager, disable HTTP redirects using redirects=False when sending requests, or not user the Proxy-Authorization header as mitigations.

Publish Date: 2024-06-17

URL: CVE-2024-37891

CVSS 3 Score Details (4.4)

Base Score Metrics:

  • Exploitability Metrics:
    • Attack Vector: Network
    • Attack Complexity: High
    • Privileges Required: High
    • User Interaction: None
    • Scope: Unchanged
  • Impact Metrics:
    • Confidentiality Impact: High
    • Integrity Impact: None
    • Availability Impact: None

For more information on CVSS3 Scores, click here.

Suggested Fix

Type: Upgrade version

Origin: GHSA-34jh-p97f-mpxf

Release Date: 2024-06-17

Fix Resolution: 2.2.2

In order to enable automatic remediation, please create workflow rules


In order to enable automatic remediation for this issue, please create workflow rules

FILTER_PROJECTS_BY_LAST_CREATED_COPIES removes projects even when there is nothing to filter.

Bug Description
When the number of projects to filter is less than or equal to the DAYS_TO_KEEP parameter, all the projects are deleted.

Steps to Reproduce

mend_sca_cleanup_tool -r 2 -m FilterProjectsByLastCreatedCopies -u <User_ID> -k <Org_ID> -y true -i <Product_Token> -g <Tag_Key>:<Tag_Value>

Expected Behavior
The command should keep the latest 2 projects that match the tag <Tag_Key>:<Tag_Value> in the given product and delete the older ones. It works when there are more than 2 projects that match this condition. However, if the number of projects are 1 or 2, it deletes those projects.

Screenshots

  1. Bug (-daysToKeep=2)
Getting tags for project <project_1>
<project_1> has matching tag
Getting tags for project <project_2>
<project_2> has matching tag
Filtering projects besides most recent: 2
Total: 2. Nothing to filter
2 project(s) to remove after filtering
Dry Run found 2 project(s) to delete: [โ€˜<project_1>โ€™, โ€˜<project_2>โ€™]
  1. Working condition when projects>day_to_keep (-daysToKeep=1)
Getting tags for project <project_1>
<project_1> has matching tag
Getting tags for project <project_2>
<project_2> has matching tag
Filtering projects besides most recent: 1
Total: 2. Removing oldest 1
1 project(s) to remove after filtering
Dry Run found 1 project(s) to delete: [โ€˜<project_1>โ€™]

Possible Solution
Line 159 in sca_cleanup_tool.py can set projects_to_return=[ ] so that an empty array is returned when projects<days_to_keep

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.