get-cwe 1.10.8

Tools for CVE managing, exploring and collect some data about their weaknesses and classifications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use crate::CweDisplayType::{
    Attacks, Consequences, Description, Detections, Extended, Mitigations, Name,
};
use csv::Reader;
use fenir::capec::show_attacks;
use fenir::cve::cve_from_cwe;
use fenir::cwe::CweRecord;
use fenir::database::{
    criteria_analysis, db_mitre_path, execute_query, find_capec_by_id,
    find_cwe_by_id, find_domain_and_criteria, parse_id_to_u32, prepare_query, search,
    text_or_null, MitreDatabase,
};

use fenir::facilities::{configure_csv_reader, hierarchical_show, ProgressText, Uppercase};
use fenir::package::{
    concepts::simplify_cve_list_content,
    errors::{write_error_message, write_error_message_and_exit},
};
use fenir::query::{build_query, QueryType::ByCwe};
use fenir::{db_mitre, header, section, section_level};
use rusqlite::{params, Connection, Rows};
use std::error::Error;
use std::fs::File;
use std::path::Path;
use termint::{
    enums::{Color},
    widgets::ToSpan,
};
use treelog::{builder::TreeBuilder, Tree};

/// Enum representing different types of CWE information to display
#[derive(Debug)]
pub enum CweDisplayType {
    /// Display all information
    All,
    /// Display related capec
    Attacks,
    /// Display consequences
    Consequences,
    /// Display description
    Description,
    /// Display detection methods
    Detections,
    /// Display extended description
    Extended,
    /// Display mitigation strategies
    Mitigations,
    /// Display cwe name
    Name,
}

impl CweDisplayType {
    pub fn show(&self, cwe_record: &CweRecord) {
        Self::show_record(self, cwe_record);
    }

    fn show_record(cwe_display_type: &CweDisplayType, cwe_record: &CweRecord) {
        match cwe_display_type {
            Description => println!(
                "{} {}",
                format!("{:>5} Description:", "-").fg(Color::DarkBlue),
                cwe_record.description
            ),

            Extended => {
                if !cwe_record.extended.is_empty() {
                    println!(
                        "{} {}",
                        format!("{:>5} Extended:", "-").fg(Color::DarkBlue),
                        cwe_record.extended
                    )
                }
            }

            Attacks => {
                println!();
                section_level!(2, "Attacks");
                show_attacks(cwe_record.attacks.clone());
            }

            Consequences => {
                if !cwe_record.consequences.is_empty() {
                    hierarchical_show("Consequences", cwe_record.clone().consequences)
                }
            }

            Detections => {
                if !cwe_record.detections.is_empty() {
                    hierarchical_show("Detections", cwe_record.clone().detections)
                }
            }

            Mitigations => {
                if !cwe_record.mitigations.is_empty() {
                    hierarchical_show("Mitigations", cwe_record.clone().mitigations)
                }
            }

            Name => print!(""),

            CweDisplayType::All => {
                Self::show_record(&Description, cwe_record);
                Self::show_record(&Extended, cwe_record);
                Self::show_record(&Consequences, cwe_record);
                Self::show_record(&Detections, cwe_record);
                Self::show_record(&Mitigations, cwe_record);
                Self::show_record(&Attacks, cwe_record);
            }
        }
    }
}

/// Injects data from a CSV file into a CWE table in an SQLite database.
///
/// This function connects to the SQLite database specified by `db_mitre_path()` internal method,
/// initializes the `cwe` table if it does not already exist, and reads data
/// from the CSV file specified by `cwe_csv_path` to inject into the `cwe` table.
///
/// # Arguments
///
/// * `cwe_csv_path` - A path the CSV file containing the CWE data.
///
/// # Returns
///
/// This function returns a `Result` with an empty tuple `()` on success, and a boxed `dyn std::error::Error` on failure.
///
/// # Errors
///
/// This function will return an error if:
///
/// * The connection to the SQLite database cannot be established.
/// * The CSV file cannot be read.
/// * Any of the records in the CSV file cannot be parsed correctly.
/// * There is an error executing the SQL insert statement.
///
/// # Dependencies
///
/// This function depends on the `csv` crate for reading CSV files and the `rusqlite` crate for interacting with SQLite databases.
pub fn inject_csv_into_cwe_table(cwe_csv_path: &Path) -> rusqlite::Result<(), Box<dyn Error>> {
    // Open the CSV file and read its content
    let mut reader = configure_csv_reader(cwe_csv_path)?;

    let file_name = cwe_csv_path.file_name().unwrap().to_str().unwrap();
    inject_cwe_data(&mut reader, file_name)
}

/// Injects CWE (Common Weakness Enumeration) data into an SQLite database.
///
/// This function reads data from a CSV file using a `csv::Reader` and inserts the data into an SQLite database
/// table named `cwe`. The function assumes that the CSV contains the following columns:
/// 1. `id`: CWE ID (i64)
/// 2. `name`: CWE name (String)
/// 3. `description`: CWE description (String)
/// 4. `extended`: Extended information (String)
/// 5. `consequences`: Potential consequences of the weakness (String)
/// 6. `detections`: Ways to detect the weakness (String)
/// 7. `mitigations`: Ways to mitigate the weakness (String)
///
/// # Arguments
///
/// * `conn` - An open SQLite `Connection`.
/// * `reader` - A mutable reference to a `csv::Reader` that reads from a file containing the CWE data.
///
/// # Returns
///
/// This function returns a nested `Result`:
/// * `Ok(Ok(()))` if the data was successfully injected into the database.
/// * `Ok(Err(e))` if there was a problem parsing the CSV records or inserting data into the database.
/// * `Err(e)` if an error occurs while reading the CSV records or executing the database operations.
///
/// # Errors
///
/// This function will return an error if:
/// * There is an error reading the CSV records.
/// * There is an error parsing the CSV data (e.g., converting the `id` column to an `i64`).
/// * There is an error executing the SQL insert statement.
fn inject_cwe_data(reader: &mut Reader<File>, file: &str) -> rusqlite::Result<(), Box<dyn Error>> {
    let records = reader.records().collect::<rusqlite::Result<Vec<_>, _>>()?;
    let mut progress_bar = ProgressText::new(1, records.len(), file.to_string());

    let connection = db_mitre!()?;
    for record in records {
        progress_bar.progress();

        let _ = connection.execute(
            "INSERT INTO cwe (id, name, description, extended, consequences, detections, mitigations, attacks) VALUES (?1, ?2, ?3, ?4, ?5,?6, ?7, ?8)",
            params![record[0].parse::<i64>()?, record[1].to_string(), record[4].to_string(), text_or_null(record[5].to_string()), record[14].to_string(),
                    text_or_null(record[15].to_string()), text_or_null(record[16].to_string()), text_or_null(record[21].to_string()),],
        );
    }

    println!("\nCWE data injected into SQLite database successfully.");
    Ok(())
}

pub struct CweTable;

impl MitreDatabase for CweTable {
    fn table_definitions(&self) -> Vec<(&'static str, &'static str)> {
        vec![(
            "cwe",
            "CREATE TABLE IF NOT EXISTS cwe (
                    id INTEGER PRIMARY KEY,
                    name TEXT NOT NULL,
                    description TEXT NOT NULL,
                    extended TEXT,
                    consequences TEXT,
                    detections TEXT,
                    mitigations TEXT,
                    attacks TEXT)",
        )]
    }
    
    fn index_definitions(&self) -> Vec<(&'static str, &'static str)> {
        vec![]
    }
}

/// Create the tree of the cwe schema. This schema included the list of associated CAPEC and CVE for a cwe record
///
/// # Argument
/// * `cwe` - Cwe record for which the schema must be built
///
/// # Return
/// The tree schema.
///
/// # Example
///
/// ```rust
/// use fenir::database::find_cwe_by_id;
/// use get_cwe::build_tree_schema;
///
/// let cwe = find_cwe_by_id(327).unwrap();
/// let schema = build_tree_schema(&cwe);
///
/// println!("{}", schema.render_to_string())
/// ```
pub fn build_tree_schema(cwe: &CweRecord) -> Tree {
    let mut builder = TreeBuilder::new();
    let cwe_str = format!("CWE-{}", cwe.id);
    builder.node(header!(cwe_str).to_string());

    
        builder.node("CAPEC".fg(Color::DarkRed).to_string());
        let capec_ids = parse_id_to_u32(cwe.attacks.clone());
        for capec_id in capec_ids {
            if let Some(capec) = find_capec_by_id(capec_id) {
                builder.leaf(
                    format!("CAPEC-{} - {}", capec_id, capec.name)
                        .fg(Color::DarkRed)
                        .to_string(),
                );
            }
        }

        builder.end();
    

    builder.node("CVE");
    let cve_results = execute_query(build_query(ByCwe, cwe_str.as_str()));
    let mut cves = cve_from_cwe(&cve_results);
    simplify_cve_list_content(&mut cves);
    if cves.is_empty() {
        builder.leaf("None");
    } else {
        cves.iter().for_each(|x| {
            builder.leaf(x.reference.clone());
        });
    }
    builder.end();

    builder.build()
}

pub fn run_search(args: &[String]) {
    let extraction = find_domain_and_criteria(args);
    if let Some(elements) = extraction {
        let domain = elements.0;
        let criteria = elements.1;

        let crit_analysis = criteria_analysis(criteria.clone());
        let (words, operators) = crit_analysis.unwrap();
        let found = search(
            prepare_query(
                format!("SELECT id FROM cwe WHERE {domain}"),
                words,
                &operators,
            ),
            extract_cwe_records,
        );
        if found.is_empty() {
            write_error_message(
                format!("Domain '{domain}' with criteria '{criteria}' not found").as_str(),
                None,
            );
        }

        found.iter().for_each(|x| {
            println!("{}", x);
            CweDisplayType::show_record(&switch_to_display_type(domain.as_str()), x)
        });
    } else {
        write_error_message_and_exit("Invalid argument: '=' missing. See help.", None);
    }
}

fn switch_to_display_type(name: &str) -> CweDisplayType {
    match name.trim().to_lowercase().as_str() {
        "consequences" => Consequences,
        "detections" => Detections,
        "description" => Description,
        "extended" => Extended,
        "mitigations" => Mitigations,
        "name" => Name,
        _ => CweDisplayType::All,
    }
}

fn extract_cwe_records(rows: &mut Rows) -> Vec<CweRecord> {
    let mut records = Vec::new();
    while let Some(row) = rows.next().unwrap() {
        let result = find_cwe_by_id(row.get(0).unwrap());
        if let Some(result) = result {
            records.push(result);
        }
    }

    records
}

#[cfg(test)]
mod tests {
    use crate::{find_cwe_by_id, inject_csv_into_cwe_table};
    use fenir::cwe::CweRecord;
    use fenir::database::{refresh_mitre_database, MitreDefinition, MITRE_DB_NAME};
    use fenir::os::{create_tyr_home, find_tyr_home_path};

    fn setup() {
        let tyr_home = find_tyr_home_path();
        if !tyr_home.exists() {
            create_tyr_home(&tyr_home);

            refresh_mitre_database(CweRecord::define(), inject_csv_into_cwe_table);
        }
    }

    #[test]
    fn test_cwe_invalid_none() {
        assert_eq!(None, find_cwe_by_id(10000000));
    }

    #[test]
    fn test_cwe_valid_parameter_not_none() {
        setup();

        assert_ne!(None, find_cwe_by_id(89));
    }

    #[test]
    fn test_cwe_update_csv_reference() {
        setup();

        let tyr_home = find_tyr_home_path();

        assert!(tyr_home.join(MITRE_DB_NAME).exists());
    }

    #[test]
    fn test_cwe_name_valid() {
        let cwe = find_cwe_by_id(112);
        assert_eq!("Missing XML Validation", cwe.unwrap().name);
    }

    #[test]
    fn test_cwe_description_valid() {
        let cwe = find_cwe_by_id(90);

        assert_eq!(
            "The product constructs all or part of an LDAP query using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended LDAP query when it is sent to a downstream component.",
            cwe.unwrap().description
        );
    }

    #[test]
    fn test_cwe_extended_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "Within XML, special elements could include reserved words or characters such as <, >, , and &, which could then be used to add new data or modify XML syntax.",
            cwe.unwrap().extended
        );
    }

    #[test]
    fn test_cwe_id_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(91, cwe.unwrap().id);
    }

    #[test]
    fn test_cwe_consequences_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "::SCOPE:Confidentiality:SCOPE:Integrity:SCOPE:Availability:IMPACT:Execute Unauthorized Code or Commands:IMPACT:Read Application Data:IMPACT:Modify Application Data::",
            cwe.unwrap().consequences
        );
    }

    #[test]
    fn test_cwe_detections_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "::METHOD:Automated Static Analysis:DESCRIPTION:Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect sources (origins of input) with sinks (destinations where the data interacts with external components, a lower layer such as the OS, etc.):EFFECTIVENESS:High::",
            cwe.unwrap().detections
        );
    }

    #[test]
    fn test_cwe_mitigations_valid() {
        let cwe = find_cwe_by_id(91);

        assert_eq!(
            "::PHASE:Implementation:STRATEGY:Input Validation:DESCRIPTION:Assume all input is malicious. Use an accept known good input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, boat may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as red or blue. Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.::",
            cwe.unwrap().mitigations
        );
    }
}