CVE-编号查找工具,用于查询和搜索CVE漏洞信息。

CVE-编号查找工具

CVE漏洞编号扫描工具:https://github.com/strivepan/CVE-

这是一个基于NVD API的CVE漏洞扫描工具,可以用于查询和搜索CVE漏洞信息。

功能特点

    • 支持关键词搜索CVE漏洞

    • 支持通过CVE ID查询特定漏洞

    • 显示漏洞详细信息,包括:

    • CVE ID

    • 发布日期

    • 严重程度

    • CVSS分数

    • 漏洞描述

    • 相关参考链接

    • 支持NVD API密钥配置

    • 自动重试机制和错误处理

    • 彩色输出界面

安装说明

    1. 克隆或下载本项目

    1. 安装依赖包:


    1. pip install -r requirements.txt
requests==2.31.0
python-dotenv==1.0.0
colorama==0.4.6

    1. 配置NVD API密钥:
        • 在项目根目录创建.env文件

        • 添加以下内容:
          NVD_API_KEY=你的API密钥

        • 如果没有API密钥,可以访问 https://nvd.nist.gov/developers/request-an-api-key 申请

使用方法

运行程序:

  python cve_scanner.py

import requests
import json
from datetime import datetime
from colorama import init, Fore, Style
import os
from dotenv import load_dotenv
import time

# 初始化colorama
init()

class CVEScanner:
    def __init__(self):
        # 加载环境变量
        load_dotenv(override=True)
        
        # API配置
        self.nvd_api_url = "https://services.nvd.nist.gov/rest/json/cves/2.0"
        
        # API密钥
        self.nvd_api_key = os.getenv('NVD_API_KEY')
        
        # 请求头
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        if self.nvd_api_key:
            print(f"{Fore.GREEN}NVD API密钥已配置{Style.RESET_ALL}")
            self.headers['apiKey'] = self.nvd_api_key
        else:
            print(f"{Fore.YELLOW}警告: 未配置NVD API密钥,可能会遇到访问限制{Style.RESET_ALL}")
            
    def _make_request(self, url, params=None, max_retries=3):
        """发送HTTP请求,包含重试机制"""
        for attempt in range(max_retries):
            try:
                print(f"{Fore.YELLOW}正在发送请求到: {url}{Style.RESET_ALL}")
                if params:
                    print(f"{Fore.YELLOW}请求参数: {params}{Style.RESET_ALL}")
                
                response = requests.get(url, headers=self.headers, params=params, timeout=10)
                response.raise_for_status()
                
                # 检查响应状态
                if response.status_code == 200:
                    return response.json()
                elif response.status_code == 403:
                    print(f"{Fore.RED}错误: 访问被拒绝。可能是API密钥无效或请求频率过高。{Style.RESET_ALL}")
                    if not self.nvd_api_key:
                        print(f"{Fore.YELLOW}建议: 请考虑申请NVD API密钥以提高访问限制。{Style.RESET_ALL}")
                elif response.status_code == 429:
                    print(f"{Fore.RED}错误: 请求过于频繁,请稍后再试。{Style.RESET_ALL}")
                    wait_time = 30  # 等待30秒
                    print(f"{Fore.YELLOW}等待 {wait_time} 秒后重试...{Style.RESET_ALL}")
                    time.sleep(wait_time)
                    continue
                    
            except requests.exceptions.Timeout:
                print(f"{Fore.RED}错误: 请求超时。{Style.RESET_ALL}")
            except requests.exceptions.ConnectionError:
                print(f"{Fore.RED}错误: 网络连接错误。请检查您的网络连接。{Style.RESET_ALL}")
            except requests.exceptions.RequestException as e:
                print(f"{Fore.RED}错误: 请求失败: {str(e)}{Style.RESET_ALL}")
                print(f"{Fore.YELLOW}响应内容: {response.text if 'response' in locals() else '无响应'}{Style.RESET_ALL}")
                
            if attempt < max_retries - 1:
                wait_time = 5 * (attempt + 1)  # 递增等待时间
                print(f"{Fore.YELLOW}等待 {wait_time} 秒后重试...{Style.RESET_ALL}")
                time.sleep(wait_time)
                
        return None
        
    def search_cve(self, keyword):
        """搜索特定关键词相关的CVE漏洞"""
        params = {
            'keywordSearch': keyword,
            'resultsPerPage': 20
        }
        
        data = self._make_request(self.nvd_api_url, params)
        if data:
            return self._process_results(data)
        return None

    def get_cve_by_id(self, cve_id):
        """通过CVE ID获取特定漏洞信息"""
        # 确保CVE ID格式正确
        cve_id = cve_id.upper()  # 转换为大写
        if not cve_id.startswith('CVE-'):
            cve_id = f"CVE-{cve_id}"
            
        url = f"{self.nvd_api_url}?cveId={cve_id}"
        print(f"{Fore.YELLOW}正在查询: {url}{Style.RESET_ALL}")
        
        data = self._make_request(url)
        if data:
            return self._process_results(data)
        return None
            
    def _process_results(self, data):
        """处理API返回的结果"""
        if not data or 'vulnerabilities' not in data:
            return []
            
        results = []
        for item in data['vulnerabilities']:
            cve = item['cve']
            description = cve['descriptions'][0]['value']
                
            results.append({
                'id': cve['id'],
                'published': cve['published'],
                'description': description,
                'severity': self._get_severity(cve),
                'cvss_score': self._get_cvss_score(cve),
                'references': self._get_references(cve)
            })
            
        return results
        
    def _get_severity(self, cve):
        """获取漏洞严重程度"""
        if 'metrics' in cve and 'cvssMetricV31' in cve['metrics']:
            return cve['metrics']['cvssMetricV31'][0]['cvssData']['baseSeverity']
        return "未知"
        
    def _get_cvss_score(self, cve):
        """获取CVSS分数"""
        if 'metrics' in cve and 'cvssMetricV31' in cve['metrics']:
            return cve['metrics']['cvssMetricV31'][0]['cvssData']['baseScore']
        return "未知"

    def _get_references(self, cve):
        """获取漏洞相关参考链接"""
        if 'references' in cve:
            return [ref['url'] for ref in cve['references']]
        return []
        
    def print_results(self, results):
        """打印扫描结果"""
        if not results:
            print(f"{Fore.YELLOW}未找到相关CVE漏洞{Style.RESET_ALL}")
            return
            
        print(f"\n{Fore.GREEN}找到 {len(results)} 个相关CVE漏洞:{Style.RESET_ALL}\n")
        
        for result in results:
            print(f"{Fore.CYAN}CVE ID: {result['id']}{Style.RESET_ALL}")
            print(f"发布日期: {result['published']}")
            print(f"严重程度: {self._get_severity_color(result['severity'])}")
            print(f"CVSS分数: {result['cvss_score']}")
            print(f"\n{Fore.YELLOW}漏洞描述:{Style.RESET_ALL}")
            print(result['description'])
            if result['references']:
                print(f"\n{Fore.YELLOW}相关链接:{Style.RESET_ALL}")
                for ref in result['references']:
                    print(f"- {ref}")
            print("-" * 80)
            
    def _get_severity_color(self, severity):
        """根据严重程度返回带颜色的文本"""
        severity_map = {
            'CRITICAL': ('严重', Fore.RED),
            'HIGH': ('高危', Fore.LIGHTRED_EX),
            'MEDIUM': ('中危', Fore.YELLOW),
            'LOW': ('低危', Fore.GREEN)
        }
        chinese, color = severity_map.get(severity, (severity, Fore.WHITE))
        return f"{color}{chinese}{Style.RESET_ALL}"

def main():
    print(f"{Fore.BLUE}CVE漏洞扫描工具{Style.RESET_ALL}")
    print("=" * 50)
    print(f"{Fore.YELLOW}提示: 如果没有配置API密钥,可能会遇到访问限制。{Style.RESET_ALL}")
    print(f"{Fore.YELLOW}建议: 访问 https://nvd.nist.gov/developers/request-an-api-key 申请API密钥。{Style.RESET_ALL}")
    
    scanner = CVEScanner()
    
    while True:
        print("\n请选择操作:")
        print("1. 关键词搜索")
        print("2. CVE ID查询")
        print("q. 退出")
        
        choice = input("\n请输入选项: ")
        
        if choice.lower() == 'q':
            break
        elif choice == '1':
            keyword = input("\n请输入要搜索的关键词: ")
            print(f"\n正在搜索与 '{keyword}' 相关的CVE漏洞...")
            results = scanner.search_cve(keyword)
            scanner.print_results(results)
        elif choice == '2':
            cve_id = input("\n请输入CVE ID (例如: CVE-2022-1388): ")
            print(f"\n正在查询 {cve_id} 的详细信息...")
            results = scanner.get_cve_by_id(cve_id)
            scanner.print_results(results)
        else:
            print(f"{Fore.RED}无效的选项,请重新选择{Style.RESET_ALL}")

if __name__ == "__main__":
    main()

在程序运行后,你可以:

    1. 选择”1″进行关键词搜索

    1. 选择”2″通过CVE ID查询

    1. 选择”q”退出程序 注意事项

    • 如果没有配置API密钥,可能会遇到访问限制

    • 建议申请NVD API密钥以提高访问限制

    • 请合理控制查询频率,避免触发API限制

效果图如下:
1
2

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容