### Install NVDLib using pip Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md Installs the NVDLib Python package and its dependencies, such as the requests library. This command is run in the console within a Python virtual environment. ```console (.venv) $ pip install nvdlib ``` -------------------------------- ### Configure Logging for nvdlib Source: https://github.com/vehemont/nvdlib/blob/main/HISTORY.md Demonstrates how to configure the Python logging module to capture logs from nvdlib and the Requests library. This setup directs debug-level logs, including HTTP requests and syntax/server errors, to a file named 'example_NVDLib.log'. ```python import logging import nvdlib logging.basicConfig(filename='example_NVDLib.log', encoding='utf-8', level=logging.DEBUG) r = nvdlib.searchCVE(keywordSearch="Microsoft") ``` -------------------------------- ### Search CVE with Datetime Objects in Python Source: https://github.com/vehemont/nvdlib/blob/main/HISTORY.md Demonstrates how to use datetime objects for publication start and end dates when searching for CVEs using the NVDLib library. It also shows how to enable verbose output to inspect the generated API request URL. ```python >>> import nvdlib >>> import datetime >>> end = datetime.datetime.now() >>> start = end - datetime.timedelta(days=7) >>> r = nvdlib.searchCVE(pubStartDate=start, pubEndDate=end, verbose=True) Filter: https://services.nvd.nist.gov/rest/json/cves/1.0?pubStartDate=2022-02-08T08:57:26:000 UTC-00:00&pubEndDate=2022-02-15T08:57:26:000 UTC-00:00 >>> len(r) 629 ``` -------------------------------- ### Search CVEs by CPE Name, Keyword, and Exact Match Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md This example demonstrates filtering CVEs based on a specific CPE name, a keyword, and enabling exact match for the CPE name. This ensures that only CVEs associated with the precise CPE string and keyword are returned. ```python >>> r = nvdlib.searchCVE(cpeName = 'cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*', keyword = '1ArcServe', exactMatch = True) ``` -------------------------------- ### Search CPE Match Strings and Print Matching CPE Names Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CPEv2.md This example shows how to fetch CPE match strings for a CVE ID and then access the nested 'matches' list to print the 'cpeName' for each CPE that matches. It requires iterating through both the match strings and their individual CPE matches. ```python r = nvdlib.searchCPEmatch(cveId='CVE-2017-0144') for eachMatchString in r: for eachCPE in eachMatchString.matches: print(eachCPE.cpeName) ``` -------------------------------- ### Import NVDLib module in Python Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md Imports the necessary NVDLib module to start using its functionalities within a Python script or interactive session. ```python import nvdlib ``` -------------------------------- ### GET /searchCVE_V2 Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Creates a generator for CVEs, useful for memory-constrained environments. It yields CVE objects one at a time. ```APIDOC ## GET /searchCVE_V2 ### Description Creates a generator that yields CVE objects one at a time. This is useful for searching large datasets where memory constraints are a concern. It uses the same parameters as `searchCVE`. ### Method GET ### Endpoint /searchCVE_V2 ### Parameters #### Query Parameters - **cpeName** (str) - Optional - The CPE name to filter CVEs by. - **keywordSearch** (str) - Optional - A keyword search term to find CVEs. - **v2accessComplexity** (str) - Optional - CVSS v2 Access Complexity (HIGH, MEDIUM, LOW). - **v31privilegesRequired** (str) - Optional - CVSS v3.1 Privileges Required (HIGH, LOW, NONE). - **v30privilegesRequired** (str) - Optional - CVSS v3.0 Privileges Required (HIGH, LOW, NONE). - **v31userInteraction** (str) - Optional - CVSS v3.1 User Interaction (NONE, REQUIRED). - **v30userInteraction** (str) - Optional - CVSS v3.0 User Interaction (NONE, REQUIRED). - **v31scope** (str) - Optional - CVSS v3.1 Scope (UNCHANGED, CHANGED). - **v30scope** (str) - Optional - CVSS v3.0 Scope (UNCHANGED, CHANGED). - **v31confidentialityImpact** (str) - Optional - CVSS v3.1 Confidentiality Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v30confidentialityImpact** (str) - Optional - CVSS v3.0 Confidentiality Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v2confidentialityImpact** (str) - Optional - CVSS v2 Confidentiality Impact (NONE, PARTIAL, COMPLETE). - **v2authentication** (str) - Optional - CVSS v2 Authentication (MULTIPLE, SINGLE, NONE). - **v31integrityImpact** (str) - Optional - CVSS v3.1 Integrity Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v30integrityImpact** (str) - Optional - CVSS v3.0 Integrity Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v2integrityImpact** (str) - Optional - CVSS v2 Integrity Impact (NONE, PARTIAL, COMPLETE). - **v31availabilityImpact** (str) - Optional - CVSS v3.1 Availability Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v30availabilityImpact** (str) - Optional - CVSS v3.0 Availability Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v2availabilityImpact** (str) - Optional - CVSS v2 Availability Impact (NONE, PARTIAL, COMPLETE). - **limit** (int) - Optional - The maximum number of CVEs to return. ### Request Example ```python import nvdlib r = nvdlib.searchCVE_V2(keywordSearch='Microsoft Exchange 2010', limit=100) oneCVE = next(r) print(oneCVE.id) ``` ### Response #### Success Response (200) - **generator** (generator) - A generator that yields CVE objects one at a time. ``` -------------------------------- ### Using Proxy Configuration with nvdlib Source: https://context7.com/vehemont/nvdlib/llms.txt Shows how to configure and use proxy settings for NVDLib searches, essential for environments requiring HTTP/HTTPS proxy connections. This includes setting up proxy dictionaries and passing them to search functions for CVE, CPE, and CPE match queries. The examples require Python, the nvdlib package, and valid proxy server details. The output demonstrates retrieving data through the specified proxy. ```python import nvdlib # Define proxy configuration proxies = { 'http': 'http://proxy.example.com:8080', 'https': 'https://proxy.example.com:8443' } # Use proxy with CVE search cves_with_proxy = nvdlib.searchCVE( keywordSearch='authentication bypass', cvssV3Severity='HIGH', proxies=proxies, key='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', delay=0.6 ) # Use proxy with CPE search cpes_with_proxy = nvdlib.searchCPE( keywordSearch='WordPress', limit=50, proxies=proxies ) # Use proxy with CPE match search matches_with_proxy = nvdlib.searchCPEmatch( cveId='CVE-2023-12345', proxies=proxies ) for cve in cves_with_proxy: print(f"{cve.id}: {cve.v31severity}") ``` -------------------------------- ### Generator-Based CPE Search with V2 API Source: https://context7.com/vehemont/nvdlib/llms.txt This example utilizes the `searchCPE_V2` function for memory-efficient searching of CPEs, particularly useful for large datasets. It demonstrates using a generator to process CPE entries one by one and checking for deprecated CPEs with their replacements. The snippet also shows how to retrieve a single result using `next()`. ```python import nvdlib # Generator-based CPE search cpe_generator = nvdlib.searchCPE_V2( keywordSearch='apache', lastModStartDate='2023-01-01 00:00', lastModEndDate='2023-12-31 23:59' ) # Process CPEs one at a time processed_count = 0 for cpe in cpe_generator: print(f"Processing: {cpe.cpeName}") processed_count += 1 # Check if deprecated and show replacements if cpe.deprecated and hasattr(cpe, 'deprecatedBy'): print(f" Deprecated by: {cpe.deprecatedBy}") print(f"Processed {processed_count} CPE entries") # Get single result with next() first_match = next(nvdlib.searchCPE_V2( cpeMatchString='cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*', limit=1 )) print(f"First match: {first_match.cpeName}") ``` -------------------------------- ### Search CPE Names by Keyword, Match String, and Date Source: https://context7.com/vehemont/nvdlib/llms.txt This example focuses on searching for Common Platform Enumeration (CPE) names. It shows how to perform basic keyword searches, search using a specific CPE match string, and filter CPEs by their last modification date. The snippet also demonstrates how to access and iterate through CPE details, including titles in different languages. ```python import nvdlib import datetime # Basic CPE search by keyword cpes = nvdlib.searchCPE( keywordSearch='Microsoft Exchange', limit=10 ) for cpe in cpes: print(f"CPE Name: {cpe.cpeName}") print(f"CPE ID: {cpe.cpeNameId}") print(f"Deprecated: {cpe.deprecated}") print(f"Created: {cpe.created}") # Access titles (may be in multiple languages) if hasattr(cpe, 'titles'): for title in cpe.titles: print(f" Title ({title.lang}): {title.title}") # Search with CPE match string exchange_cpes = nvdlib.searchCPE( cpeMatchString='cpe:2.3:a:microsoft:exchange_server:2013:*:*:*:*:*:*:*' ) # Search by modification date end = datetime.datetime.now() start = end - datetime.timedelta(days=30) recent_cpes = nvdlib.searchCPE( lastModStartDate=start, lastModEndDate=end, keywordSearch='Linux' ) print(f"Found {len(recent_cpes)} CPE entries modified in last 30 days") ``` -------------------------------- ### Search CPEs with a Match String and API Key (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CPEv2.md Example of searching CPEs using a specific CPE match string, providing an API key, and setting a custom delay. This method is useful for precise searching when a known CPE pattern is available. It returns CPE names that match the provided criteria. ```python r = nvdlib.searchCPE(cpeMatchString='cpe:2.3:a:microsoft:exchange_server:2013:', key='xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxx', delay=6) for eachCPE in r: print(eachCPE.cpeName) ``` -------------------------------- ### Search CPEs and Retrieve Vulnerabilities (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md This example demonstrates how to search for CPEs matching a specific string and retrieve all associated vulnerabilities. It filters for Microsoft Exchange Server 2013, enables CVE retrieval, and then iterates through the results to print each vulnerability. Note that CVEs returned this way only contain the ID and not full details. ```python r = nvdlib.searchCPE(cpeMatchString='cpe:2.3:a:microsoft:exchange_server:2013:', cves=True, key='xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxx') for eachCPE in r: for eachVuln in eachCPE.vulnerabilities: print(eachVuln) ``` -------------------------------- ### Search CVEs and Display Information using NVDLib (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/index.md This Python code snippet demonstrates how to use the NVDLib library to search for a specific CVE and then extract and print various details about it, including severity, score, description, and CVSS vector. It requires the 'nvdlib' library to be installed. ```python import nvdlib r = nvdlib.searchCVE(cveId='CVE-2021-26855')[0] print(r.v31severity + ' - ' + str(r.v31score)) print(r.descriptions[0].value) print(r.v31vector) ``` -------------------------------- ### Search CVEs with Filters using NVDLib Source: https://context7.com/vehemont/nvdlib/llms.txt Demonstrates searching for CVEs using various filters such as keywords, CVSS severity, publication date ranges, and CPE names. It shows how to use both string and datetime objects for date filtering and how to retrieve detailed metrics for each found CVE. The example also includes searching for vulnerabilities with specific CPE names and keywords. ```python import nvdlib import datetime # Search with multiple filters results = nvdlib.searchCVE( keywordSearch='Microsoft Exchange', cvssV3Severity='CRITICAL', pubStartDate='2021-01-01 00:00', pubEndDate='2021-12-31 23:59', limit=50 ) print(f"Found {len(results)} CVEs") for cve in results: print(f"{cve.id}: {cve.score[1]} ({cve.score[2]})") # Search using datetime objects for last 7 days end = datetime.datetime.now() start = end - datetime.timedelta(days=7) recent_cves = nvdlib.searchCVE(pubStartDate=start, pubEndDate=end) # Search with CPE name and keyword cpe_results = nvdlib.searchCVE( cpeName='cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*', keywordSearch='remote code execution', keywordExactMatch=True, isVulnerable=True ) # Access detailed metrics for cve in cpe_results: print(f"CVE: {cve.id}") print(f"Attack Vector: {cve.v31attackVector}") print(f"Attack Complexity: {cve.v31attackComplexity}") print(f"Exploitability Score: {cve.v31exploitability}") print(f"Impact Score: {cve.v31impactScore}") print(f"URL: {cve.url}") ``` -------------------------------- ### Extract CPE Names Matching a CVE with CPE Dictionary Enabled Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md This example demonstrates how to extract CPE names associated with CVEs when the `cpe_dict` option is enabled during the search. It iterates through the configurations and CPE match list of each CVE to print the CPE URIs. ```python r = nvdlib.searchCVE(cpeName = 'cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*', keyword = '1ArcServe', exactMatch = True, cpe_dict = True) for eachCVE in r: config = eachCVE.configurations.nodes for eachNode in config: for eachCpe in eachNode.cpe_match: print(eachCpe.cpe23Uri) ``` -------------------------------- ### Search CVEs with searchCVE_V2 Function (Generator) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Illustrates the usage of `searchCVE_V2`, which returns a generator instead of a list. This is beneficial for large datasets to manage memory usage. The example shows how to retrieve one CVE at a time using the `next()` function after searching by keyword. ```python >>> r = nvdlib.searchCVE_V2(keywordSearch='Microsoft Exchange 2010', limit=100) >>> oneCVE = next(r) >>> print(oneCVE.id) ``` -------------------------------- ### Search CVEs with Publication Dates, Keyword, Severity, and API Key Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md This snippet demonstrates how to search for CVEs within a specified publication date range, filtered by a keyword, critical CVSS v3 severity, and an API key for faster requests. It highlights the requirement for both start and end dates for publication searches and the 120-day range limitation. ```python >>> r = nvdlib.searchCVE(pubStartDate = '2021-09-08 00:00', pubEndDate = '2021-12-01 00:00', keyword = 'Microsoft Exchange', cvssV3Severity = 'Critical', key='xxxxx-xxxxxx-xxxxxxx') ``` -------------------------------- ### GET /searchCVE Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Searches for CVEs using specified criteria and returns a list of matching CVE objects. All parameters are optional and can be mixed in any order. ```APIDOC ## GET /searchCVE ### Description Searches for CVEs based on various criteria and returns a list of CVE objects. The function builds the request based on the provided parameters. If a parameter is not passed, it is assumed to be false and not included in the filter. ### Method GET ### Endpoint /searchCVE ### Parameters #### Query Parameters - **cpeName** (str) - Optional - The CPE name to filter CVEs by. - **keywordSearch** (str) - Optional - A keyword search term to find CVEs. - **v2accessComplexity** (str) - Optional - CVSS v2 Access Complexity (HIGH, MEDIUM, LOW). - **v31privilegesRequired** (str) - Optional - CVSS v3.1 Privileges Required (HIGH, LOW, NONE). - **v30privilegesRequired** (str) - Optional - CVSS v3.0 Privileges Required (HIGH, LOW, NONE). - **v31userInteraction** (str) - Optional - CVSS v3.1 User Interaction (NONE, REQUIRED). - **v30userInteraction** (str) - Optional - CVSS v3.0 User Interaction (NONE, REQUIRED). - **v31scope** (str) - Optional - CVSS v3.1 Scope (UNCHANGED, CHANGED). - **v30scope** (str) - Optional - CVSS v3.0 Scope (UNCHANGED, CHANGED). - **v31confidentialityImpact** (str) - Optional - CVSS v3.1 Confidentiality Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v30confidentialityImpact** (str) - Optional - CVSS v3.0 Confidentiality Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v2confidentialityImpact** (str) - Optional - CVSS v2 Confidentiality Impact (NONE, PARTIAL, COMPLETE). - **v2authentication** (str) - Optional - CVSS v2 Authentication (MULTIPLE, SINGLE, NONE). - **v31integrityImpact** (str) - Optional - CVSS v3.1 Integrity Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v30integrityImpact** (str) - Optional - CVSS v3.0 Integrity Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v2integrityImpact** (str) - Optional - CVSS v2 Integrity Impact (NONE, PARTIAL, COMPLETE). - **v31availabilityImpact** (str) - Optional - CVSS v3.1 Availability Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v30availabilityImpact** (str) - Optional - CVSS v3.0 Availability Impact (LOW, MEDIUM, HIGH, CRITICAL). - **v2availabilityImpact** (str) - Optional - CVSS v2 Availability Impact (NONE, PARTIAL, COMPLETE). - **limit** (int) - Optional - The maximum number of CVEs to return. ### Request Example ```python import nvdlib r = nvdlib.searchCVE(cpeName = 'cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*', limit = 2) for eachCVE in r: print(eachCVE.id) ``` ### Response #### Success Response (200) - **list** (list) - A list containing CVE objects that match the search criteria. ``` -------------------------------- ### Search CVEs with NVDLib using updated parameters Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/changesv1.md Illustrates how to use `nvdlib.searchCVE` with updated parameter names that now precisely match the NVD API documentation. It highlights the change from older arguments like `keyword` to `keywordSearch` and the inclusion of new parameters for more granular searching. The example also shows the updated score format, preferring CVSS v3.1. ```python >>> r = nvdlib.searchCVE(keywordSearch='vulnerability', lastModStartDate='01/01/2023', lastModEndDate='01/31/2023') >>> r[0].score ['V31', 9.8, 'CRITICAL'] ``` -------------------------------- ### Get Recent CVEs using Datetime Object and API Key (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Retrieves all CVEs published within the last 7 days using a datetime object for the date range and an API key. Requires the datetime and nvdlib libraries. Returns a list of CVE objects. ```python >>> import datetime >>> end = datetime.datetime.now() >>> start = end - datetime.timedelta(days=7) >>> r = nvdlib.searchCVE(pubStartDate=start, pubEndDate=end, key='xxxxx-xxxxxx-xxxxxxx') ``` -------------------------------- ### Filter CVEs by CVSS Metrics and Known Exploited Vulnerabilities Source: https://context7.com/vehemont/nvdlib/llms.txt This snippet demonstrates filtering CVEs based on CVSS v3 metrics and searching for CVEs within the Known Exploited Vulnerabilities (KEV) catalog. It shows how to specify CVSS metrics, severity levels, and the `hasKev` parameter. The example also includes iterating through KEV results to print relevant details like the addition date and required action. ```python import nvdlib # Filter by CVSS metrics cvss_filtered = nvdlib.searchCVE( cvssV3Metrics='CVSS:3.1/AV:N/AC:L', key='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', delay=1.0 ) # Search for CVEs in Known Exploited Vulnerabilities catalog kev_cves = nvdlib.searchCVE( hasKev=True, cvssV3Severity='CRITICAL', key='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', delay=0.6 ) for cve in kev_cves: if hasattr(cve, 'exploitAdd'): print(f"{cve.id} added to KEV on {cve.exploitAdd}") print(f"Required action: {cve.requiredAction}") ``` -------------------------------- ### Memory-Efficient CVE Search with Generator in NVDLib Source: https://context7.com/vehemont/nvdlib/llms.txt Utilizes the `searchCVE_V2` function to perform searches using a generator, which is memory-efficient for handling large datasets. It iterates through CVEs one by one, printing their IDs, scores, and severities. The example also shows how to access associated weaknesses (CWE) and CPE match criteria for each CVE. ```python import nvdlib # Generator-based search for memory efficiency cve_generator = nvdlib.searchCVE_V2( keywordSearch='Microsoft Exchange', pubStartDate='2020-01-01 00:00', pubEndDate='2023-12-31 23:59', cvssV3Severity='HIGH' ) # Process one CVE at a time for cve in cve_generator: print(f"{cve.id}: {cve.v31score} - {cve.v31severity}") # Access weaknesses (CWE) if hasattr(cve, 'cwe'): for weakness in cve.cwe: print(f" CWE: {weakness.get('value', 'N/A')}") # Access CPE match criteria if hasattr(cve, 'cpe'): for cpe in cve.cpe: print(f" CPE: {cpe.criteria}") # Retrieve specific number of results first_cve = next(nvdlib.searchCVE_V2(keywordSearch='SQL injection', limit=100)) print(f"First result: {first_cve.id}") ``` -------------------------------- ### Search CPE Match Strings by CVE ID and Modification Date Source: https://context7.com/vehemont/nvdlib/llms.txt This snippet demonstrates how to search for CPE match strings associated with specific CVE IDs. It shows how to retrieve all match strings for a CVE, filter them using a `matchStringSearch` parameter, and look up a match by its specific `matchCriteriaId`. The example also includes searching for match strings based on modification dates. ```python import nvdlib # Search match strings for a specific CVE match_strings = nvdlib.searchCPEmatch(cveId='CVE-2017-0144') for match_string in match_strings: print(f"Match Criteria ID: {match_string.matchCriteriaId}") print(f"Criteria: {match_string.criteria}") print(f"Status: {match_string.status}") print(f"Last Modified: {match_string.lastModifiedDate}") # Iterate through matching CPE names if hasattr(match_string, 'matches'): print(f" Matches {len(match_string.matches)} CPE names:") for cpe_match in match_string.matches: print(f" {cpe_match.cpeName}") # Search with match string filter filtered_matches = nvdlib.searchCPEmatch( cveId='CVE-2017-0144', matchStringSearch='cpe:2.3:o:microsoft:windows_server_2012:*' ) # Search by specific match criteria ID specific_match = nvdlib.searchCPEmatch( cveId='CVE-2017-0144', matchCriteriaId='AB506484-7F0C-46BF-8EA6-4FB5AF454CED' ) # Returns list with single element when using matchCriteriaId if specific_match: match = specific_match[0] print(f"Criteria: {match.criteria}") print(f"Created: {match.created}") # Search by modification date match_by_date = nvdlib.searchCPEmatch( lastModStartDate='2023-01-01 00:00', lastModEndDate='2023-03-31 23:59', limit=100 ) ``` -------------------------------- ### Search CVE by ID using NVDLib Source: https://context7.com/vehemont/nvdlib/llms.txt Retrieves a specific CVE by its ID, returning a list containing the CVE object. It demonstrates accessing various attributes of the CVE, including its ID, severity, score, vector, description, publication date, and last modified date. It also shows how to get the best available CVSS score across different versions. ```python import nvdlib # Search for a specific CVE (returns a list with one element) cve = nvdlib.searchCVE(cveId='CVE-2021-26855')[0] # Access CVE attributes print(f"CVE ID: {cve.id}") print(f"Severity: {cve.v31severity}") print(f"Score: {cve.v31score}") print(f"Vector: {cve.v31vector}") print(f"Description: {cve.descriptions[0].value}") print(f"Published: {cve.published}") print(f"Last Modified: {cve.lastModified}") # Use the score attribute for version-agnostic scoring (prefers V31 > V30 > V2) version, score, severity = cve.score print(f"Best available score: {severity} - {score} ({version})") ``` -------------------------------- ### Search CVEs by Date Ranges and Source Identifier Source: https://context7.com/vehemont/nvdlib/llms.txt This section illustrates how to filter CVEs using publication and last modification dates. It covers searching within specific date ranges using string formats or `datetime` objects. The example also demonstrates filtering CVEs by their source identifier, such as 'cve@mitre.org', and setting a limit on the number of results. ```python import nvdlib from datetime import datetime, timedelta # Search by publication date (maximum 120-day range) recent_published = nvdlib.searchCVE( pubStartDate='2024-01-01 00:00', pubEndDate='2024-04-30 23:59', noRejected=True # Exclude rejected CVEs ) # Search by last modified date recently_modified = nvdlib.searchCVE( lastModStartDate='2024-03-01 00:00', lastModEndDate='2024-03-31 23:59', cvssV3Severity='HIGH' ) # Search with datetime objects end_date = datetime.now() start_date = end_date - timedelta(days=30) last_month = nvdlib.searchCVE( pubStartDate=start_date, pubEndDate=end_date ) print(f"CVEs published in last 30 days: {len(last_month)}") # Filter by source identifier mitre_cves = nvdlib.searchCVE( sourceIdentifier='cve@mitre.org', pubStartDate='2024-01-01 00:00', pubEndDate='2024-01-31 23:59', limit=100 ) ``` -------------------------------- ### Filter CPEs by Modification Date Range and Keyword (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CPEv2.md Shows how to filter CPEs based on their last modified date range and a keyword. This example retrieves CPEs modified within a specific month and counts the total number found. It requires start and end dates for the range. ```python r = nvdlib.searchCPE(lastModStartDate='2020-01-01 00:00', lastModEndDate='2020-02-01 00:00', keywordSearch='PHP') print(len(r)) 1599 ``` -------------------------------- ### Search CPEs by Recent Modification Date (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md This example demonstrates filtering CPE entries modified within the last 30 days using Python's datetime objects. It calculates the start and end dates for the past 30 days and uses them to query the CPE database. This approach is useful for finding recently updated CPE information. ```python import datetime end = datetime.datetime.now() start = end - datetime.timedelta(days=30) r = nvdlib.searchCPE(modStartDate=start, modEndDate=end) ``` -------------------------------- ### Search CVE with Keyword and API Key in Python Source: https://github.com/vehemont/nvdlib/blob/main/HISTORY.md Shows how to search for CVEs using a keyword and an API key for authentication. It also demonstrates how to handle CVEs that may not have a score available, setting their score to None to prevent errors. ```python >>> import nvdlib >>> r = nvdlib.searchCVE(keyword='log4j', key='xxxxxx-xxxx-xxxx-xxxxx-xxxxxxxx', limit=5) >>> print([(x.id + ' ' + str(x.score[0])) for x in r]) ['CVE-2022-23307 9.8', 'CVE-2021-44228 10.0', 'CVE-2022-21704 None', 'CVE-2021-4104 7.5', 'CVE-2022-23302 None'] ``` -------------------------------- ### Search CVE with API Key Source: https://context7.com/vehemont/nvdlib/llms.txt Demonstrates how to use an NVD API key to potentially increase rate limits and customize request delays for faster data retrieval. ```APIDOC ## Search CVE with API Key ### Description Using an NVD API key can improve performance by allowing for more frequent requests. It also enables customization of the delay between requests, with a lower minimum delay possible when a key is provided. ### Method GET (simulated by library function) ### Endpoint `/vulnerabilities/cve/2.0/` (internal NVD API endpoint, abstracted by the library) ### Parameters #### Query Parameters - **keywordSearch** (string) - Optional - Keywords to search for. - **cvssV3Severity** (string) - Optional - Filters by CVSS v3.1 severity level. - **key** (string) - Required - Your NVD API key (e.g., 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'). - **delay** (float) - Optional - Custom delay between requests (seconds). Without an API key, the default is 6 seconds. With an API key, a lower minimum delay (e.g., 0.6 seconds) can be set. ### Request Example ```python import nvdlib # Search with API key for potentially faster requests (minimum 0.6 seconds delay) api_key = 'YOUR_NVD_API_KEY' results = nvdlib.searchCVE( keywordSearch='apache', cvssV3Severity='HIGH', key=api_key, delay=0.6 # Minimum delay with API key ) print(f"Found {len(results)} CVEs with API key.") # Example of search without an API key (default 6-second delay) # slow_results = nvdlib.searchCVE(keywordSearch='nginx') ``` ### Response #### Success Response (200) Returns a list of CVE objects, similar to the standard search functionality. The main benefit is potential performance improvement due to reduced delays between requests. - **id** (string) - The CVE identifier. - **score** (tuple) - A tuple containing (version, score, severity) for the best available CVSS score. #### Response Example ```json [ { "id": "CVE-2023-0001", "score": ["V31", 8.0, "HIGH"], // ... other CVE fields } ] ``` ``` -------------------------------- ### Search CVEs with searchCVE Function Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Demonstrates how to use the `searchCVE` function to find CVEs based on CPE name and a specified limit. The function returns a list of CVE objects. This example retrieves CVEs for Microsoft Exchange Server 2013 cumulative update 11. ```python >>> r = nvdlib.searchCVE(cpeName = 'cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*', limit = 2) >>> type(r) >>> for eachCVE in r: ... print(eachCVE.id) CVE-1999-1322 CVE-2016-0032 ``` -------------------------------- ### Filter CPEs by Recent Modification Dates using Datetime (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CPEv2.md Demonstrates filtering CPEs modified within the last 30 days using Python's datetime objects. This approach is useful for finding recently updated CPE information. It dynamically calculates the start and end dates. ```python import datetime >>> end = datetime.datetime.now() >>> start = end - datetime.timedelta(days=30) >>> r = nvdlib.searchCPE(lastModStartDate=start, lastModEndDate=end) ``` -------------------------------- ### Search CVE by Keywords and Filters Source: https://context7.com/vehemont/nvdlib/llms.txt Searches the CVE database using various criteria such as keywords, date ranges, severity levels, and CPE names. ```APIDOC ## Search CVE by Keywords and Filters ### Description Search for vulnerabilities using keywords, date ranges, severity filters, CPE names, and other criteria to find relevant CVEs. Supports exact keyword matching and vulnerability status. ### Method GET (simulated by library function) ### Endpoint `/vulnerabilities/cve/2.0/` (internal NVD API endpoint, abstracted by the library) ### Parameters #### Query Parameters - **keywordSearch** (string) - Optional - Keywords to search for within CVE descriptions and other fields. - **keywordExactMatch** (boolean) - Optional - If true, performs an exact phrase match for `keywordSearch`. Defaults to false. - **cvssV3Severity** (string) - Optional - Filters by CVSS v3.1 severity level (e.g., 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'). - **pubStartDate** (string or datetime object) - Optional - Start date for publication range (YYYY-MM-DD or YYYY-MM-DD HH:MM). - **pubEndDate** (string or datetime object) - Optional - End date for publication range (YYYY-MM-DD or YYYY-MM-DD HH:MM). - **cpeName** (string) - Optional - Filters by Common Platform Enumeration (CPE) name (e.g., 'cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*'). - **isVulnerable** (boolean) - Optional - If true, only returns CVEs that list the specified CPE as vulnerable. - **limit** (integer) - Optional - Maximum number of results to return. Default is typically 1000 for standard search. - **apiKey** (string) - Optional - Your NVD API key for increased rate limits. - **delay** (float) - Optional - Custom delay between requests (seconds). ### Request Example ```python import nvdlib import datetime # Search with multiple filters results = nvdlib.searchCVE( keywordSearch='Microsoft Exchange', cvssV3Severity='CRITICAL', pubStartDate='2021-01-01 00:00', pubEndDate='2021-12-31 23:59', limit=50 ) print(f"Found {len(results)} CVEs") for cve in results: print(f"{cve.id}: {cve.score[1]} ({cve.score[2]})") # Search using datetime objects for last 7 days end = datetime.datetime.now() start = end - datetime.timedelta(days=7) recent_cves = nvdlib.searchCVE(pubStartDate=start, pubEndDate=end) # Search with CPE name and keyword cpe_results = nvdlib.searchCVE( cpeName='cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*', keywordSearch='remote code execution', keywordExactMatch=True, isVulnerable=True ) # Access detailed metrics for cve in cpe_results: print(f"CVE: {cve.id}") print(f"Attack Vector: {cve.v31attackVector}") print(f"Exploitability Score: {cve.v31exploitability}") ``` ### Response #### Success Response (200) - **id** (string) - The CVE identifier. - **score** (tuple) - A tuple containing (version, score, severity) for the best available CVSS score. - **v31attackVector** (string) - CVSS v3.1 Attack Vector metric. - **v31exploitability** (float) - CVSS v3.1 Exploitability Score. - **url** (string) - The direct URL to the CVE on the NVD website. - Other fields similar to 'Search CVE by ID' response. #### Response Example ```json [ { "id": "CVE-2021-26855", "score": ["V31", 9.8, "CRITICAL"], "v31attackVector": "Network", "v31exploitability": 3.9, "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-26855", "descriptions": [ { "lang": "en", "value": "Microsoft Exchange Server Remote Code Execution Vulnerability..." } ] // ... other CVE fields } ] ``` ``` -------------------------------- ### Search CVEs by CPE Name, Keyword, Exact Match, and CPE Dictionary Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md This snippet shows how to search for CVEs using a CPE name, keyword, exact match, and enabling the `cpe_dict` option. Enabling `cpe_dict` is necessary to retrieve CPE information within the CVE results. ```python >>> r = nvdlib.searchCVE(cpeName = 'cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*', keyword = '1ArcServe', exactMatch = True, cpe_dict = True) ``` -------------------------------- ### Search CVE by ID using NVDLib Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/changesv1.md Demonstrates how to search for a specific CVE using its ID with `nvdlib.searchCVE`. Since `nvdlib.getCVE` is deprecated, `searchCVE` is used with the `cveId` argument. The function always returns a list, so the first element must be accessed to get the CVE details. ```python >>> r = nvdlib.searchCVE(cveId='CVE-2021-26855') >>> r[0].id 'CVE-2021-26855' ``` ```python >>> r = nvdlib.searchCVE(cveId='CVE-2021-26855')[0] >>> r.id 'CVE-2021-26855' ``` -------------------------------- ### Search CVEs by Date, Keyword, Severity, and API Key (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Searches for CVEs within a specified publication date range, with a keyword filter, critical CVSS v3 severity, and uses an API key for authentication. Requires the nvdlib library. Returns a list of CVE objects. ```python >>> r = nvdlib.searchCVE(pubStartDate = '2021-09-08 00:00', pubEndDate = '2021-12-01 00:00', keywordSearch = 'Microsoft Exchange', cvssV3Severity = 'Critical', key='xxxxx-xxxxxx-xxxxxxx', delay=6) ``` -------------------------------- ### Import NVDLib and Search for a Single CVE (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Demonstrates how to import the NVDLib library and search for a specific CVE using its ID. This is the fundamental step to obtain CVE data. The `searchCVE` function returns a list, even when searching for a single CVE. ```python >>> import nvdlib >>> r = nvdlib.searchCVE(cveId='CVE-2017-0144') ``` -------------------------------- ### Advanced CVE Filtering with nvdlib Source: https://context7.com/vehemont/nvdlib/llms.txt Demonstrates filtering CVE data using various criteria such as CWE IDs, CVSS metrics (V2 and V3), version ranges, and virtual match strings. It also shows how to filter by US-CERT alerts and OVAL data, and perform complex searches with multiple combined filters. The nvdlib library is used for these operations, requiring Python and the nvdlib package. Outputs include lists of CVE objects that match the specified criteria. ```python import nvdlib # Filter by CWE (Common Weakness Enumeration) sql_injection = nvdlib.searchCVE( cweId='CWE-89', # SQL Injection cvssV3Severity='CRITICAL', pubStartDate='2023-01-01 00:00', pubEndDate='2023-12-31 23:59' ) # Filter by CVSS V2 metrics v2_filtered = nvdlib.searchCVE( cvssV2Metrics='AV:N/AC:L/Au:N', cvssV2Severity='HIGH' ) # Search with version ranges version_range = nvdlib.searchCVE( virtualMatchString='cpe:2.3:a:apache:http_server:*:*:*:*:*:*:*:*', versionStart='2.4.0', versionStartType='including', versionEnd='2.4.50', versionEndType='excluding' ) # Filter by US-CERT alerts and OVAL cert_alerts = nvdlib.searchCVE( hasCertAlerts=True, cvssV3Severity='CRITICAL' ) oval_cves = nvdlib.searchCVE( hasOval=True, keywordSearch='buffer overflow' ) # Complex search with multiple filters complex_search = nvdlib.searchCVE( cpeName='cpe:2.3:a:microsoft:*:*:*:*:*:*:*:*:*', keywordSearch='privilege escalation', keywordExactMatch=False, cvssV3Severity='HIGH', pubStartDate='2023-01-01 00:00', pubEndDate='2023-12-31 23:59', noRejected=True, limit=200 ) for cve in complex_search: print(f"{cve.id} - {cve.v31score} - {cve.descriptions[0].value[:100]}...") ``` -------------------------------- ### Search CPEs by Date Range and Keyword (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v1/v1.md This example shows how to filter CPE entries based on their modification dates and a keyword. It searches for CPEs modified between January 1, 2019, and January 1, 2020, that contain the keyword 'PHP'. The result then prints the total number of CPE entries found. A maximum date range of 120 days is supported. ```python r = nvdlib.searchCPE(modStartDate='2019-01-01 00:00', modEndDate='2020-01-01 00:00', keyword='PHP') print(len(r)) 5992 ``` -------------------------------- ### Search CVEs by CPE Name and Keyword with Exact Match (Python) Source: https://github.com/vehemont/nvdlib/blob/main/docs/source/v2/CVEv2.md Filters CVEs by a specific CPE name and a keyword, with exact keyword matching enabled. Requires the nvdlib library. Returns a list of CVE objects. ```python >>> r = nvdlib.searchCVE(cpeName = 'cpe:2.3:a:microsoft:exchange_server:2013:cumulative_update_11:*:*:*:*:*:*', keywordSearch = '1ArcServe', keywordExactMatch = True) ```