evectl 0.1.0-alpha.8

EveCtl with Suricata and EveBox
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
// SPDX-FileCopyrightText: (C) 2021 Jason Ish <jason@codemonkey.net>
// SPDX-License-Identifier: MIT

use crate::prelude::*;

use serde::Deserialize;
use std::process::Command;

pub const DEFAULT_SURICATA_IMAGE: &str = "docker.io/jasonish/suricata:latest";
pub const DEFAULT_EVEBOX_IMAGE: &str = "docker.io/jasonish/evebox:master";

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum ContainerManager {
    Docker(DockerManager),
    Podman(PodmanManager),
}

impl std::fmt::Display for ContainerManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            ContainerManager::Docker(_) => "Docker",
            ContainerManager::Podman(_) => "Podman",
        };
        write!(f, "{name}")
    }
}

impl ContainerManager {
    pub(crate) fn command(&self) -> Command {
        Command::new(self.bin())
    }

    pub(crate) fn bin(&self) -> &str {
        match self {
            Self::Docker(docker) => docker.bin(),
            Self::Podman(podman) => podman.bin(),
        }
    }

    /// Test if a container manager exists.
    pub(crate) fn exists(&self) -> bool {
        Command::new(self.bin())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok()
    }

    /// Return true if the container manager is Podman.
    pub(crate) fn is_podman(&self) -> bool {
        matches!(self, ContainerManager::Podman(_))
    }

    /// Return true if the container manager is Docker.
    pub(crate) fn is_docker(&self) -> bool {
        matches!(self, ContainerManager::Docker(_))
    }

    pub(crate) fn version(&self) -> Result<String> {
        let output = self
            .command()
            .args(["version", "--format", "{{json . }}"])
            .output()?;
        if !output.status.success() {
            bail!(String::from_utf8_lossy(&output.stderr).to_string());
        } else if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&output.stdout) {
            if let Some(version) = json["Client"]["Version"].as_str() {
                return Ok(version.to_string());
            }
            if let Some(version) = json["Version"].as_str() {
                return Ok(version.to_string());
            }
        }
        bail!(
            "Failed to find {} version in output: {}",
            self.to_string(),
            String::from_utf8_lossy(&output.stdout).to_string()
        );
    }

    /// Quietly remove container.
    pub(crate) fn quiet_rm(&self, name: &str) {
        let mut args = vec!["rm"];

        // Podman needs to be a little more agressive here.
        if self.is_podman() {
            args.push("--force");
        }

        args.push(name);
        let _ = self.command().args(&args).output();
    }

    pub(crate) fn stop(&self, name: &str, signal: Option<&str>) -> Result<()> {
        let mut cmd = self.command();
        cmd.arg("stop");

        // Custom stop signals are not supported on Podman.
        if self.is_docker() {
            cmd.args(["--signal", signal.unwrap_or("SIGTERM")]);
        }
        cmd.arg(name);
        let output = cmd.output()?;
        if !output.status.success() {
            bail!(String::from_utf8_lossy(&output.stderr).to_string());
        }
        Ok(())
    }

    pub(crate) fn pull(&self, image: &str) -> Result<()> {
        let status = self.command().args(["pull", image]).status()?;
        if status.success() {
            Ok(())
        } else {
            bail!("Pull did not exit successfully")
        }
    }

    pub(crate) fn inspect_first(&self, name: &str) -> Result<InspectEntry> {
        let mut command = self.command();
        command.args(["inspect", name]);
        let mut entries: Vec<InspectEntry> = command_json(&mut command)?;
        if entries.is_empty() {
            bail!("{} returned unexpected empty inspect array", self);
        } else {
            Ok(entries.swap_remove(0))
        }
    }

    pub(crate) fn has_image(&self, name: &str) -> bool {
        self.inspect_first(name).is_ok()
    }

    pub(crate) fn is_running(&self, name: &str) -> bool {
        if let Ok(state) = self.state(name) {
            return state.running;
        }
        false
    }

    /// Return the Inspect.State object for a container.
    ///
    /// If the container doesn't exist an error is returned.
    pub(crate) fn state(&self, name: &str) -> Result<InspectState> {
        match self.inspect_first(name)?.state {
            Some(state) => Ok(state),
            None => bail!("not a container"),
        }
    }

    /// Test if a container exists.
    ///
    /// Any failure results in false.
    pub(crate) fn container_exists(&self, name: &str) -> bool {
        if let Ok(output) = self.command().args(["inspect", name]).output() {
            return output.status.success();
        }
        false
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) struct PodmanManager {}

impl PodmanManager {
    pub(crate) fn new() -> Self {
        Self {}
    }

    pub(crate) fn bin(&self) -> &str {
        "podman"
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) struct DockerManager {}

impl DockerManager {
    pub(crate) fn new() -> Self {
        Self {}
    }

    pub(crate) fn bin(&self) -> &str {
        "docker"
    }
}

/// Command extensions useful for containers.
pub(crate) trait CommandExt {
    /// Like `Command::output`, but return an error on command failure
    /// as well as non-successful exit code.
    fn status_output(&mut self) -> anyhow::Result<Vec<u8>>;

    /// Like `Command::status` but will also fail if the command did
    /// not exit successfully.
    fn status_ok(&mut self) -> Result<()>;
}

impl CommandExt for std::process::Command {
    fn status_output(&mut self) -> Result<Vec<u8>> {
        let output = self.output()?;
        if output.status.success() {
            Ok(output.stdout)
        } else {
            bail!(String::from_utf8_lossy(&output.stderr).to_string())
        }
    }

    fn status_ok(&mut self) -> Result<()> {
        let status = self.status()?;
        if status.success() {
            Ok(())
        } else {
            bail!("Failed with exit code {:?}", status.code())
        }
    }
}

#[derive(Debug, Deserialize)]
pub(crate) struct InspectEntry {
    #[serde(rename = "Id")]
    _id: String,

    // Only found when inspecting containers.
    #[serde(rename = "State")]
    state: Option<InspectState>,

    // Only found when inspecting images.
    #[serde(rename = "RepoTags")]
    _repo_tags: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct InspectState {
    #[serde(rename = "Status")]
    pub _status: String,

    #[serde(rename = "Running")]
    pub running: bool,

    #[serde(rename = "Error")]
    pub _error: String,

    #[serde(rename = "ExitCode")]
    pub _exit_code: i32,
}

fn command_json<T>(command: &mut Command) -> Result<T>
where
    T: serde::de::DeserializeOwned + std::fmt::Debug,
{
    let output = command.output()?;
    if !output.status.success() {
        if output.stderr.is_empty() {
            bail!("Command failed with no stderr output");
        } else {
            bail!(String::from_utf8_lossy(&output.stderr).to_string());
        }
    } else {
        Ok(serde_json::from_slice(&output.stdout)?)
    }
}

pub(crate) fn find_manager(podman: bool) -> Option<ContainerManager> {
    if !podman {
        debug!("Looking for Docker container engine");

        let manager = ContainerManager::Docker(DockerManager::new());
        if manager.exists() {
            info!("Found Docker container engine");
            if let Ok(version) = manager.version() {
                debug!("Found Docker version {version}");
                return Some(manager);
            }
        } else {
            info!("Docker not found");
        }
    };

    debug!("Looking for Podman container engine");
    let manager = ContainerManager::Podman(PodmanManager::new());
    if manager.exists() {
        info!("Found Podman container engine");
        if let Ok(version) = manager.version() {
            debug!("Found Podman version {version}");
            match semver::Version::parse(&version) {
                Ok(version) => {
                    if version.major < 4 || (version.major == 4 && version.minor < 6) {
                        error!("Podman version must be at least 4.7.0");
                    } else {
                        return Some(manager);
                    }
                }
                Err(_) => {
                    error!("Failed to parse Podman version");
                }
            }
        }
    } else {
        info!("Podman not found");
    }

    None
}

#[derive(Debug)]
pub(crate) enum Container {
    Suricata,
    EveBox,
}

pub(crate) struct SuricataContainer {
    context: Context,
}

impl SuricataContainer {
    pub(crate) fn new(context: Context) -> Self {
        Self { context }
    }

    pub(crate) fn volumes(&self) -> Vec<String> {
        let libdir = self.context.config_dir().join("suricata").join("lib");
        let logdir = self.context.data_dir().join("suricata").join("log");
        let rundir = self.context.data_dir().join("suricata").join("run");

        let volumes = vec![
            format!("{}:/var/log/suricata", logdir.display()),
            format!("{}:/var/lib/suricata", libdir.display()),
            format!("{}:/var/run/suricata", rundir.display()),
        ];
        volumes
    }

    pub(crate) fn run(&self) -> RunCommandBuilder {
        let mut builder = RunCommandBuilder::new(
            self.context.manager,
            self.context.image_name(Container::Suricata),
        );
        builder.volumes(&self.volumes());
        builder
    }
}

pub(crate) struct RunCommandBuilder {
    manager: ContainerManager,
    image: String,
    rm: bool,
    it: bool,
    volumes: Vec<String>,
    name: Option<String>,
    args: Vec<String>,
    user: Option<String>,
}

impl RunCommandBuilder {
    pub(crate) fn new(manager: ContainerManager, image: impl ToString) -> Self {
        Self {
            manager,
            image: image.to_string(),
            rm: false,
            it: false,
            volumes: vec![],
            name: None,
            args: vec![],
            user: None,
        }
    }

    pub(crate) fn rm(&mut self) -> &mut Self {
        self.rm = true;
        self
    }

    pub(crate) fn it(&mut self) -> &mut Self {
        self.it = true;
        self
    }

    pub(crate) fn args(&mut self, args: &[impl ToString]) -> &mut Self {
        for arg in args {
            self.args.push(arg.to_string());
        }
        self
    }

    pub(crate) fn volumes(&mut self, volumes: &[impl ToString]) -> &mut Self {
        for volume in volumes {
            self.volumes.push(volume.to_string());
        }
        self
    }

    pub(crate) fn build(&self) -> Command {
        let mut command = self.manager.command();
        command.arg("run");
        if self.it {
            command.arg("-it");
        }
        if self.rm {
            command.arg("--rm");
        }
        if let Some(name) = &self.name {
            command.arg(format!("--name={}", name));
        }
        for volume in &self.volumes {
            command.arg(format!("--volume={}", volume));
        }
        if let Some(user) = &self.user {
            command.arg(format!("--user={}", user));
        }
        command.arg(&self.image);
        command.args(&self.args);
        command
    }
}