binary-security-check 2.0.2

Analyzer of security features in executable binaries
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
// Copyright 2018-2025 Koutheir Attouchi.
// See the "LICENSE.txt" file at the top-level directory of this distribution.
//
// Licensed under the MIT license. This file may not be copied, modified,
// or distributed except according to those terms.

pub(crate) mod checked_functions;
pub(crate) mod gnu_properties;
pub(crate) mod needed_libc;

use std::collections::HashSet;

use log::{debug, log_enabled, warn};

use crate::elf::gnu_properties::{GNUProperty, GNUPropertyAArch64Feature1, GNUPropertyX86Feature1};
use crate::errors::Result;
use crate::options::status::{ASLRCompatibilityLevel, DisplayInColorTerm};
use crate::options::{
    AddressSpaceLayoutRandomizationOption, BinarySecurityOption,
    ELFBranchTargetIdentificationOption, ELFFortifySourceOption, ELFGuardedControlStackOption,
    ELFImmediateBindingOption, ELFReadOnlyAfterRelocationsOption, ELFStackMustBeExecutableOption,
    ELFStackProtectionOption, ELFSupportsShadowStackOption,
};
use crate::parser::BinaryParser;

use self::checked_functions::function_is_checked_version;
use self::needed_libc::NeededLibC;

pub(crate) fn analyze_binary(
    parser: &BinaryParser,
    options: &crate::cmdline::Options,
) -> Result<Vec<Box<dyn DisplayInColorTerm>>> {
    let supports_address_space_layout_randomization =
        AddressSpaceLayoutRandomizationOption.check(parser, options)?;
    let has_stack_protection = ELFStackProtectionOption.check(parser, options)?;
    let stack_must_be_executable = ELFStackMustBeExecutableOption.check(parser, options)?;
    let supports_shadow_stack = ELFSupportsShadowStackOption.check(parser, options)?;
    let guarded_control_stack = ELFGuardedControlStackOption.check(parser, options)?;
    let branch_target_identification =
        ELFBranchTargetIdentificationOption.check(parser, options)?;
    let read_only_after_reloc = ELFReadOnlyAfterRelocationsOption.check(parser, options)?;
    let immediate_bind = ELFImmediateBindingOption.check(parser, options)?;

    let mut result = vec![
        supports_address_space_layout_randomization,
        has_stack_protection,
        stack_must_be_executable,
        supports_shadow_stack,
        guarded_control_stack,
        branch_target_identification,
        read_only_after_reloc,
        immediate_bind,
    ];

    if !options.no_libc {
        let fortify_source =
            ELFFortifySourceOption::new(options.libc_spec).check(parser, options)?;
        result.push(fortify_source);
    }

    Ok(result)
}

pub(crate) fn get_libc_functions_by_protection<'t>(
    elf: &goblin::elf::Elf,
    libc_ref: &'t NeededLibC,
) -> (HashSet<&'t str>, HashSet<&'t str>) {
    let imported_functions = elf
        .dynsyms
        .iter()
        .filter_map(|symbol| dynamic_symbol_is_named_imported_function(elf, &symbol));

    let mut protected_functions = HashSet::<&str>::default();
    let mut unprotected_functions = HashSet::<&str>::default();
    for imported_function in imported_functions {
        if function_is_checked_version(imported_function) {
            if let Some(unchecked_function) = libc_ref.exports_function(imported_function) {
                protected_functions.insert(unchecked_function);
            } else {
                warn!(
                    "Checked function '{imported_function}' is not exported by \
                    the C runtime library. This might indicate a C runtime mismatch."
                );
            }
        } else if let Some(unchecked_function) =
            libc_ref.exports_checked_version_of_function(imported_function)
        {
            unprotected_functions.insert(unchecked_function);
        }
    }

    (protected_functions, unprotected_functions)
}

/// [`ET_EXEC`, `ET_DYN`, `PT_PHDR`](http://refspecs.linux-foundation.org/elf/TIS1.1.pdf).
pub(crate) fn supports_aslr(elf: &goblin::elf::Elf) -> ASLRCompatibilityLevel {
    debug!(
        "Header type is 'ET_{}'.",
        goblin::elf::header::et_to_str(elf.header.e_type)
    );

    match elf.header.e_type {
        goblin::elf::header::ET_EXEC => {
            // Position-dependent executable.
            ASLRCompatibilityLevel::Unsupported
        }

        goblin::elf::header::ET_DYN => {
            if log_enabled!(log::Level::Debug) {
                if elf
                    .program_headers
                    .iter()
                    .any(|ph| ph.p_type == goblin::elf::program_header::PT_PHDR)
                {
                    // Position-independent executable.
                    debug!("Found type 'PT_PHDR' inside program headers section.");
                } else if let Some(dynamic_section) = elf.dynamic.as_ref() {
                    let dynamic_section_flags_include_pie = dynamic_section.dyns.iter().any(|e| {
                        (e.d_tag == goblin::elf::dynamic::DT_FLAGS_1) && ((e.d_val & DF_1_PIE) != 0)
                    });

                    if dynamic_section_flags_include_pie {
                        // Position-independent executable.
                        debug!(
                            "Bit 'DF_1_PIE' is set in tag 'DT_FLAGS_1' inside \
                            dynamic linking information."
                        );
                    } else {
                        // Shared library.
                        debug!("Binary is a shared library with dynamic linking information.");
                    }
                } else {
                    // Shared library.
                    debug!("Binary is a shared library without dynamic linking information.");
                }
            }

            ASLRCompatibilityLevel::Supported
        }

        _ => {
            debug!("Position-independence could not be determined.");
            ASLRCompatibilityLevel::Unknown
        }
    }
}

/// [PT_GNU_RELRO](http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/progheader.html).
pub(crate) fn becomes_read_only_after_relocations(elf: &goblin::elf::Elf) -> bool {
    let r = elf
        .program_headers
        .iter()
        .any(|ph| ph.p_type == goblin::elf::program_header::PT_GNU_RELRO);

    if r {
        debug!("Found type 'PT_GNU_RELRO' inside program headers section.");
    }
    r
}

/// [PT_GNU_STACK](http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/progheader.html).
pub(crate) fn stack_must_be_executable(elf: &goblin::elf::Elf) -> bool {
    // The p_flags member specifies the permissions on the segment containing the stack
    // and is used to indicate wether the stack should be executable.
    // The absense of this header indicates that the stack will be executable.

    if let Some(ph) = elf
        .program_headers
        .iter()
        .find(|ph| ph.p_type == goblin::elf::program_header::PT_GNU_STACK)
    {
        let predicate = (ph.p_flags & goblin::elf::program_header::PF_X) != 0;

        debug!(
            "Found type 'PT_GNU_STACK' inside program headers section. \
             The stack must{} be executable.",
            if predicate { "" } else { " not" }
        );
        predicate
    } else {
        debug!(
            "Did not find type 'PT_GNU_STACK' inside program headers section. \
             The stack must be executable."
        );
        true
    }
}

/// Control flow protection against return-oriented programming.
pub(crate) fn supports_shadow_stack(elf: &goblin::elf::Elf, bytes: &[u8]) -> Result<bool> {
    let properties = GNUProperty::parse_all(elf, bytes)?;

    Ok(properties
        .into_iter()
        .filter_map(|property| {
            if let GNUProperty::X86Feature1And(feature) = property {
                Some(feature)
            } else {
                None
            }
        })
        .any(|feature| feature.contains(GNUPropertyX86Feature1::SHSTK)))
}

/// Control flow protection against return-oriented programming.
pub(crate) fn branch_target_identification(elf: &goblin::elf::Elf, bytes: &[u8]) -> Result<bool> {
    let properties = GNUProperty::parse_all(elf, bytes)?;

    Ok(properties
        .into_iter()
        .filter_map(|property| match property {
            GNUProperty::X86Feature1And(feature) => {
                Some(feature.contains(GNUPropertyX86Feature1::IBT))
            }

            GNUProperty::AARCH64Feature1And(feature) => {
                Some(feature.contains(GNUPropertyAArch64Feature1::BTI))
            }

            GNUProperty::StackSize(_)
            | GNUProperty::NoCopyOnProtected
            | GNUProperty::ProcessorSpecific(_)
            | GNUProperty::UserSpecific(_)
            | GNUProperty::X86UInt32And(_)
            | GNUProperty::X86Feature2Used(_)
            | GNUProperty::X86UInt32OrAnd(_)
            | GNUProperty::X86Feature2Needed(_)
            | GNUProperty::X86UInt32Or(_)
            | GNUProperty::X86ISA1Used(_)
            | GNUProperty::X86ISA1Needed(_)
            | GNUProperty::AARCH64FeaturePAuth(_) => None,
        })
        .any(|feature| feature))
}

/// Control flow protection against return-oriented programming.
pub(crate) fn guarded_control_stack(elf: &goblin::elf::Elf, bytes: &[u8]) -> Result<bool> {
    let properties = GNUProperty::parse_all(elf, bytes)?;

    Ok(properties
        .into_iter()
        .filter_map(|property| {
            if let GNUProperty::AARCH64Feature1And(feature) = property {
                Some(feature)
            } else {
                None
            }
        })
        .any(|feature| feature.contains(GNUPropertyAArch64Feature1::GCS)))
}

/// [`__stack_chk_fail`](http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/baselib---stack-chk-fail-1.html).
pub(crate) fn has_stack_protection(elf: &goblin::elf::Elf) -> bool {
    let r = elf
        .dynsyms
        .iter()
        // Consider only named functions, and focus on their names.
        .filter_map(|symbol| dynamic_symbol_is_named_function(elf, &symbol))
        // Check if any function name corresponds to '__stack_chk_fail'.
        .any(|name| name == "__stack_chk_fail");

    if r {
        debug!("Found function symbol '__stack_chk_fail' inside dynamic symbols section.");
    }
    r
}

/// Visibility is specified by binding type.
const STV_DEFAULT: u8 = 0;
// Defined by processor supplements.
//const STV_INTERNAL: u8 = 1;
// Not visible to other components.
//const STV_HIDDEN: u8 = 2;
// Visible in other components but not preemptable.
//const STV_PROTECTED: u8 = 3;

pub(crate) fn dynamic_symbol_is_named_exported_function<'elf>(
    elf: &'elf goblin::elf::Elf,
    symbol: &goblin::elf::sym::Sym,
) -> Option<&'elf str> {
    // Visibility must be STV_DEFAULT.
    if symbol.st_other == STV_DEFAULT {
        // Type must be STT_FUNC or STT_GNU_IFUNC.
        let st_type = symbol.st_type();
        if st_type == goblin::elf::sym::STT_FUNC || st_type == goblin::elf::sym::STT_GNU_IFUNC {
            // Binding must be STB_GLOBAL or BSF_WEAK or STB_GNU_UNIQUE.
            // Value must not be zero.
            let st_bind = symbol.st_bind();
            if (st_bind == goblin::elf::sym::STB_GLOBAL
                || st_bind == goblin::elf::sym::STB_WEAK
                || st_bind == goblin::elf::sym::STB_GNU_UNIQUE)
                && (symbol.st_value != 0)
            {
                return elf
                    .dynstrtab
                    .get_at(symbol.st_name)
                    .filter(|name| !name.is_empty()); // Only consider non-empty names.
            }
        }
    }
    None
}

/// Position Independent Executable.
pub(crate) const DF_1_PIE: u64 = 0x08_00_00_00;

pub(crate) fn symbol_is_named_function_or_unspecified<'elf>(
    elf: &'elf goblin::elf::Elf,
    symbol: &goblin::elf::sym::Sym,
) -> Option<&'elf str> {
    // Type must be STT_FUNC or STT_GNU_IFUNC or STT_NOTYPE.
    let st_type = symbol.st_type();
    if st_type == goblin::elf::sym::STT_FUNC
        || st_type == goblin::elf::sym::STT_GNU_IFUNC
        || st_type == goblin::elf::sym::STT_NOTYPE
    {
        elf.strtab
            .get_at(symbol.st_name)
            .filter(|name| !name.is_empty()) // Only consider non-empty names.
    } else {
        None
    }
}

fn dynamic_symbol_is_named_function<'elf>(
    elf: &'elf goblin::elf::Elf,
    symbol: &goblin::elf::sym::Sym,
) -> Option<&'elf str> {
    // Type must be STT_FUNC or STT_GNU_IFUNC.
    let st_type = symbol.st_type();
    if st_type == goblin::elf::sym::STT_FUNC || st_type == goblin::elf::sym::STT_GNU_IFUNC {
        elf.dynstrtab
            .get_at(symbol.st_name)
            .filter(|name| !name.is_empty()) // Only consider non-empty names.
    } else {
        None
    }
}

fn dynamic_symbol_is_named_imported_function<'elf>(
    elf: &'elf goblin::elf::Elf,
    symbol: &goblin::elf::sym::Sym,
) -> Option<&'elf str> {
    // Type must be STT_FUNC or STT_GNU_IFUNC.
    let st_type = symbol.st_type();
    if st_type == goblin::elf::sym::STT_FUNC || st_type == goblin::elf::sym::STT_GNU_IFUNC {
        // Binding must be STB_GLOBAL or BSF_WEAK or STB_GNU_UNIQUE.
        // Value must be zero.
        let st_bind = symbol.st_bind();
        if (st_bind == goblin::elf::sym::STB_GLOBAL
            || st_bind == goblin::elf::sym::STB_WEAK
            || st_bind == goblin::elf::sym::STB_GNU_UNIQUE)
            && (symbol.st_value == 0)
        {
            return elf
                .dynstrtab
                .get_at(symbol.st_name)
                .filter(|name| !name.is_empty()); // Only consider non-empty names.
        }
    }
    None
}

/// - [`DT_BIND_NOW`](http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dynamicsection.html).
/// - [`DF_BIND_NOW`, `DF_1_NOW`](http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/libc-ddefs.html).
pub(crate) fn requires_immediate_binding(elf: &goblin::elf::Elf) -> bool {
    elf.dynamic
        // We want to reference the data in `elf.dynamic`, not move it.
        .as_ref()
        .and_then(|dli| {
            // We have dynamic linking information.
            // Find the first entry that requires immediate binding.
            dli.dyns
                .iter()
                .find(|dyn_entry| dynamic_linking_info_entry_requires_immediate_binding(dyn_entry))
        })
        .is_some()
}

fn dynamic_linking_info_entry_requires_immediate_binding(
    dyn_entry: &goblin::elf::dynamic::Dyn,
) -> bool {
    match dyn_entry.d_tag {
        goblin::elf::dynamic::DT_BIND_NOW => {
            debug!("Found tag 'DT_BIND_NOW' inside dynamic linking information.");
            true
        }

        goblin::elf::dynamic::DT_FLAGS => {
            let r = (dyn_entry.d_val & goblin::elf::dynamic::DF_BIND_NOW) != 0;
            if r {
                debug!(
                    "Bit 'DF_BIND_NOW' is set in tag 'DT_FLAGS' inside \
                    dynamic linking information."
                );
            }
            r
        }

        goblin::elf::dynamic::DT_FLAGS_1 => {
            let r = (dyn_entry.d_val & goblin::elf::dynamic::DF_1_NOW) != 0;
            if r {
                debug!(
                    "Bit 'DF_1_NOW' is set in tag 'DT_FLAGS_1' inside \
                    dynamic linking information."
                );
            }
            r
        }

        _ => false,
    }
}