yara-x 1.15.0

A pure Rust implementation of YARA.
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*! Implementation of the `vt` module.

This a VirusTotal-specific module that provides additional context and metadata
about files, URLs, IP addresses and domains scanned in VirusTotal.
*/

mod bitsquatting;
mod homoglyphs;
mod interleaved;
mod typos;

use std::net::IpAddr;
use std::ops::BitAnd;
use std::rc::Rc;
use std::sync::LazyLock;

use bstr::BStr;
use ipnet::IpNet;
use protobuf::EnumFull;

use crate::modules::prelude::*;
use crate::modules::protos::titan::*;
use crate::modules::protos::vtnet::enriched_domain::Permutation;
use crate::modules::vt::bitsquatting::bitsquatting;
use crate::modules::vt::homoglyphs::is_homoglyph;
use crate::modules::vt::interleaved::interleaved;
use crate::modules::vt::typos::{
    doubling, insertion, omission, replacement, swap, vowel_swap,
};
use crate::types::Struct;

static BITSQUATTING: LazyLock<i64> = LazyLock::new(|| {
    Struct::enum_value_i64(&Permutation::BITSQUATTING.descriptor()).unwrap()
});

static TYPO: LazyLock<i64> = LazyLock::new(|| {
    Struct::enum_value_i64(&Permutation::TYPO.descriptor()).unwrap()
});

static HYPHENATION: LazyLock<i64> = LazyLock::new(|| {
    Struct::enum_value_i64(&Permutation::HYPHENATION.descriptor()).unwrap()
});

static HOMOGLYPH: LazyLock<i64> = LazyLock::new(|| {
    Struct::enum_value_i64(&Permutation::HOMOGLYPH.descriptor()).unwrap()
});

static SUBDOMAIN: LazyLock<i64> = LazyLock::new(|| {
    Struct::enum_value_i64(&Permutation::SUBDOMAIN.descriptor()).unwrap()
});

#[module_main]
fn main(
    _data: &[u8],
    _meta: Option<&[u8]>,
) -> Result<LiveHuntData, ModuleError> {
    Ok(LiveHuntData::new())
}

/// Returns true if the IP address is within the given CIDR range.
#[module_export(method_of = "vt.net.EnrichedIP")]
fn in_range(
    ctx: &mut ScanContext,
    ip: Rc<Struct>,
    cidr: RuntimeString,
) -> bool {
    let cidr =
        match cidr.to_str(ctx).ok().and_then(|s| s.parse::<IpNet>().ok()) {
            Some(cidr) => cidr,
            None => return false,
        };

    let ip = ip.field_by_name("raw").unwrap().type_value.as_string();

    let ip = match ip.to_str().ok().and_then(|s| s.parse::<IpAddr>().ok()) {
        Some(ip) => ip,
        None => return false,
    };

    cidr.contains(&ip)
}

/// Returns true if the domain is a permutation of the given `target` domain.
#[module_export(name = "permutation_of", method_of = "vt.net.EnrichedDomain")]
fn all_permutations(
    ctx: &mut ScanContext,
    domain: Rc<Struct>,
    target: RuntimeString,
) -> bool {
    permutations(ctx, domain, target, 0x1F)
}

/// Returns true if the domain is a permutation of the given `target` domain, 
/// but the permutation must be any of the kinds specified in `permutation_kinds`.
#[module_export(name = "permutation_of", method_of = "vt.net.EnrichedDomain")]
fn permutations(
    ctx: &mut ScanContext,
    scanned_domain: Rc<Struct>,
    legitimate_domain: RuntimeString,
    permutation_kinds: i64,
) -> bool {
    let scanned_domain =
        scanned_domain.field_by_name("raw").unwrap().type_value.as_string();

    let scanned_domain = match parse_domain(scanned_domain.as_bstr()) {
        Some(d) => d,
        None => return false,
    };

    let legit_domain = match parse_domain(legitimate_domain.as_bstr(ctx)) {
        Some(s) => s,
        None => return false,
    };

    // The domain is not a permutation of itself.
    if scanned_domain == legit_domain {
        return false;
    }

    // Both domains must have the same TLD.
    if scanned_domain.tld != legit_domain.tld {
        return false;
    }

    let scanned_prefix = scanned_domain.prefix;
    let scanned_domain = match scanned_domain.domain {
        Some(d) => d,
        None => return false,
    };

    let legit_prefix = legit_domain.prefix;
    let legit_domain = match legit_domain.domain {
        Some(d) => d,
        None => return false,
    };

    if TYPO.bitand(&permutation_kinds) != 0
        && (insertion(legit_domain, scanned_domain)
            || omission(legit_domain, scanned_domain)
            || replacement(legit_domain, scanned_domain)
            || doubling(legit_domain, scanned_domain)
            || swap(legit_domain, scanned_domain)
            || vowel_swap(legit_domain, scanned_domain))
    {
        return true;
    }

    if HOMOGLYPH.bitand(&permutation_kinds) != 0
        && is_homoglyph(legit_domain, scanned_domain)
    {
        return true;
    }

    if BITSQUATTING.bitand(&permutation_kinds) != 0
        && bitsquatting(legit_domain, scanned_domain)
    {
        return true;
    }

    if SUBDOMAIN.bitand(&permutation_kinds) != 0
        && let (Some(legit), Some(scanned)) = (legit_prefix, scanned_prefix)
            && interleaved(legit, scanned, '.') {
                return true;
            }

    if HYPHENATION.bitand(&permutation_kinds) != 0
        && interleaved(legit_domain, scanned_domain, '-')
    {
        return true;
    }

    false
}

/// Parses a domain name and returns its parts. For instance,
/// for `www.virustotal.com` it returns:
///
/// ```text
/// DomainParts {
///   prefix: Some("www.virustotal"),
///   subdomain: Some("www"),
///   domain: Some("virustotal"),
///   tld: "com",
/// }
/// ```
///
/// Returns `None` if the argument is not a valid domain name.
fn parse_domain(domain: &BStr) -> Option<DomainParts<'_>> {
    let domain_len = domain.len();
    let suffix_len = psl::suffix(domain)?.as_bytes().len();
    let tld = domain[domain_len - suffix_len..].to_str().ok()?;
    let suffix_plus_dot = suffix_len + 1;

    if domain_len <= suffix_plus_dot {
        return Some(DomainParts {
            prefix: None,
            subdomain: None,
            domain: None,
            tld,
        });
    }

    let prefix = domain.get(..domain_len - suffix_plus_dot)?.to_str().ok()?;

    let (mut subdomain, mut domain) = match prefix.rsplit_once('.') {
        Some((subdomain, domain)) => (Some(subdomain), Some(domain)),
        None => (None, Some(prefix)),
    };

    // The psl::suffix function can incorrectly parse domains like
    // "www.gov.uk", returning "www" as the domain and "gov.uk" as the public
    // suffix. This happens because both "gov.uk" and "uk" are valid public
    // suffixes, leading to ambiguity:
    //
    // Possible interpretations:
    // - "www.gov.uk": subdomain="www", domain="gov", suffix="uk" (correct)
    // - "www.gov.uk": subdomain="", domain="www", suffix="gov.uk" (incorrect)
    //
    // However, for "www.tfl.gov.uk":
    // - subdomain="www.tfl", domain="gov", suffix="uk" (incorrect)
    // - subdomain="www", domain="tfl", suffix="gov.uk" (correct)
    //
    // This workaround checks for common subdomains (e.g., "www") and correctly
    // assigns the domain and subdomain fields to handle these cases.
    if matches!(
        domain,
        Some("www")
            | Some("ftp")
            | Some("m")
            | Some("mail")
            | Some("webmail")
            | Some("ns1")
            | Some("ns2")
    ) {
        subdomain = domain;
        domain = None;
    }

    Some(DomainParts { prefix: Some(prefix), subdomain, domain, tld })
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DomainParts<'a> {
    pub prefix: Option<&'a str>,
    pub subdomain: Option<&'a str>,
    pub domain: Option<&'a str>,
    pub tld: &'a str,
}

#[cfg(test)]
mod tests {
    use crate::modules::protos::titan::LiveHuntData;
    use crate::modules::vt::{parse_domain, DomainParts};
    use crate::{Compiler, Scanner};
    use bstr::BStr;
    use protobuf::text_format::parse_from_str;

    #[test]
    fn in_range_ipv4() {
        let vt_meta = Box::new(
            parse_from_str::<LiveHuntData>(
                r#"
                meta {
                    itw {
                        ip {
                            raw: "142.250.184.164"
                        }
                    }
                }
                net {
                    ip {
                        raw: "192.168.1.100"
                    }
                }"#,
            )
            .unwrap(),
        );

        let rule = r#"
           import "vt"
           rule test {
             condition:
               vt.net.ip.raw == "192.168.1.100"
               and vt.metadata.itw.ip.raw == "142.250.184.164"
               and vt.net.ip.in_range("192.168.1.100/32")
               and vt.net.ip.in_range("192.168.1.1/17")
               and vt.net.ip.in_range("192.168.1.0/24")
               and not vt.net.ip.in_range("192.168.1.0/32")
               and not vt.net.ip.in_range("192.168.1.0/31")
               and vt.metadata.itw.ip.in_range("142.250.184.164/20")
               and vt.metadata.itw.ip.in_range("142.250.176.0/20")
           }"#;

        let mut compiler = Compiler::new();

        compiler
            .enable_feature("ip_address")
            .enable_feature("file")
            .add_source(rule)
            .unwrap();

        let rules = compiler.build();

        assert_eq!(
            Scanner::new(&rules)
                .set_module_output(vt_meta)
                .unwrap()
                .scan(b"")
                .unwrap()
                .matching_rules()
                .len(),
            1
        );
    }

    #[test]
    fn in_range_ipv6() {
        let vt_meta = Box::new(
            parse_from_str::<LiveHuntData>(
                r#"
                meta {
                    itw {
                        ip {
                            raw: "2001:db8::1"
                        }
                    }
                }
                net {
                    ip {
                        raw: "2001:0DB8:7654:0010:FEDC:0000:0000:3210"
                    }
                }"#,
            )
            .unwrap(),
        );

        let rule = r#"
           import "vt"
           rule test {
             condition:
               vt.net.ip.raw == "2001:0DB8:7654:0010:FEDC:0000:0000:3210"
               and vt.metadata.itw.ip.raw == "2001:db8::1"
               and vt.net.ip.in_range("2001:db8::1/32")
               and not vt.net.ip.in_range("2001:db8::1/34")
               and vt.metadata.itw.ip.in_range("2001:db8::1/64")
           }"#;

        let mut compiler = Compiler::new();

        compiler
            .enable_feature("ip_address")
            .enable_feature("file")
            .add_source(rule)
            .unwrap();

        let rules = compiler.build();

        assert_eq!(
            Scanner::new(&rules)
                .set_module_output(vt_meta)
                .unwrap()
                .scan(b"")
                .unwrap()
                .matching_rules()
                .len(),
            1
        );
    }

    #[test]
    fn permutation_constants() {
        let rule = r#"
           import "vt"
           rule test {
             condition:
               vt.Domain.Permutation.ALL == vt.Domain.Permutation.TYPO
                | vt.Domain.Permutation.HYPHENATION
                | vt.Domain.Permutation.HOMOGLYPH
                | vt.Domain.Permutation.SUBDOMAIN
                | vt.Domain.Permutation.BITSQUATTING
           }"#;

        let mut compiler = Compiler::new();

        compiler
            .enable_feature("ip_address")
            .enable_feature("file")
            .add_source(rule)
            .unwrap();

        let rules = compiler.build();

        assert_eq!(
            Scanner::new(&rules).scan(b"").unwrap().matching_rules().len(),
            1
        );
    }

    macro_rules! squatting {
        ($legit_domain:literal, $scanned_domain:literal) => {{
            let vt_meta = Box::new(
                parse_from_str::<LiveHuntData>(
                    format!(
                        "net {{ domain {{ raw: \"{}\" }} }}",
                        $scanned_domain
                    )
                    .as_str(),
                )
                .unwrap(),
            );

            let rule = format!(
                r#"
           import "vt"
           rule test {{
             condition:
               vt.net.domain.permutation_of("{}")
           }}"#,
                $legit_domain
            );

            let mut compiler = Compiler::new();

            compiler
                .enable_feature("ip_address")
                .enable_feature("file")
                .add_source(rule.as_str())
                .unwrap();

            let rules = compiler.build();

            let result = Scanner::new(&rules)
                .set_module_output(vt_meta)
                .unwrap()
                .scan(b"")
                .unwrap()
                .matching_rules()
                .len()
                == 1;

            result
        }};
    }

    #[test]
    fn test_parse_domain() {
        assert_eq!(
            parse_domain(BStr::new("www.google.com")),
            Some(DomainParts {
                prefix: Some("www.google"),
                subdomain: Some("www"),
                domain: Some("google"),
                tld: "com"
            })
        );

        assert_eq!(
            parse_domain(BStr::new("gov.uk")),
            Some(DomainParts {
                prefix: None,
                subdomain: None,
                domain: None,
                tld: "gov.uk"
            })
        );

        assert_eq!(
            parse_domain(BStr::new("www.gov.uk")),
            Some(DomainParts {
                prefix: Some("www"),
                subdomain: Some("www"),
                domain: None,
                tld: "gov.uk"
            })
        );

        assert_eq!(
            parse_domain(BStr::new("ftp.gov.uk")),
            Some(DomainParts {
                prefix: Some("ftp"),
                subdomain: Some("ftp"),
                domain: None,
                tld: "gov.uk"
            })
        );

        assert_eq!(
            parse_domain(BStr::new("www.ncbi.nlm.nih.gov")),
            Some(DomainParts {
                prefix: Some("www.ncbi.nlm.nih"),
                subdomain: Some("www.ncbi.nlm"),
                domain: Some("nih"),
                tld: "gov"
            })
        );
    }

    #[test]
    fn test_squatting() {
        // the 'b' was omitted.
        assert!(squatting!("bankofamerica.com", "ankofamerica.com"));
        // the `o` was omitted.
        assert!(squatting!("bankofamerica.com", "bankfamerica.com"));
        // the `k` is repeated.
        assert!(squatting!("bankofamerica.com", "bankkofamerica.com"));
        // the `l` was inserted.
        assert!(squatting!("bankofamerica.com", "banklofamerica.com"));
        // 'q' is close to 'a' in the keyboard.
        assert!(squatting!("bankofamerica.com", "bqnkofamerica.com"));
        // 'É‘' is a homoglyph of 'a'
        assert!(squatting!("bankofamerica.com", "bɑnkofamerica.com"));
        // transposition of "a" and "b".
        assert!(squatting!("bankofamerica.com", "abnkofamerica.com"));
        // insertion of hyphens.
        assert!(squatting!("bankofamerica.com", "bank-of-america.com"));
        // the `e` was replaced with `d`, which is close in the keyboard.
        assert!(squatting!("bankofamerica.com", "bankofamdrica.com"));
        // the vowel `a` was replaced with `e`.
        assert!(squatting!("bankofamerica.com", "bonkofamerica.com"));
        // bitsquatting, the `k` and the `c` differ in one bit.
        assert!(squatting!("bankofamerica.com", "bancofamerica.com"));
        // subdomain
        assert!(squatting!("bankofamerica.com", "bankof.america.com"));
        assert!(squatting!("bankofamerica.com", "bank.of.america.com"));

        // test some negative cases
        assert!(!squatting!("www.google.com", "notifications.google.com"));
        assert!(!squatting!("www.ing.com", "www.ncbi.nlm.nih.gov"));
        assert!(!squatting!("www.google.com", "www.goggle.es"));
        assert!(!squatting!("www.google.com", "www.goore.com"));
    }
}