cwe-explorer 0.3.2__tar.gz → 0.5.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. cwe_explorer-0.5.2/MANIFEST.in +4 -0
  2. {cwe_explorer-0.3.2/cwe_explorer.egg-info → cwe_explorer-0.5.2}/PKG-INFO +45 -17
  3. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/README.md +58 -15
  4. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/__init__.py +1 -1
  5. cwe_explorer-0.5.2/cwe_explorer/cli.py +374 -0
  6. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/cve.py +212 -7
  7. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/data.py +67 -16
  8. cwe_explorer-0.5.2/cwe_explorer/docs_server.py +51 -0
  9. cwe_explorer-0.5.2/cwe_explorer/docs_site/404.html +452 -0
  10. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/images/favicon.png +0 -0
  11. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/bundle.525ec568.min.js +16 -0
  12. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/bundle.525ec568.min.js.map +7 -0
  13. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.ar.min.js +1 -0
  14. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.da.min.js +18 -0
  15. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.de.min.js +18 -0
  16. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.du.min.js +18 -0
  17. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.el.min.js +1 -0
  18. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.es.min.js +18 -0
  19. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.fi.min.js +18 -0
  20. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.fr.min.js +18 -0
  21. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.he.min.js +1 -0
  22. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.hi.min.js +1 -0
  23. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.hu.min.js +18 -0
  24. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.hy.min.js +1 -0
  25. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.it.min.js +18 -0
  26. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.ja.min.js +1 -0
  27. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.jp.min.js +1 -0
  28. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.kn.min.js +1 -0
  29. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.ko.min.js +1 -0
  30. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.multi.min.js +1 -0
  31. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.nl.min.js +18 -0
  32. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.no.min.js +18 -0
  33. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.pt.min.js +18 -0
  34. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.ro.min.js +18 -0
  35. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.ru.min.js +18 -0
  36. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.sa.min.js +1 -0
  37. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.stemmer.support.min.js +1 -0
  38. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.sv.min.js +18 -0
  39. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.ta.min.js +1 -0
  40. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.te.min.js +1 -0
  41. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.th.min.js +1 -0
  42. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.tr.min.js +18 -0
  43. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.vi.min.js +1 -0
  44. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/min/lunr.zh.min.js +1 -0
  45. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/tinyseg.js +206 -0
  46. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/lunr/wordcut.js +6708 -0
  47. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/workers/search.6ce7567c.min.js +42 -0
  48. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/javascripts/workers/search.6ce7567c.min.js.map +7 -0
  49. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/stylesheets/main.8c3ca2c6.min.css +1 -0
  50. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/stylesheets/main.8c3ca2c6.min.css.map +1 -0
  51. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/stylesheets/palette.06af60db.min.css +1 -0
  52. cwe_explorer-0.5.2/cwe_explorer/docs_site/assets/stylesheets/palette.06af60db.min.css.map +1 -0
  53. cwe_explorer-0.5.2/cwe_explorer/docs_site/css/extra.css +28 -0
  54. cwe_explorer-0.5.2/cwe_explorer/docs_site/cve-cwe-mapping/index.html +1496 -0
  55. cwe_explorer-0.5.2/cwe_explorer/docs_site/cve-ecosystem/index.html +971 -0
  56. cwe_explorer-0.5.2/cwe_explorer/docs_site/cve-viewer.png +0 -0
  57. cwe_explorer-0.5.2/cwe_explorer/docs_site/features/index.html +1211 -0
  58. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/logo.png +0 -0
  59. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-ancestors.webp +0 -0
  60. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-check.webp +0 -0
  61. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-cve.webp +0 -0
  62. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-cves.webp +0 -0
  63. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-member-of.webp +0 -0
  64. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-signals.webp +0 -0
  65. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-tree.webp +0 -0
  66. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-tui-cve.webp +0 -0
  67. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-tui-view.webp +0 -0
  68. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-view-699.webp +0 -0
  69. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-view-top25.webp +0 -0
  70. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/term-views.webp +0 -0
  71. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-cve-verdicts.webp +0 -0
  72. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-dark.webp +0 -0
  73. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-detailed.webp +0 -0
  74. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-filter-top25.webp +0 -0
  75. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-filters-hide.webp +0 -0
  76. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-filters.webp +0 -0
  77. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-fullscreen.webp +0 -0
  78. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-mapping.webp +0 -0
  79. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-mobile.webp +0 -0
  80. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-nvd-cves.webp +0 -0
  81. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-search-cve.webp +0 -0
  82. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-search.webp +0 -0
  83. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-signals.webp +0 -0
  84. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-view-owasp.webp +0 -0
  85. cwe_explorer-0.5.2/cwe_explorer/docs_site/img/web-view-top25.webp +0 -0
  86. cwe_explorer-0.5.2/cwe_explorer/docs_site/index.html +660 -0
  87. cwe_explorer-0.5.2/cwe_explorer/docs_site/json/index.html +2339 -0
  88. cwe_explorer-0.5.2/cwe_explorer/docs_site/limitations/index.html +752 -0
  89. cwe_explorer-0.5.2/cwe_explorer/docs_site/search/search_index.json +1 -0
  90. cwe_explorer-0.5.2/cwe_explorer/docs_site/sitemap.xml +3 -0
  91. cwe_explorer-0.5.2/cwe_explorer/docs_site/sitemap.xml.gz +0 -0
  92. cwe_explorer-0.5.2/cwe_explorer/docs_site/tui-viewer.png +0 -0
  93. cwe_explorer-0.5.2/cwe_explorer/docs_site/usage/index.html +1588 -0
  94. cwe_explorer-0.5.2/cwe_explorer/docs_site/views/index.html +966 -0
  95. cwe_explorer-0.5.2/cwe_explorer/docs_site/web-viewer.png +0 -0
  96. cwe_explorer-0.5.2/cwe_explorer/hierarchy.py +587 -0
  97. cwe_explorer-0.5.2/cwe_explorer/quality.py +125 -0
  98. cwe_explorer-0.5.2/cwe_explorer/records.py +188 -0
  99. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/render_html.py +35 -4
  100. cwe_explorer-0.5.2/cwe_explorer/render_term.py +674 -0
  101. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/tui.py +7 -4
  102. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/web/viewer.css +152 -0
  103. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/web/viewer.html +6 -0
  104. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/web/viewer.js +527 -48
  105. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2/cwe_explorer.egg-info}/PKG-INFO +45 -17
  106. cwe_explorer-0.5.2/cwe_explorer.egg-info/SOURCES.txt +116 -0
  107. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/docs/pypi.md +44 -16
  108. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/pyproject.toml +1 -1
  109. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/tests/fixtures/mini_cwe.xml +106 -0
  110. cwe_explorer-0.5.2/tests/test_cwe_explorer.py +1061 -0
  111. cwe_explorer-0.3.2/MANIFEST.in +0 -2
  112. cwe_explorer-0.3.2/cwe_explorer/cli.py +0 -236
  113. cwe_explorer-0.3.2/cwe_explorer/hierarchy.py +0 -320
  114. cwe_explorer-0.3.2/cwe_explorer/render_term.py +0 -393
  115. cwe_explorer-0.3.2/cwe_explorer.egg-info/SOURCES.txt +0 -26
  116. cwe_explorer-0.3.2/tests/test_cwe_explorer.py +0 -482
  117. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/LICENSE +0 -0
  118. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/__main__.py +0 -0
  119. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/details.py +0 -0
  120. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer/web/logo.png +0 -0
  121. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer.egg-info/dependency_links.txt +0 -0
  122. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer.egg-info/entry_points.txt +0 -0
  123. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/cwe_explorer.egg-info/top_level.txt +0 -0
  124. {cwe_explorer-0.3.2 → cwe_explorer-0.5.2}/setup.cfg +0 -0
@@ -0,0 +1,4 @@
1
+ # El sdist incluye los tests; su catálogo de ejemplo también hace falta para ejecutarlos.
2
+ recursive-include tests *.xml
3
+ # La web de documentación, si se ha construido (mkdocs build) antes de empaquetar.
4
+ recursive-include cwe_explorer/docs_site *
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cwe-explorer
3
- Version: 0.3.2
3
+ Version: 0.5.2
4
4
  Summary: Explore the MITRE CWE hierarchy (View 1000) from a CWE or a CVE: terminal tree, interactive explorer, web graph, ancestor/descendant queries and full CWE entries
5
5
  Author-email: Emi <edm@unex.es>
6
6
  License-Expression: MIT
@@ -37,10 +37,12 @@ Give `cwex` a **CWE** (`79`, `CWE-79`) or a **CVE** (`CVE-2021-44228`):
37
37
 
38
38
  - **For a CWE** it shows its type, status, publication date and description, and its
39
39
  lineage up to the top of the hierarchy (MITRE's View 1000, *Complete Weakness
40
- Hierarchy*).
40
+ Hierarchy*), its rank in the latest CWE Top 25 and its OWASP Top Ten category. It
41
+ can also count the CVEs in the NVD that have the weakness.
41
42
  - **For a CVE** it finds the CWEs linked to the vulnerability, says who links each one
42
43
  (the organization that published the CVE, CISA, the NVD or the CWE catalog
43
- itself), and shows all of them in the same hierarchy.
44
+ itself), and shows all of them in the same hierarchy. It also says whether the CVE
45
+ is being exploited: CISA's KEV catalog and SSVC assessment, and FIRST's EPSS score.
44
46
 
45
47
  ## Install
46
48
 
@@ -58,6 +60,9 @@ cwex 79 # a CWE: its details and its place in the hierarch
58
60
  cwex CVE-2021-44228 # a CVE: its CWEs and the hierarchy that joins them
59
61
  cwex CVE-2021-44228 --web # the same, as an interactive graph in the browser
60
62
  cwex 79 --tui # an interactive explorer in the terminal
63
+ cwex --check CVE-2021-44228 # should the CVE's CWEs be used to map it?
64
+ cwex 79 --cves # how many CVEs in the NVD have CWE-79, and the most recent
65
+ cwex --view 1450 --web # another view (here, the OWASP Top Ten 2025); cwex --views lists them
61
66
  ```
62
67
 
63
68
  What `cwex CVE-2021-44228` (Log4Shell) prints, shortened:
@@ -67,29 +72,44 @@ CVE CVE-2021-44228 Apache Log4j2 JNDI features do not protect against attacker
67
72
  and other JNDI related endpoints
68
73
  State Published on 2021-12-10
69
74
  ...
75
+ KEV Yes: in CISA's Known Exploited Vulnerabilities catalog since 2021-12-10, action due
76
+ 2021-12-24.
77
+ SSVC Exploitation active · Automatable yes · Technical Impact total (CISA-ADP, 2025-02-04)
78
+ EPSS 99.999% chance of exploitation in the next 30 days · percentile 100 (FIRST, 2026-11-03)
70
79
  Weaknesses CWE-502 Deserialization of Untrusted Data (Base) · from apache (CNA)
71
80
  CWE-400 Uncontrolled Resource Consumption (Class) · from apache (CNA)
81
+ ! Discouraged for mapping (Frequent Misuse, Abstraction). MITRE suggests CWE-770,
82
+ CWE-771, CWE-772, CWE-410, CWE-834, CWE-405.
72
83
  CWE-20 Improper Input Validation (Class) · from apache (CNA)
84
+ ! Discouraged for mapping (Frequent Misuse, Frequent Misinterpretation,
85
+ Abstraction). MITRE suggests CWE-1173, CWE-116, CWE-790, CWE-1284, CWE-1285,
86
+ CWE-1286 and 3 more.
73
87
  CWE-917 Improper Neutralization of Special Elements used in an Expression Language
74
88
  Statement (Base) · from NVD, CWE catalog (observed example)
75
89
  CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream
76
90
  Component (Class) · from CWE catalog (observed example)
91
+ ! Discouraged for mapping (Frequent Misuse, Abstraction). More specific: CWE-75,
92
+ CWE-77, CWE-79, CWE-91, CWE-93, CWE-94 and 3 more.
93
+ Warning The sources disagree: apache (CNA) (CWE-502, CWE-400, CWE-20) and NVD (CWE-917)
94
+ point to different branches: none of these CWEs is an ancestor or descendant of the
95
+ other source's.
77
96
  ...
78
97
  CWEs linked to CVE-2021-44228 in View 1000 (CWE 5.0, depth 0)
79
- Pi CWE-664 Improper Control of a Resource Through its Lifetime
80
- ├─ Cl CWE-913 Improper Control of Dynamically-Managed Code Resources
81
- │ └─ Ba CWE-502 Deserialization of Untrusted Data ◀
82
- └─ Cl CWE-400 Uncontrolled Resource Consumption (+7 children) ◀
83
- Pi CWE-707 Improper Neutralization
84
- ├─ Cl CWE-20 Improper Input Validation (+9 children) ◀
85
- └─ Cl CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream C… ◀
86
- └─ Cl CWE-77 Improper Neutralization of Special Elements used in a Command
87
- └─ Ba CWE-917 Improper Neutralization of Special Elements used in an Expression Lang… ◀
98
+ Pi CWE-664 Improper Control of a Resource Through its Lifetime ! Draft 2008
99
+ ├─ Cl CWE-913 Improper Control of Dynamically-Managed Code Resources ? Incomplete 2013
100
+ │ └─ Ba CWE-502 Deserialization of Untrusted Data ◀ Draft 2006
101
+ └─ Cl CWE-400 Uncontrolled Resource Consumption (+7 children) ◀ ! Draft 2006
102
+ Pi CWE-707 Improper Neutralization ! Incomplete 2008
103
+ ├─ Cl CWE-20 Improper Input Validation (+9 children) ◀ ! Stable 2006
104
+ └─ Cl CWE-74 Improper Neutralization of Special Elements in Output Use… ◀ ! Incomplete 2006
105
+ └─ Cl CWE-77 Improper Neutralization of Special Elements used in a Com… ? Draft 2006
106
+ └─ Ba CWE-917 Improper Neutralization of Special Elements used in… ◀ Incomplete 2013
88
107
  ```
89
108
 
90
109
  Apache, which published the CVE, links it to three CWEs; the NVD's analysts chose a
91
- different one, CWE-917. The tree shows where they all sit: Apache's three fall under
92
- two different pillars, and CWE-917 is three levels below the pillar CWE-707.
110
+ different one, CWE-917, in another branch of the hierarchy. Two of Apache's CWEs are
111
+ ones MITRE discourages for mapping vulnerabilities (marked `!`), and the card suggests
112
+ more specific ones.
93
113
 
94
114
  ## Options
95
115
 
@@ -99,15 +119,21 @@ The identifier can be a CWE or a CVE in every mode.
99
119
  | --- | --- |
100
120
  | *(none)* | Details and hierarchy as a tree in the terminal |
101
121
  | `--tui` | Interactive explorer: browse with the mouse or the arrow keys, `/` to jump to another CWE or CVE |
102
- | `--web` | A single HTML page with an interactive graph, which can also look up any other CVE |
122
+ | `--web` | A single HTML page with an interactive graph, which can also look up any other CVE, filter the weaknesses and count the CVEs of a CWE |
103
123
  | `--ancestors` | The parents (`--depth N` or `--depth all` for further levels) |
104
124
  | `--descendants` | The children, with the same `--depth` |
105
- | `--json` | With `--ancestors` or `--descendants`: the same result as JSON, for scripts |
125
+ | `--json` | Everything about the CWE or CVE as JSON, for scripts: data, lineages, ancestors, descendants, relations, mapping guidance, exploitation signals and the full catalog entry. Also the result of `--ancestors`, `--descendants`, `--check`, `--cves` or `--search` |
106
126
  | `--detailed` | Every section of the CWE entry: consequences, mitigations, code examples, observed CVEs, references… |
127
+ | `--check` | Whether each CWE, or each CWE of a CVE, should be used to map vulnerabilities, following MITRE's guidance, with alternatives. Exit status 1 if any is invalid or prohibited (`--strict`: also discouraged), for scripts and CI |
107
128
  | `--search TEXT` | Find weaknesses by name |
108
129
  | `--update` | Download the latest CWE catalog |
130
+ | `--cves` | How many CVEs in the NVD have the CWE, and the most recent ones (`--limit N`, `--since DATE`, `--include-descendants`) |
131
+ | `--view ID` | Another view instead of View 1000: the NVD's 1003, a CWE Top 25, the OWASP Top Ten… (`--views` lists them) |
132
+ | `--docs` | Open the full documentation in the browser, served by `cwex` itself |
109
133
 
110
- `cwex --help` lists every option.
134
+ `cwex --help` lists every option, and **`cwex --docs`** opens the full documentation:
135
+ a user guide for every mode, the limitations, how CVEs are linked to CWEs and who
136
+ the CNAs, ADPs and the NVD are.
111
137
 
112
138
  ## Where the data comes from
113
139
 
@@ -117,6 +143,8 @@ The identifier can be a CWE or a CVE in every mode.
117
143
  the CVE and enriched by others such as CISA; the analysis of the NVD (NIST); and the
118
144
  CVEs that the CWE catalog cites as examples. Lookups are cached for 7 days.
119
145
  Without a connection, the tool uses that cache or, failing that, the catalog.
146
+ - **Exploitation:** CISA's KEV entry and SSVC assessment, from the same record and
147
+ the NVD, and the EPSS score from FIRST.
120
148
 
121
149
  These sources often disagree about which CWE fits a CVE, so `cwex` shows every link
122
150
  with its source instead of choosing one.
@@ -11,13 +11,24 @@ Give `cwex` a **CWE** (`79`, `CWE-79`) or a **CVE** (`CVE-2021-44228`):
11
11
 
12
12
  - **For a CWE:** its type, status, publication date and description, and its lineage
13
13
  up to the top of MITRE's View 1000 (*Complete Weakness Hierarchy*), including every
14
- alternative path when it has several parents.
14
+ alternative path when it has several parents. Its rank in the latest CWE Top 25,
15
+ its OWASP Top Ten category and whether the NVD's view includes it. And, if you ask,
16
+ how many CVEs in the NVD have that weakness, and the most recent ones.
15
17
  - **For a CVE:** the CWEs linked to the vulnerability, who links each one (the
16
18
  organization that published it, CISA, the NVD or the CWE catalog), and all of them
17
- placed in the same hierarchy.
19
+ placed in the same hierarchy. Also whether it is being exploited: CISA's KEV
20
+ catalog and SSVC assessment, and FIRST's EPSS score.
21
+
22
+ <figure markdown="1">
18
23
 
19
24
  ![CVE-2021-44228 (Log4Shell) in the browser, linked to its five CWEs](docs/cve-viewer.png)
20
25
 
26
+ <figcaption><code>cwex CVE-2021-44228 --web</code>. Log4Shell in the browser: the CVE
27
+ (the dark node on the right, tagged KEV because it is known to be exploited) is linked
28
+ to its five CWEs, each in its place in View 1000. Its panel shows the CVSS scores and
29
+ the exploitation signals.</figcaption>
30
+ </figure>
31
+
21
32
  ## Install
22
33
 
23
34
  ```sh
@@ -35,24 +46,41 @@ cwex 79 # a CWE: its details and its place in the hierarch
35
46
  cwex CVE-2021-44228 # a CVE: its CWEs and the hierarchy that joins them
36
47
  cwex CVE-2021-44228 --web # the same, as an interactive graph in the browser
37
48
  cwex 79 --tui # an interactive explorer in the terminal
49
+ cwex --check CVE-2021-44228 # should the CVE's CWEs be used to map it? (MITRE's guidance)
50
+ cwex 79 --cves # how many CVEs in the NVD have CWE-79, and the most recent
51
+ cwex --view 1450 --web # another view (here, the OWASP Top Ten 2025); cwex --views lists them
38
52
  ```
39
53
 
40
54
  In the terminal, the hierarchy is a tree with the queried CWE marked:
41
55
 
42
56
  ```
43
57
  Hierarchy in View 1000 (CWE 5.0, depth 2)
44
- Pi CWE-707 Improper Neutralization
45
- └─ Cl CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstr…
46
- └─ Ba CWE-79 Improper Neutralization of Input During Web Page Generation ◀
47
- ├─ Va CWE-80 Improper Neutralization of Script-Related HTML Tags in a Web Page
48
- ├─ Va CWE-81 Improper Neutralization of Script in an Error Message Web Page
49
- ├─ Va CWE-83 Improper Neutralization of Script in Attributes in a Web Page
50
- │ └─ Va CWE-82 Improper Neutralization of Script in Attributes of IMG Tags in…
58
+ Pi CWE-707 Improper Neutralization ! Incomplete 2008
59
+ └─ Cl CWE-74 Improper Neutralization of Special Elements in Output Used b… ! Incomplete 2006
60
+ └─ Ba CWE-79 Improper Neutralization of Input During Web Page Gener… ◀ Stable 2006
61
+ ├─ Va CWE-80 Improper Neutralization of Script-Related HTML Tags in… Incomplete 2006
62
+ ├─ Va CWE-81 Improper Neutralization of Script in an Error Message … Incomplete 2006
63
+ ├─ Va CWE-83 Improper Neutralization of Script in Attributes in a W… Draft 2006
64
+ │ └─ Va CWE-82 Improper Neutralization of Script in Attributes of … Incomplete 2006
51
65
  ...
52
66
  ```
53
67
 
54
68
  `Pi`, `Cl`, `Ba`, `Va` and `Co` are the CWE types: Pillar, Class, Base, Variant and
55
- Compound.
69
+ Compound. On the right, a mark when MITRE discourages (`!`), prohibits (`✗`) or asks to
70
+ review (`?`) using the entry to map vulnerabilities, its status (how mature MITRE
71
+ considers it: Stable, Usable, Draft, Incomplete or Deprecated) and the year it was
72
+ published.
73
+
74
+ The interactive explorer (`--tui`) shows the same tree next to the details of the
75
+ selected entry, and is driven with the mouse or the keyboard:
76
+
77
+ <figure markdown="1">
78
+
79
+ ![The interactive explorer on CWE-693 Protection Mechanism Failure, with CWE-347 selected](docs/tui-viewer.png)
80
+
81
+ <figcaption><code>cwex 693 --tui</code>. The interactive explorer on CWE-693
82
+ <i>Protection Mechanism Failure</i>, with CWE-347 selected.</figcaption>
83
+ </figure>
56
84
 
57
85
  ## What you can do
58
86
 
@@ -62,16 +90,22 @@ The identifier can be a CWE or a CVE in every mode.
62
90
  | --- | --- |
63
91
  | *(none)* | Details and hierarchy as a tree in the terminal |
64
92
  | `--tui` | Interactive explorer: browse with the mouse or the arrow keys, `/` to jump to another CWE or CVE |
65
- | `--web` | A single HTML page with an interactive graph, which can also look up any other CVE |
93
+ | `--web` | A single HTML page with an interactive graph, which can also look up any other CVE, filter the weaknesses by type, status, mapping usage or year, and count the CVEs of a CWE |
66
94
  | `--ancestors` | The parents (`--depth N` or `--depth all` for further levels) |
67
95
  | `--descendants` | The children, with the same `--depth` |
68
- | `--json` | With `--ancestors` or `--descendants`: the same result as JSON, for scripts |
96
+ | `--json` | Everything about the CWE or CVE as JSON, for scripts: data, lineages, ancestors, descendants, relations, mapping guidance, exploitation signals and the full catalog entry. Also the result of `--ancestors`, `--descendants`, `--check`, `--cves` or `--search` |
69
97
  | `--detailed` | Every section of the CWE entry: consequences, mitigations, code examples, observed CVEs, references… |
98
+ | `--check` | Whether each CWE, or each CWE of a CVE, should be used to map vulnerabilities, following MITRE's guidance, with alternatives. Exit status 1 if any is invalid or prohibited (`--strict`: also discouraged) |
99
+ | `--cves` | How many CVEs in the NVD have the CWE, and the most recent ones (`--limit N`, `--since DATE`, `--include-descendants`) |
100
+ | `--view ID` | Another view instead of View 1000 in every mode: the NVD's 1003, a CWE Top 25, the OWASP Top Ten, *Software Development* (699)… |
101
+ | `--views` | The views of the catalog, and which ones `--view` can show |
70
102
  | `--search TEXT` | Find weaknesses by name |
71
103
  | `--update` | Download the latest CWE catalog |
104
+ | `--docs` | Open the full documentation in the browser, served by `cwex` itself |
72
105
 
73
106
  `cwex --help` lists every option. The [User guide](docs/usage.md) covers each mode in
74
- detail, including the explorer's keys, the browser's features and the JSON format.
107
+ detail, including the explorer's keys, the browser's features, the mapping guidance
108
+ and the JSON output.
75
109
 
76
110
  ## Where the data comes from
77
111
 
@@ -81,17 +115,26 @@ detail, including the explorer's keys, the browser's features and the JSON forma
81
115
  the CVE and enriched by others such as CISA; the analysis of the NVD (NIST); and the
82
116
  CVEs that the CWE catalog cites as examples. Lookups are cached for 7 days. Without
83
117
  a connection, the tool uses that cache or, failing that, the catalog.
118
+ - **Exploitation:** CISA's KEV entry and SSVC assessment, from the same CVE.org record
119
+ and the NVD, and the EPSS score from FIRST, cached for a day.
120
+ - **CVEs of a CWE:** the NVD, searched by weakness, cached for a day.
84
121
 
85
122
  These sources often disagree about which CWE fits a CVE, so `cwex` shows every link
86
123
  with its source instead of choosing one.
87
124
 
88
125
  ## Documentation
89
126
 
127
+ `cwex --docs` serves this documentation as a website on your computer, with search,
128
+ and opens it in the browser.
129
+
90
130
  | Document | What it covers |
91
131
  | --- | --- |
92
- | [User guide](docs/usage.md) | Every mode: the tree, the interactive explorer, the browser, `--detailed`, CVEs, ancestors and descendants, JSON, the Python API, data and cache |
132
+ | [Features](docs/features.md) | Everything CWE Explorer can do, with an example and a figure for each |
133
+ | [User guide](docs/usage.md) | Every mode: the tree, the interactive explorer, the browser and its filters, `--detailed`, CVEs and their exploitation signals, the CVEs of a CWE, mapping guidance, ancestors and descendants, other views, JSON, the Python API, data and cache |
134
+ | [Views](docs/views.md) | How to list the views of the catalog (CWE Top 25, OWASP Top Ten, the NVD's…) and open them in the terminal and in the browser |
135
+ | [JSON reference](docs/json.md) | The structure of every JSON output, field by field, with examples |
93
136
  | [Limitations](docs/limitations.md) | What the hierarchy and the CVE links can and cannot tell you, with figures from the catalog |
94
- | [How CVE Explorer links CVEs to CWEs](docs/cve-cwe-mapping.md) | Data sources, merge rules and how links are placed in the hierarchy, with diagrams |
137
+ | [How CWE Explorer links CVEs to CWEs](docs/cve-cwe-mapping.md) | Data sources, merge rules and how links are placed in the hierarchy, with diagrams |
95
138
  | [The CVE ecosystem](docs/cve-ecosystem.md) | Who the CNAs, the ADPs, the NVD and the CWE catalog are, and how they relate |
96
139
  | [Development](docs/development.md) | Running the tests, code layout and publishing a release |
97
140
  | [Work in progress](WIP/README.md) | Proposed features, not implemented yet |
@@ -1,3 +1,3 @@
1
1
  """Explorador de la jerarquía CWE (vista 1000 de MITRE) en la terminal y en el navegador."""
2
2
 
3
- __version__ = "0.3.2"
3
+ __version__ = "0.5.2"
@@ -0,0 +1,374 @@
1
+ """Punto de entrada: ``cwex 79`` (terminal), ``--tui`` (interactivo) o ``--web`` (navegador)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ import webbrowser
10
+ from datetime import date
11
+
12
+ from . import __version__
13
+ from .cve import NVD_MAX_PAGE, CVENotFound, cves_for_cwe, linked_cwes, lookup_cve, parse_cve_id
14
+ from .data import cache_dir, load_catalog
15
+ from .details import load_details
16
+ from .hierarchy import DEFAULT_VIEW, CWENotFound, Hierarchy, ViewNotFound, parse_cwe_id
17
+ from .render_html import write_html
18
+ from .quality import check_cve, disagreements, verdict
19
+ from .records import (check_payload, cve_record, cve_relatives_payload, cwe_cves_payload, cwe_record, relatives_payload,
20
+ search_payload, views_payload)
21
+ from .render_term import (BADGES, CVE_NODE, print_check, print_cve, print_cwe_cves, print_relatives, print_tree, print_views,
22
+ to_ansi, use_color)
23
+
24
+ DEFAULT_DEPTH = 2 # árbol, --tui y --web
25
+ DEFAULT_LIST_DEPTH = 1 # --ancestors / --descendants: sólo los directos
26
+ DEFAULT_CVE_DEPTH = 0 # un CVE: sólo los linajes de sus CWE (los hijos, a demanda o con --depth)
27
+ DEFAULT_VIEW_DEPTH = 1 # --view sin identificador: la vista y su primer nivel
28
+ DEFAULT_CVES_LIMIT = 20 # --cves: CVE más recientes que se listan
29
+ UNSET = object() # distingue «sin --depth» de «--depth all» (None)
30
+
31
+
32
+ def parse_depth(raw: str) -> int | None:
33
+ if raw.lower() in ("all", "*"):
34
+ return None
35
+ try:
36
+ value = int(raw)
37
+ except ValueError:
38
+ raise argparse.ArgumentTypeError("use a number >= 0 or 'all'") from None
39
+ if value < 0:
40
+ raise argparse.ArgumentTypeError("use a number >= 0 or 'all'")
41
+ return value
42
+
43
+
44
+ def parse_limit(raw: str) -> int:
45
+ try:
46
+ value = int(raw)
47
+ except ValueError:
48
+ raise argparse.ArgumentTypeError(f"use a number from 0 to {NVD_MAX_PAGE}") from None
49
+ if not 0 <= value <= NVD_MAX_PAGE:
50
+ raise argparse.ArgumentTypeError(f"use a number from 0 to {NVD_MAX_PAGE}")
51
+ return value
52
+
53
+
54
+ def parse_view(raw: str) -> str:
55
+ try:
56
+ return str(parse_cwe_id(raw.lower().replace("view", "")))
57
+ except ValueError:
58
+ raise argparse.ArgumentTypeError("use a view ID, for example 1003 or 699 (cwex --views lists them)") from None
59
+
60
+
61
+ def parse_since(raw: str) -> str:
62
+ try:
63
+ value = date.fromisoformat(raw)
64
+ except ValueError:
65
+ raise argparse.ArgumentTypeError("use a date as YYYY-MM-DD, for example 2025-01-01") from None
66
+ if value > date.today():
67
+ raise argparse.ArgumentTypeError("the date is in the future")
68
+ return value.isoformat()
69
+
70
+
71
+ def build_parser() -> argparse.ArgumentParser:
72
+ parser = argparse.ArgumentParser(
73
+ prog="cwex",
74
+ description="Explore the hierarchy of a CWE, or of the CWEs linked to a CVE, in MITRE's View 1000 "
75
+ "(Complete Weakness Hierarchy) in the terminal or in the browser.",
76
+ epilog="examples:\n"
77
+ " cwex 79 tree in the terminal\n"
78
+ " cwex CWE-79 --tui interactive explorer (mouse and keyboard)\n"
79
+ " cwex 79 --web interactive graph in the browser\n"
80
+ " cwex 664 --depth all every descendant\n"
81
+ " cwex --search overflow search by name\n"
82
+ " cwex 79 --ancestors direct parents (mode 1)\n"
83
+ " cwex 79 --descendants direct children (mode 2)\n"
84
+ " cwex 82 --ancestors --depth all every ancestor up to the pillar\n"
85
+ " cwex 664 --descendants -d all --json every descendant as JSON\n"
86
+ " cwex 79 --tui --detailed every section of each CWE (also the tree and --web)\n"
87
+ " cwex CVE-2021-44228 --web a CVE linked to its CWEs (every mode accepts a CVE)\n"
88
+ " cwex --check 20 79 CVE-2021-44228 should these CWEs be used to map vulnerabilities?\n"
89
+ " cwex 79 --cves how many CVEs in the NVD have CWE-79, and the most recent\n"
90
+ " cwex --view 1003 browse another view (here, the one the NVD uses)\n"
91
+ " cwex 79 --view 699 CWE-79 in that view; cwex --views lists every view\n"
92
+ " cwex 79 --json everything about CWE-79 as JSON (also for a CVE)\n"
93
+ " cwex --docs open the full documentation in the browser",
94
+ formatter_class=argparse.RawDescriptionHelpFormatter,
95
+ )
96
+ parser.add_argument("cwe", nargs="?", metavar="ID",
97
+ help="CWE identifier (79, CWE-79...) or CVE identifier (CVE-2021-44228)")
98
+ parser.add_argument("more", nargs="*", help=argparse.SUPPRESS) # más identificadores, sólo con --check
99
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
100
+ mode = parser.add_mutually_exclusive_group()
101
+ mode.add_argument("--tui", action="store_true", help="interactive explorer in the terminal")
102
+ mode.add_argument("--web", action="store_true", help="build the HTML graph and open it in the browser")
103
+ mode.add_argument("--search", metavar="TEXT", help="search weaknesses by name")
104
+ mode.add_argument("--ancestors", dest="relatives", action="store_const", const="ancestors",
105
+ help="list the ancestors: only the direct parents by default (mode 1)")
106
+ mode.add_argument("--descendants", dest="relatives", action="store_const", const="descendants",
107
+ help="list the descendants: only the direct children by default (mode 2)")
108
+ mode.add_argument("--docs", action="store_true",
109
+ help="serve the documentation on this computer and open it in the browser")
110
+ mode.add_argument("--check", action="store_true",
111
+ help="check whether each CWE (or each CWE of a CVE) should be used to map vulnerabilities, "
112
+ "following MITRE's guidance; accepts several IDs; exit status 1 if any is invalid or prohibited")
113
+ mode.add_argument("--cves", action="store_true",
114
+ help="count the CVEs in the NVD linked to the CWE and list the most recent ones")
115
+ mode.add_argument("--views", action="store_true", help="list the views of the CWE catalog")
116
+ parser.add_argument("-d", "--depth", type=parse_depth, default=UNSET, metavar="N",
117
+ help=f"levels to walk, or 'all'. Default: {DEFAULT_DEPTH} for the tree, --tui and "
118
+ f"--web, and {DEFAULT_LIST_DEPTH} (direct only) with --ancestors/--descendants")
119
+ parser.add_argument("--view", type=parse_view, metavar="ID",
120
+ help=f"use another view of the catalog instead of View {DEFAULT_VIEW}, such as 1003 (the NVD's), "
121
+ "699 (Software Development) or a Top 25; without a CWE, shows the whole view")
122
+ parser.add_argument("--json", action="store_true",
123
+ help="output JSON: everything about the CWE or CVE (with --depth limiting its descendants), "
124
+ "or the result of --ancestors, --descendants, --check, --cves or --search")
125
+ parser.add_argument("--strict", action="store_true", help="with --check, also fail on Discouraged CWEs")
126
+ parser.add_argument("--limit", type=parse_limit, default=DEFAULT_CVES_LIMIT, metavar="N",
127
+ help=f"with --cves, how many recent CVEs to list (default {DEFAULT_CVES_LIMIT}, "
128
+ f"up to {NVD_MAX_PAGE}; 0 only counts)")
129
+ parser.add_argument("--since", type=parse_since, metavar="DATE",
130
+ help="with --cves, only CVEs published on or after DATE (YYYY-MM-DD)")
131
+ parser.add_argument("--include-descendants", action="store_true",
132
+ help="with --cves, also count the CVEs of every descendant of the CWE (one request each)")
133
+ parser.add_argument("--detailed", action="store_true",
134
+ help="show every section of each CWE (consequences, mitigations, examples, observed "
135
+ "CVEs, references...) in the tree, --tui and --web")
136
+ parser.add_argument("-o", "--output", metavar="FILE", help="path of the HTML written by --web")
137
+ parser.add_argument("--no-open", action="store_true", help="with --web or --docs, do not open the browser")
138
+ parser.add_argument("--xml", metavar="PATH", help="use a local cwec_*.xml or .zip instead of downloading it")
139
+ parser.add_argument("--update", action="store_true", help="download the MITRE catalog again")
140
+ color = parser.add_mutually_exclusive_group()
141
+ color.add_argument("--color", dest="color", action="store_true", default=None, help="force ANSI colors")
142
+ color.add_argument("--no-color", dest="color", action="store_false", help="disable colors")
143
+ return parser
144
+
145
+
146
+ def open_web(h: Hierarchy, cid: int, depth: int | None, output: str | None = None, launch: bool = True,
147
+ details: dict | None = None, cve=None) -> str:
148
+ path = write_html(h, cid, depth, output, details, cve)
149
+ if launch:
150
+ webbrowser.open(path.as_uri())
151
+ return f"Web graph written to {path}"
152
+
153
+
154
+ def main(argv: list[str] | None = None) -> int:
155
+ try:
156
+ code = _main(argv)
157
+ sys.stdout.flush() # si la tubería ya se cerró, el error salta aquí y no al salir
158
+ return code
159
+ except KeyboardInterrupt:
160
+ return 130
161
+ except BrokenPipeError: # p. ej. `cwex 664 --depth all | head`
162
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
163
+ return 0
164
+
165
+
166
+ def _main(argv: list[str] | None) -> int:
167
+ parser = build_parser()
168
+ args = parser.parse_args(argv)
169
+ if args.docs:
170
+ from .docs_server import serve
171
+
172
+ return serve(open_browser=not args.no_open)
173
+ other_view = args.view is not None and args.view != DEFAULT_VIEW
174
+ if not args.cwe and not args.search and not args.update and not args.views and not other_view:
175
+ parser.print_usage(sys.stderr)
176
+ hint = (f" (View {DEFAULT_VIEW} has no single root: its pillars are the top)" if args.view else "")
177
+ print(f"cwex: give a CWE identifier, for example: cwex 79{hint}", file=sys.stderr)
178
+ return 2
179
+ if args.view is not None and (args.check or args.cves or args.views):
180
+ parser.error("--view cannot be combined with --check, --cves or --views, which use the whole catalog")
181
+ if args.json and (args.tui or args.web):
182
+ parser.error("--json cannot be combined with --tui or --web")
183
+ full_json = args.json and not (args.relatives or args.check or args.search or args.cves)
184
+ # La ficha completa en JSON trae todos los descendientes salvo que se pida otra profundidad.
185
+ args.json_depth = None if args.depth is UNSET else args.depth
186
+ if args.detailed and (args.relatives or args.search or args.check or args.cves):
187
+ parser.error("--detailed only works with the tree view, --tui and --web")
188
+ if args.strict and not args.check:
189
+ parser.error("--strict can only be used with --check")
190
+ used = [opt for opt, on in (("--limit", args.limit != DEFAULT_CVES_LIMIT), ("--since", args.since),
191
+ ("--include-descendants", args.include_descendants)) if on]
192
+ if used and not args.cves:
193
+ parser.error(f"{used[0]} can only be used with --cves")
194
+ if args.more and not args.check:
195
+ parser.error("only --check accepts several identifiers")
196
+ cve_id = parse_cve_id(args.cwe) if args.cwe else None
197
+ if args.depth is UNSET:
198
+ whole_view = other_view and not args.cwe
199
+ args.depth = (DEFAULT_LIST_DEPTH if args.relatives else DEFAULT_CVE_DEPTH if cve_id
200
+ else DEFAULT_VIEW_DEPTH if whole_view else DEFAULT_DEPTH)
201
+ elif args.relatives and args.depth == 0:
202
+ parser.error("with --ancestors/--descendants the depth must be 1 or more (or 'all')")
203
+
204
+ try:
205
+ catalog = load_catalog(args.xml, refresh=args.update)
206
+ except Exception as exc: # red, XML corrupto, permisos...
207
+ print(f"cwex: could not load the CWE catalog: {exc}", file=sys.stderr)
208
+ return 1
209
+ try:
210
+ h = Hierarchy(catalog, args.view or DEFAULT_VIEW)
211
+ except ViewNotFound as exc:
212
+ print(f"cwex: {exc} cwex --views lists the views that can be browsed.", file=sys.stderr)
213
+ return 1
214
+ try:
215
+ details = load_details(h.version, h.date, args.xml) if args.detailed or full_json else None
216
+ except Exception as exc:
217
+ print(f"cwex: could not load the CWE catalog: {exc}", file=sys.stderr)
218
+ return 1
219
+
220
+ if args.update and not args.cwe and not args.search and not args.views and not other_view:
221
+ print(f"CWE catalog {h.version} ({h.date}) saved to {cache_dir()}: {len(h.nodes)} weaknesses in {h.view_label}.")
222
+ return 0
223
+
224
+ if args.views:
225
+ if args.json:
226
+ print(json.dumps(views_payload(h), ensure_ascii=False, indent=2))
227
+ else:
228
+ print_views(h, color=args.color)
229
+ return 0
230
+
231
+ if args.search and args.json:
232
+ payload = search_payload(h, args.search)
233
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
234
+ return 0 if payload["results"] else 1
235
+
236
+ if args.search:
237
+ hits = h.search(args.search, limit=25)
238
+ if not hits:
239
+ print(f"No results for \"{args.search}\".")
240
+ return 1
241
+ color = use_color(args.color)
242
+ for n in hits:
243
+ line = [(BADGES.get(n.abstraction, "??"), f"badge:{n.abstraction}"), (" ", "plain"),
244
+ (f"{n.label:<9}", "bold"), (" " + n.name, "plain")]
245
+ print(to_ansi(line, color))
246
+ return 0
247
+
248
+ if args.check:
249
+ return _run_check(args, h)
250
+
251
+ if cve_id and args.cves:
252
+ print("cwex: --cves needs a CWE; for the CWEs of a CVE, run: cwex " + cve_id, file=sys.stderr)
253
+ return 2
254
+
255
+ if cve_id:
256
+ try:
257
+ cve = lookup_cve(cve_id, h, refresh=args.update)
258
+ except (ValueError, CVENotFound) as exc:
259
+ print(f"cwex: {exc}", file=sys.stderr)
260
+ return 1
261
+ return _run_cve(args, h, cve, details)
262
+
263
+ try:
264
+ node = h.get(args.cwe) if args.cwe else h.nodes[h.view_root]
265
+ except (ValueError, CWENotFound) as exc:
266
+ print(f"cwex: {exc}", file=sys.stderr)
267
+ return 1
268
+
269
+ if args.cves:
270
+ return _run_cves(args, h, node.id)
271
+ if args.json and not args.relatives:
272
+ print(json.dumps(cwe_record(h, node.id, details, args.json_depth), ensure_ascii=False, indent=2))
273
+ elif args.relatives and args.json:
274
+ print(json.dumps(relatives_payload(h, node.id, args.relatives, args.depth), ensure_ascii=False, indent=2))
275
+ elif args.relatives:
276
+ print_relatives(h, node.id, args.relatives, args.depth, color=args.color)
277
+ elif args.web:
278
+ print(open_web(h, node.id, args.depth, args.output, launch=not args.no_open, details=details))
279
+ elif args.tui:
280
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
281
+ print("cwex: --tui needs an interactive terminal.", file=sys.stderr)
282
+ return 1
283
+ from . import tui # curses no existe en algunos Windows: se importa sólo si hace falta
284
+
285
+ tui.run(h, node.id, args.depth, lambda cid, depth, cve=None: open_web(h, cid, depth, details=details, cve=cve),
286
+ details)
287
+ else:
288
+ print_tree(h, node.id, args.depth, color=args.color, details=details)
289
+ return 0
290
+
291
+
292
+ def _run_check(args, h: Hierarchy) -> int:
293
+ """--check: la recomendación de MITRE para cada CWE, o para cada CWE de cada CVE."""
294
+ groups: list[dict] = []
295
+ loose: list = [] # los CWE sueltos van juntos, en el orden dado
296
+ for raw in [args.cwe, *args.more]:
297
+ if not parse_cve_id(raw):
298
+ loose.append(verdict(h, raw))
299
+ continue
300
+ if loose:
301
+ groups.append({"verdicts": loose})
302
+ loose = []
303
+ try:
304
+ cve = lookup_cve(raw, h, refresh=args.update, epss=False)
305
+ except (ValueError, CVENotFound) as exc:
306
+ groups.append({"input": raw, "error": str(exc)})
307
+ continue
308
+ groups.append({"input": cve.id, "cve": cve, "verdicts": check_cve(h, cve),
309
+ "disagreements": disagreements(h, cve)})
310
+ if loose:
311
+ groups.append({"verdicts": loose})
312
+ if args.json:
313
+ payload = check_payload(h, groups, args.strict)
314
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
315
+ return 0 if payload["passed"] else 1
316
+ return 1 if print_check(h, groups, strict=args.strict, color=args.color) else 0
317
+
318
+
319
+ def _run_cves(args, h: Hierarchy, cid: int) -> int:
320
+ """--cves: los CVE del NVD con este CWE (y, con --include-descendants, el recuento de cada descendiente)."""
321
+ def progress(message: str) -> None:
322
+ print(message, file=sys.stderr, flush=True)
323
+
324
+ # Sin clave, el NVD admite 5 peticiones cada 30 s: cves_for_cwe avisa (progress) cuando le toca esperar.
325
+ others = [r.id for r in h.relatives(cid, "descendants", None)] if args.include_descendants else []
326
+ try:
327
+ result = cves_for_cwe(cid, args.limit, args.since, refresh=args.update, progress=progress)
328
+ by_cwe = None
329
+ if args.include_descendants:
330
+ counts = [(cid, result.count)]
331
+ for other in others:
332
+ counted = cves_for_cwe(other, 0, args.since, refresh=args.update, progress=progress)
333
+ counts.append((other, counted.count))
334
+ result.notes += [n for n in counted.notes if n not in result.notes]
335
+ by_cwe = [counts[0]] + sorted(counts[1:], key=lambda item: -item[1])
336
+ except OSError as exc:
337
+ print(f"cwex: could not query the NVD: {exc}", file=sys.stderr)
338
+ return 1
339
+ if args.json:
340
+ print(json.dumps(cwe_cves_payload(h, result, by_cwe), ensure_ascii=False, indent=2))
341
+ else:
342
+ print_cwe_cves(h, cid, result, by_cwe, color=args.color)
343
+ return 0
344
+
345
+
346
+ def _run_cve(args, h: Hierarchy, cve, details: dict | None) -> int:
347
+ """Los mismos modos que con una CWE, aplicados a los CWE del CVE que están en la vista 1000."""
348
+ linked = linked_cwes(h, cve)
349
+ if args.json and not args.relatives:
350
+ print(json.dumps(cve_record(h, cve, details, args.json_depth), ensure_ascii=False, indent=2))
351
+ elif args.relatives and args.json:
352
+ print(json.dumps(cve_relatives_payload(h, cve, args.relatives, args.depth), ensure_ascii=False, indent=2))
353
+ elif args.relatives:
354
+ color = use_color(args.color)
355
+ refs = ", ".join(f"CWE-{cid}" for cid in linked) or f"none in {h.view_label}"
356
+ print(to_ansi([("CVE", "cve"), (" ", "plain"), (cve.id, "bold"), (" ", "plain"), (cve.summary[:90], "plain")],
357
+ color))
358
+ print(to_ansi([(f"Linked CWEs: {refs}", "dim")], color))
359
+ for cid in linked:
360
+ print()
361
+ print_relatives(h, cid, args.relatives, args.depth, color=args.color)
362
+ elif args.web:
363
+ print(open_web(h, CVE_NODE, args.depth, args.output, launch=not args.no_open, details=details, cve=cve))
364
+ elif args.tui:
365
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
366
+ print("cwex: --tui needs an interactive terminal.", file=sys.stderr)
367
+ return 1
368
+ from . import tui
369
+
370
+ tui.run(h, CVE_NODE, args.depth, lambda cid, depth, c=cve: open_web(h, cid, depth, details=details, cve=c),
371
+ details, cve)
372
+ else:
373
+ print_cve(h, cve, args.depth, color=args.color, details=details)
374
+ return 0