elf_runner/
config.rs

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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::error::ProgramError;
use ::routing::policy::ScopedPolicyChecker;
use fidl_fuchsia_data as fdata;
use runner::StartInfoProgramError;

const CREATE_RAW_PROCESSES_KEY: &str = "job_policy_create_raw_processes";
const SHARED_PROCESS_KEY: &str = "is_shared_process";
const CRITICAL_KEY: &str = "main_process_critical";
const FORWARD_STDOUT_KEY: &str = "forward_stdout_to";
const FORWARD_STDERR_KEY: &str = "forward_stderr_to";
const VMEX_KEY: &str = "job_policy_ambient_mark_vmo_exec";
const STOP_EVENT_KEY: &str = "lifecycle.stop_event";
const STOP_EVENT_VARIANTS: [&'static str; 2] = ["notify", "ignore"];
const USE_NEXT_VDSO_KEY: &str = "use_next_vdso";
const JOB_WITH_AVAILABLE_EXCEPTION_CHANNEL_KEY: &str = "job_with_available_exception_channel";
const MEMORY_ATTRIBUTION: &str = "memory_attribution";

/// Target sink for stdout and stderr output streams.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StreamSink {
    /// The component omitted configuration or explicitly requested forwarding to the log.
    Log,
    /// The component requested to not forward to the log.
    None,
}

impl Default for StreamSink {
    fn default() -> Self {
        StreamSink::Log
    }
}

/// Parsed representation of the `ComponentStartInfo.program` dictionary.
#[derive(Debug, Default, Eq, PartialEq, Clone)]
pub struct ElfProgramConfig {
    pub binary: String,
    pub args: Vec<String>,
    pub notify_lifecycle_stop: bool,
    pub ambient_mark_vmo_exec: bool,
    pub main_process_critical: bool,
    pub create_raw_processes: bool,
    pub is_shared_process: bool,
    pub use_next_vdso: bool,
    pub job_with_available_exception_channel: bool,
    pub memory_attribution: bool,
    pub stdout_sink: StreamSink,
    pub stderr_sink: StreamSink,
    pub environ: Option<Vec<String>>,
}

impl ElfProgramConfig {
    /// Parse the given dictionary into an ElfProgramConfig, checking it against security policy as
    /// needed.
    ///
    /// Checking against security policy is intentionally combined with parsing here, so that policy
    /// enforcement is as close to the point of parsing as possible and can't be inadvertently skipped.
    pub fn parse_and_check(
        program: &fdata::Dictionary,
        checker: &ScopedPolicyChecker,
    ) -> Result<Self, ProgramError> {
        let config = Self::parse(program).map_err(ProgramError::Parse)?;

        if config.ambient_mark_vmo_exec {
            checker.ambient_mark_vmo_exec_allowed().map_err(ProgramError::Policy)?;
        }

        if config.main_process_critical {
            checker.main_process_critical_allowed().map_err(ProgramError::Policy)?;
        }

        if config.create_raw_processes {
            checker.create_raw_processes_allowed().map_err(ProgramError::Policy)?;
        }

        if config.is_shared_process && !config.create_raw_processes {
            return Err(ProgramError::SharedProcessRequiresJobPolicy);
        }

        Ok(config)
    }

    // Parses a `program` dictionary but does not check policy or consistency.
    fn parse(program: &fdata::Dictionary) -> Result<Self, StartInfoProgramError> {
        let notify_lifecycle_stop =
            match runner::get_enum(program, STOP_EVENT_KEY, &STOP_EVENT_VARIANTS)? {
                Some("notify") => true,
                _ => false,
            };

        Ok(ElfProgramConfig {
            binary: runner::get_program_binary_from_dict(&program)?,
            args: runner::get_program_args_from_dict(&program)?,
            notify_lifecycle_stop,
            ambient_mark_vmo_exec: runner::get_bool(program, VMEX_KEY)?,
            main_process_critical: runner::get_bool(program, CRITICAL_KEY)?,
            create_raw_processes: runner::get_bool(program, CREATE_RAW_PROCESSES_KEY)?,
            is_shared_process: runner::get_bool(program, SHARED_PROCESS_KEY)?,
            use_next_vdso: runner::get_bool(program, USE_NEXT_VDSO_KEY)?,
            job_with_available_exception_channel: runner::get_bool(
                program,
                JOB_WITH_AVAILABLE_EXCEPTION_CHANNEL_KEY,
            )?,
            memory_attribution: runner::get_bool(program, MEMORY_ATTRIBUTION)?,
            stdout_sink: get_stream_sink(&program, FORWARD_STDOUT_KEY)?,
            stderr_sink: get_stream_sink(&program, FORWARD_STDERR_KEY)?,
            environ: runner::get_environ(&program)?,
        })
    }

    pub fn process_options(&self) -> zx::ProcessOptions {
        if self.is_shared_process {
            zx::ProcessOptions::SHARED
        } else {
            zx::ProcessOptions::empty()
        }
    }
}

fn get_stream_sink(
    dict: &fdata::Dictionary,
    key: &str,
) -> Result<StreamSink, StartInfoProgramError> {
    match runner::get_enum(dict, key, &["log", "none"])? {
        Some("log") => Ok(StreamSink::Log),
        Some("none") => Ok(StreamSink::None),
        Some(_) => unreachable!("get_enum returns only values in variants"),
        None => Ok(StreamSink::default()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ::routing::policy::PolicyError;
    use assert_matches::assert_matches;
    use cm_config::{
        AllowlistEntryBuilder, ChildPolicyAllowlists, JobPolicyAllowlists, SecurityPolicy,
    };
    use fidl_fuchsia_data as fdata;
    use lazy_static::lazy_static;
    use moniker::Moniker;
    use std::collections::HashMap;
    use std::sync::Arc;
    use test_case::test_case;

    const BINARY_KEY: &str = "binary";
    const TEST_BINARY: &str = "test_binary";

    lazy_static! {
        static ref TEST_MONIKER: Moniker = Moniker::root();
        static ref PERMISSIVE_SECURITY_POLICY: Arc<SecurityPolicy> = Arc::new(SecurityPolicy {
            job_policy: JobPolicyAllowlists {
                ambient_mark_vmo_exec: vec![AllowlistEntryBuilder::build_exact_from_moniker(
                    &TEST_MONIKER
                ),],
                main_process_critical: vec![AllowlistEntryBuilder::build_exact_from_moniker(
                    &TEST_MONIKER
                ),],
                create_raw_processes: vec![AllowlistEntryBuilder::build_exact_from_moniker(
                    &TEST_MONIKER
                ),],
            },
            capability_policy: HashMap::new(),
            debug_capability_policy: HashMap::new(),
            child_policy: ChildPolicyAllowlists { reboot_on_terminate: vec![] },
        });
        static ref RESTRICTIVE_SECURITY_POLICY: Arc<SecurityPolicy> =
            Arc::new(SecurityPolicy::default());
    }

    #[test_case("forward_stdout_to", new_string("log"), ElfProgramConfig { stdout_sink: StreamSink::Log, ..default_valid_config()} ; "when_stdout_log")]
    #[test_case("forward_stdout_to", new_string("none"), ElfProgramConfig { stdout_sink: StreamSink::None, ..default_valid_config()} ; "when_stdout_none")]
    #[test_case("forward_stderr_to", new_string("log"), ElfProgramConfig { stderr_sink: StreamSink::Log, ..default_valid_config()} ; "when_stderr_log")]
    #[test_case("forward_stderr_to", new_string("none"), ElfProgramConfig { stderr_sink: StreamSink::None, ..default_valid_config()} ; "when_stderr_none")]
    #[test_case("environ", new_empty_vec(), ElfProgramConfig { environ: None, ..default_valid_config()} ; "when_environ_empty")]
    #[test_case("environ", new_vec(vec!["FOO=BAR"]), ElfProgramConfig { environ: Some(vec!["FOO=BAR".into()]), ..default_valid_config()} ; "when_environ_has_values")]
    #[test_case("lifecycle.stop_event", new_string("notify"), ElfProgramConfig { notify_lifecycle_stop: true, ..default_valid_config()} ; "when_stop_event_notify")]
    #[test_case("lifecycle.stop_event", new_string("ignore"), ElfProgramConfig { notify_lifecycle_stop: false, ..default_valid_config()} ; "when_stop_event_ignore")]
    #[test_case("main_process_critical", new_string("true"), ElfProgramConfig { main_process_critical: true, ..default_valid_config()} ; "when_main_process_critical_true")]
    #[test_case("main_process_critical", new_string("false"), ElfProgramConfig { main_process_critical: false, ..default_valid_config()} ; "when_main_process_critical_false")]
    #[test_case("job_policy_ambient_mark_vmo_exec", new_string("true"), ElfProgramConfig { ambient_mark_vmo_exec: true, ..default_valid_config()} ; "when_ambient_mark_vmo_exec_true")]
    #[test_case("job_policy_ambient_mark_vmo_exec", new_string("false"), ElfProgramConfig { ambient_mark_vmo_exec: false, ..default_valid_config()} ; "when_ambient_mark_vmo_exec_false")]
    #[test_case("job_policy_create_raw_processes", new_string("true"), ElfProgramConfig { create_raw_processes: true, ..default_valid_config()} ; "when_create_raw_processes_true")]
    #[test_case("job_policy_create_raw_processes", new_string("false"), ElfProgramConfig { create_raw_processes: false, ..default_valid_config()} ; "when_create_raw_processes_false")]
    #[test_case("use_next_vdso", new_string("true"), ElfProgramConfig { use_next_vdso: true, ..default_valid_config()} ; "use_next_vdso_true")]
    #[test_case("use_next_vdso", new_string("false"), ElfProgramConfig { use_next_vdso: false, ..default_valid_config()} ; "use_next_vdso_false")]
    fn test_parse_and_check_with_permissive_policy(
        key: &str,
        value: fdata::DictionaryValue,
        expected: ElfProgramConfig,
    ) {
        let checker =
            ScopedPolicyChecker::new(PERMISSIVE_SECURITY_POLICY.clone(), TEST_MONIKER.clone());
        let program = new_program_stanza(key, value);

        let actual = ElfProgramConfig::parse_and_check(&program, &checker).unwrap();

        assert_eq!(actual, expected);
    }

    #[test_case("job_policy_ambient_mark_vmo_exec", new_string("true") , "ambient_mark_vmo_exec" ; "when_ambient_mark_vmo_exec_true")]
    #[test_case("main_process_critical", new_string("true"), "main_process_critical" ; "when_main_process_critical_true")]
    #[test_case("job_policy_create_raw_processes", new_string("true"), "create_raw_processes" ; "when_create_raw_processes_true")]
    fn test_parse_and_check_with_restrictive_policy(
        key: &str,
        value: fdata::DictionaryValue,
        policy: &str,
    ) {
        let checker =
            ScopedPolicyChecker::new(RESTRICTIVE_SECURITY_POLICY.clone(), TEST_MONIKER.clone());
        let program = new_program_stanza(key, value);

        let actual = ElfProgramConfig::parse_and_check(&program, &checker);

        assert_matches!(
            actual,
            Err(ProgramError::Policy(PolicyError::JobPolicyDisallowed {
                policy: p,
                ..
            }))
            if p == policy
        );
    }

    #[test_case("lifecycle.stop_event", new_string("invalid") ; "for_stop_event")]
    #[test_case("environ", new_empty_string() ; "for_environ")]
    fn test_parse_and_check_with_invalid_value(key: &str, value: fdata::DictionaryValue) {
        // Use a permissive policy because we want to fail *iff* value set for
        // key is invalid.
        let checker =
            ScopedPolicyChecker::new(PERMISSIVE_SECURITY_POLICY.clone(), TEST_MONIKER.clone());
        let program = new_program_stanza(key, value);

        let actual = ElfProgramConfig::parse_and_check(&program, &checker);

        assert_matches!(
            actual,
            Err(ProgramError::Parse(StartInfoProgramError::InvalidValue(k, _, _)))
            if k == key
        );
    }

    #[test_case("lifecycle.stop_event", new_empty_vec() ; "for_stop_event")]
    #[test_case("job_policy_ambient_mark_vmo_exec", new_empty_vec() ; "for_ambient_mark_vmo_exec")]
    #[test_case("main_process_critical", new_empty_vec() ; "for_main_process_critical")]
    #[test_case("job_policy_create_raw_processes", new_empty_vec() ; "for_create_raw_processes")]
    #[test_case("forward_stdout_to", new_empty_vec() ; "for_stdout")]
    #[test_case("forward_stderr_to", new_empty_vec() ; "for_stderr")]
    #[test_case("use_next_vdso", new_empty_vec() ; "for_use_next_vdso")]
    fn test_parse_and_check_with_invalid_type(key: &str, value: fdata::DictionaryValue) {
        // Use a permissive policy because we want to fail *iff* value set for
        // key is invalid.
        let checker =
            ScopedPolicyChecker::new(PERMISSIVE_SECURITY_POLICY.clone(), TEST_MONIKER.clone());
        let program = new_program_stanza(key, value);

        let actual = ElfProgramConfig::parse_and_check(&program, &checker);

        assert_matches!(
            actual,
            Err(ProgramError::Parse(StartInfoProgramError::InvalidType(k)))
            if k == key
        );
    }

    fn default_valid_config() -> ElfProgramConfig {
        ElfProgramConfig { binary: TEST_BINARY.to_string(), args: Vec::new(), ..Default::default() }
    }

    fn new_program_stanza(key: &str, value: fdata::DictionaryValue) -> fdata::Dictionary {
        fdata::Dictionary {
            entries: Some(vec![
                fdata::DictionaryEntry {
                    key: BINARY_KEY.to_owned(),
                    value: Some(Box::new(new_string(TEST_BINARY))),
                },
                fdata::DictionaryEntry { key: key.to_owned(), value: Some(Box::new(value)) },
            ]),
            ..Default::default()
        }
    }

    fn new_string(value: &str) -> fdata::DictionaryValue {
        fdata::DictionaryValue::Str(value.to_owned())
    }

    fn new_vec(values: Vec<&str>) -> fdata::DictionaryValue {
        fdata::DictionaryValue::StrVec(values.into_iter().map(str::to_owned).collect())
    }

    fn new_empty_string() -> fdata::DictionaryValue {
        fdata::DictionaryValue::Str("".to_owned())
    }

    fn new_empty_vec() -> fdata::DictionaryValue {
        fdata::DictionaryValue::StrVec(vec![])
    }
}