nabla-cli 0.2.1

An OSS tool for reverse engineering and binary composition analysis
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
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

use goblin::{elf::Elf, pe::PE};
use wasmparser::{Parser, Payload};

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VersionInfo {
    pub version_strings: Vec<String>,
    pub file_version: Option<String>,
    pub product_version: Option<String>,
    pub company: Option<String>,
    pub product_name: Option<String>,
    pub confidence: f64,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LicenseInfo {
    pub licenses: Vec<String>,
    pub copyright_notices: Vec<String>,
    pub spdx_identifiers: Vec<String>,
    pub license_texts: Vec<String>,
    pub confidence: f64,
}

pub fn extract_version_info(contents: &[u8], strings: &[String], format: &str) -> VersionInfo {
    let mut version_strings = HashSet::new();
    let mut file_version = None;
    let mut product_version = None;
    let mut company = None;
    let mut product_name = None;

    let version_patterns = [
        Regex::new(r"\b(\d+\.\d+\.\d+(?:\.\d+)?)\b").unwrap(),
        Regex::new(r"\bv(\d+\.\d+\.\d+(?:\.\d+)?)\b").unwrap(),
        Regex::new(r"\bversion\s*[:=]\s*([^\s,;]+)").unwrap(),
        Regex::new(r"\bVERSION\s*[:=]\s*([^\s,;]+)").unwrap(),
        Regex::new(r"\b(\d+\.\d+(?:\.\d+)?(?:\.\d+)?)\b").unwrap(),
    ];

    for string in strings {
        for pattern in &version_patterns {
            for captures in pattern.captures_iter(string) {
                if let Some(version) = captures.get(1) {
                    if is_valid_version(version.as_str()) {
                        version_strings.insert(version.as_str().to_string());
                    }
                }
            }
        }

        if company.is_none() {
            if let Some(comp) = extract_company_name(string) {
                company = Some(comp);
            }
        }

        if product_name.is_none() {
            if let Some(prod) = extract_product_name(string) {
                product_name = Some(prod);
            }
        }
    }

    match format {
        "application/x-msdownload" => {
            if let Some(pe_version) = extract_pe_version_info(contents) {
                file_version = file_version.or(pe_version.file_version);
                product_version = product_version.or(pe_version.product_version);
                company = company.or(pe_version.company);
                product_name = product_name.or(pe_version.product_name);
            }
        }
        "application/x-elf" => {
            if let Some(elf_versions) = extract_elf_version_info(contents) {
                version_strings.extend(elf_versions);
            }
        }
        "application/x-mach-binary" => {
            if let Some(macho_versions) = extract_macho_version_info(contents) {
                version_strings.extend(macho_versions);
            }
        }
        "application/wasm" => {
            if let Some(wasm_versions) = extract_wasm_version_info(contents) {
                version_strings.extend(wasm_versions);
            }
        }
        _ => {}
    }

    if file_version.is_none() && !version_strings.is_empty() {
        file_version = version_strings
            .iter()
            .max_by_key(|v| v.matches('.').count())
            .cloned();
    }

    let confidence = calculate_version_confidence(&version_strings, &file_version);

    VersionInfo {
        version_strings: version_strings.into_iter().collect(),
        file_version,
        product_version,
        company,
        product_name,
        confidence,
    }
}

pub fn extract_license_info(strings: &[String]) -> LicenseInfo {
    let mut licenses = HashSet::new();
    let mut copyright_notices = Vec::new();
    let mut spdx_identifiers = HashSet::new();
    let mut license_texts = Vec::new();

    let license_patterns = [
        (
            Regex::new(r"(?i)\b(MIT|BSD|GPL|LGPL|Apache|Mozilla|ISC|Unlicense)\b").unwrap(),
            "identifier",
        ),
        (
            Regex::new(r"(?i)licensed under the ([^.,;]+)").unwrap(),
            "phrase",
        ),
        (
            Regex::new(r"(?i)license:\s*([^.,;\n]+)").unwrap(),
            "declaration",
        ),
        (Regex::new(r"(?i)copyright\s+.*").unwrap(), "copyright"),
        (
            Regex::new(r"SPDX-License-Identifier:\s*([^\s]+)").unwrap(),
            "spdx",
        ),
    ];

    let license_text_patterns = [
        Regex::new(r"(?i)permission is hereby granted.*").unwrap(),
        Regex::new(r"(?i)redistribution and use in source and binary forms.*").unwrap(),
        Regex::new(r"(?i)this program is free software.*").unwrap(),
        Regex::new(r"(?i)licensed under the apache license.*").unwrap(),
    ];

    for string in strings {
        if string.len() < 10 {
            continue;
        }

        for (pattern, kind) in &license_patterns {
            for captures in pattern.captures_iter(string) {
                match *kind {
                    "identifier" | "phrase" | "declaration" => {
                        if let Some(license) = captures.get(1) {
                            let license_str = normalize_license_name(license.as_str());
                            if !license_str.is_empty() {
                                licenses.insert(license_str);
                            }
                        }
                    }
                    "copyright" => {
                        copyright_notices.push(string.clone());
                    }
                    "spdx" => {
                        if let Some(spdx) = captures.get(1) {
                            spdx_identifiers.insert(spdx.as_str().to_string());
                        }
                    }
                    _ => {}
                }
            }
        }

        for pattern in &license_text_patterns {
            if pattern.is_match(string) && string.len() > 100 {
                license_texts.push(string.clone());
                if let Some(inferred) = infer_license_from_text(string) {
                    licenses.insert(inferred);
                }
            }
        }
    }

    let confidence = calculate_license_confidence(&licenses, &spdx_identifiers, &license_texts);

    LicenseInfo {
        licenses: licenses.into_iter().collect(),
        copyright_notices,
        spdx_identifiers: spdx_identifiers.into_iter().collect(),
        license_texts,
        confidence,
    }
}

pub fn is_valid_version(version: &str) -> bool {
    if version.len() < 3 || version.len() > 20 || !version.contains('.') {
        return false;
    }

    let parts: Vec<&str> = version.split('.').collect();
    if parts.len() > 5 {
        return false;
    }

    for part in parts {
        if let Ok(num) = part.parse::<u32>() {
            if num > 9999 {
                return false;
            }
        }
    }

    true
}

pub fn extract_company_name(string: &str) -> Option<String> {
    let patterns = [
        Regex::new(r"(?i)company:\s*([^.,;\n]+)").unwrap(),
        Regex::new(r"(?i)corporation:\s*([^.,;\n]+)").unwrap(),
        Regex::new(r"(?i)© \d{4}\s+([^.,;\n]+)").unwrap(),
        Regex::new(
            r"(?i)copyright.*?(\w+(?:\s+\w+){0,3})(?:\s+inc\.?|\s+corp\.?|\s+ltd\.?|\s+llc)",
        )
        .unwrap(),
    ];

    for pattern in &patterns {
        if let Some(caps) = pattern.captures(string) {
            if let Some(m) = caps.get(1) {
                let s = m.as_str().trim();
                if s.len() > 2 && s.len() < 100 {
                    return Some(s.to_string());
                }
            }
        }
    }
    None
}

pub fn extract_product_name(string: &str) -> Option<String> {
    let patterns = [
        Regex::new(r"(?i)product:\s*([^.,;\n]+)").unwrap(),
        Regex::new(r"(?i)application:\s*([^.,;\n]+)").unwrap(),
        Regex::new(r"(?i)program:\s*([^.,;\n]+)").unwrap(),
    ];

    for pattern in &patterns {
        if let Some(caps) = pattern.captures(string) {
            if let Some(m) = caps.get(1) {
                let s = m.as_str().trim();
                if s.len() > 2 && s.len() < 100 {
                    return Some(s.to_string());
                }
            }
        }
    }
    None
}

pub fn normalize_license_name(license: &str) -> String {
    match license.to_lowercase().as_str() {
        "mit" => "MIT".to_string(),
        "bsd" => "BSD".to_string(),
        "gpl" => "GPL".to_string(),
        "lgpl" => "LGPL".to_string(),
        "apache" => "Apache-2.0".to_string(),
        "mozilla" => "MPL-2.0".to_string(),
        "isc" => "ISC".to_string(),
        "unlicense" => "Unlicense".to_string(),
        other => other.to_string(),
    }
}

pub fn infer_license_from_text(text: &str) -> Option<String> {
    let t = text.to_lowercase();
    if t.contains("permission is hereby granted") && t.contains("mit") {
        Some("MIT".to_string())
    } else if t.contains("redistribution and use in source and binary forms") {
        Some("BSD".to_string())
    } else if t.contains("apache license") {
        Some("Apache-2.0".to_string())
    } else if t.contains("gnu general public license") {
        Some("GPL".to_string())
    } else {
        None
    }
}

pub fn calculate_version_confidence(
    version_strings: &HashSet<String>,
    file_version: &Option<String>,
) -> f64 {
    let mut confidence: f64 = 0.0;
    if !version_strings.is_empty() {
        confidence += 0.3;
    }
    if file_version.is_some() {
        confidence += 0.4;
    }
    if version_strings.len() == 1 {
        confidence += 0.3;
    } else if version_strings.len() > 1 {
        confidence += 0.1;
    }
    confidence.min(1.0)
}

pub fn calculate_license_confidence(
    licenses: &HashSet<String>,
    spdx: &HashSet<String>,
    texts: &[String],
) -> f64 {
    let mut confidence: f64 = 0.0;
    if !spdx.is_empty() {
        confidence += 0.5;
    }
    if !licenses.is_empty() {
        confidence += 0.3;
    }
    if !texts.is_empty() {
        confidence += 0.2;
    }
    confidence.min(1.0)
}

// -----------------------------------------
// Format-specific extractors below
// -----------------------------------------

#[derive(Debug)]
pub struct PeVersionInfo {
    file_version: Option<String>,
    product_version: Option<String>,
    company: Option<String>,
    product_name: Option<String>,
}

pub fn extract_pe_version_info(contents: &[u8]) -> Option<PeVersionInfo> {
    // Use goblin to parse PE headers and extract basic version info from optional header
    if let Ok(pe) = PE::parse(contents) {
        if let Some(ref opt_header) = pe.header.optional_header {
            let windows = &opt_header.windows_fields;

            // File version: image version fields (if non-zero)
            let file_version =
                if windows.major_image_version != 0 || windows.minor_image_version != 0 {
                    Some(format!(
                        "{}.{}",
                        windows.major_image_version, windows.minor_image_version
                    ))
                } else {
                    None
                };

            // Product version: subsystem version fields (if non-zero)
            let product_version =
                if windows.major_subsystem_version != 0 || windows.minor_subsystem_version != 0 {
                    Some(format!(
                        "{}.{}",
                        windows.major_subsystem_version, windows.minor_subsystem_version
                    ))
                } else {
                    None
                };

            return Some(PeVersionInfo {
                file_version,
                product_version,
                company: None,      // Not available from headers
                product_name: None, // Not available from headers
            });
        }
    }
    None
}

pub fn extract_elf_version_info(contents: &[u8]) -> Option<Vec<String>> {
    if let Ok(elf) = Elf::parse(contents) {
        let mut versions = Vec::new();
        if let Some(note_iter) = elf.iter_note_headers(contents) {
            for note_result in note_iter {
                if let Ok(n) = note_result {
                    if n.name == "GNU" && n.n_type == goblin::elf::note::NT_GNU_BUILD_ID {
                        let hex = n
                            .desc
                            .iter()
                            .map(|b| format!("{:02x}", b))
                            .collect::<String>();
                        versions.push(hex);
                    }
                }
            }
        }
        Some(versions)
    } else {
        None
    }
}

pub fn extract_macho_version_info(_contents: &[u8]) -> Option<Vec<String>> {
    None // advanced Mach-O version extraction not implemented yet
}

pub fn extract_wasm_version_info(contents: &[u8]) -> Option<Vec<String>> {
    let mut versions = Vec::new();
    let parser = Parser::new(0);
    for payload in parser.parse_all(contents) {
        if let Ok(Payload::CustomSection(s)) = payload {
            if s.name().contains("version") || s.name().contains("meta") {
                let text = String::from_utf8_lossy(s.data());
                for line in text.lines() {
                    if let Some(v) = line.split_whitespace().find(|w| is_valid_version(w)) {
                        versions.push(v.to_string());
                    }
                }
            }
        }
    }
    Some(versions)
}