ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
//! Kernel runtime parameters monitoring.
//!
//! Reads and categorizes sysctl / kernel parameters covering networking,
//! memory, security, and performance tuning. Provides analysis of
//! parameters that differ from recommended defaults and security
//! hardening assessment.
//!
//! ## Platform Support
//!
//! - **Linux**: `/proc/sys/` hierarchy, sysctl
//! - **Windows**: Registry-based kernel tuning
//! - **macOS**: sysctl parameters

use crate::error::IronError;
use serde::{Deserialize, Serialize};

/// Parameter category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ParamCategory {
    Network,
    Memory,
    Security,
    FileSystem,
    Kernel,
    Vm,
    Debug,
    Unknown,
}

impl std::fmt::Display for ParamCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Network => write!(f, "Network"),
            Self::Memory => write!(f, "Memory"),
            Self::Security => write!(f, "Security"),
            Self::FileSystem => write!(f, "Filesystem"),
            Self::Kernel => write!(f, "Kernel"),
            Self::Vm => write!(f, "VM/Memory"),
            Self::Debug => write!(f, "Debug"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// A kernel parameter and its value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelParam {
    /// Full parameter path (e.g. "net.ipv4.tcp_syncookies").
    pub name: String,
    /// Current value. `None` when the parameter could not be read. This used to
    /// be the text "N/A", which read as a value.
    pub value: Option<String>,
    /// Category.
    pub category: ParamCategory,
    /// Whether the current value matches recommended. `None` when there is no
    /// value to compare, or nothing to compare it against. An unread parameter
    /// is neither a finding nor a pass.
    pub is_recommended: Option<bool>,
    /// Recommended value (if known).
    pub recommended: Option<String>,
    /// Description.
    pub description: String,
}

/// Kernel parameters analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelParamsReport {
    /// All monitored parameters.
    pub params: Vec<KernelParam>,
    /// Security-relevant parameters.
    pub security_params: Vec<KernelParam>,
    /// Network tuning parameters.
    pub network_params: Vec<KernelParam>,
    /// Memory/VM parameters.
    pub vm_params: Vec<KernelParam>,
    /// Number of non-recommended settings. Unread parameters are not counted.
    pub non_recommended_count: u32,
    /// Security hardening score (0-100). `None` when no security parameter
    /// could be compared against its recommendation. It used to be 0 with no
    /// security parameters and 50 with nothing to compare.
    pub security_score: Option<u32>,
    /// Network tuning score (0-100). `None` under the same condition as
    /// `security_score`.
    pub network_score: Option<u32>,
    /// Recommendations.
    pub recommendations: Vec<String>,
}

/// Kernel parameters monitor.
pub struct KernelParamsMonitor {
    report: KernelParamsReport,
}

/// The TCP auto-tuning level every template agrees on, if they do.
///
/// `Get-NetTCPSetting` returns one row per template rather than one row for the
/// machine, and the reader took `Select-Object -First 1` -- which is the
/// `Automatic` template, the selector, carrying no level of its own and
/// returning an empty line. The other six rows on the development host all say
/// `Normal`, so the ontology reported "no kernel parameter was readable here"
/// about a setting the machine states six times.
///
/// Rows that state nothing are skipped. Rows that disagree describe different
/// destinations rather than one machine-wide level, and `None` is returned
/// rather than one of them being chosen to stand for all -- the answer to
/// "which template applies to this connection" is not this parameter.
#[cfg(target_os = "windows")]
fn agreed_tcp_level(cmdlet_output: &str) -> Option<String> {
    let levels: Vec<&str> = cmdlet_output
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect();
    let first = levels.first()?;
    levels
        .iter()
        .all(|l| l.eq_ignore_ascii_case(first))
        .then(|| (*first).to_string())
}

impl KernelParamsMonitor {
    /// Create a new kernel parameters monitor.
    pub fn new() -> Result<Self, IronError> {
        let report = Self::analyze()?;
        Ok(Self { report })
    }

    /// Refresh.
    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.report = Self::analyze()?;
        Ok(())
    }

    /// Get report.
    pub fn report(&self) -> &KernelParamsReport {
        &self.report
    }

    /// Get a specific parameter by name.
    pub fn param(&self, name: &str) -> Option<&KernelParam> {
        self.report.params.iter().find(|p| p.name == name)
    }

    fn analyze() -> Result<KernelParamsReport, IronError> {
        let params = Self::read_params();

        let security_params: Vec<KernelParam> = params
            .iter()
            .filter(|p| p.category == ParamCategory::Security)
            .cloned()
            .collect();
        let network_params: Vec<KernelParam> = params
            .iter()
            .filter(|p| p.category == ParamCategory::Network)
            .cloned()
            .collect();
        let vm_params: Vec<KernelParam> = params
            .iter()
            .filter(|p| p.category == ParamCategory::Vm || p.category == ParamCategory::Memory)
            .cloned()
            .collect();

        let non_recommended = params
            .iter()
            .filter(|p| p.is_recommended == Some(false) && p.recommended.is_some())
            .count() as u32;

        let security_score = Self::compute_security_score(&security_params);
        let network_score = Self::compute_network_score(&network_params);

        let mut recommendations = Vec::new();
        for p in &params {
            if p.is_recommended == Some(false) {
                if let (Some(ref value), Some(ref rec)) = (&p.value, &p.recommended) {
                    recommendations.push(format!(
                        "{}: current={}, recommended={}",
                        p.name, value, rec
                    ));
                }
            }
        }

        Ok(KernelParamsReport {
            params,
            security_params,
            network_params,
            vm_params,
            non_recommended_count: non_recommended,
            security_score,
            network_score,
            recommendations,
        })
    }

    fn compute_security_score(params: &[KernelParam]) -> Option<u32> {
        Self::score_against_recommended(params)
    }

    fn compute_network_score(params: &[KernelParam]) -> Option<u32> {
        Self::score_against_recommended(params)
    }

    /// Share of judged parameters that match their recommendation. A parameter
    /// is judged only when it was read and has a recommendation to compare to;
    /// with none judged there is nothing to score, so the answer is `None`
    /// rather than a number chosen to look neutral.
    fn score_against_recommended(params: &[KernelParam]) -> Option<u32> {
        let judged: Vec<bool> = params
            .iter()
            .filter(|p| p.recommended.is_some())
            .filter_map(|p| p.is_recommended)
            .collect();
        if judged.is_empty() {
            return None;
        }
        let good = judged.iter().filter(|&&matches| matches).count();
        Some(((good as f64 / judged.len() as f64) * 100.0) as u32)
    }

    #[cfg(target_os = "linux")]
    fn read_params() -> Vec<KernelParam> {
        let checks: Vec<(&str, &str, ParamCategory, &str, &str)> = vec![
            // Security parameters
            (
                "kernel.randomize_va_space",
                "2",
                ParamCategory::Security,
                "ASLR level (0=off, 1=stack, 2=full)",
                "2",
            ),
            (
                "kernel.kptr_restrict",
                "1",
                ParamCategory::Security,
                "Restrict kernel pointer exposure",
                "1",
            ),
            (
                "kernel.dmesg_restrict",
                "1",
                ParamCategory::Security,
                "Restrict dmesg to privileged users",
                "1",
            ),
            (
                "kernel.yama.ptrace_scope",
                "1",
                ParamCategory::Security,
                "Ptrace scope restriction",
                "1",
            ),
            (
                "kernel.unprivileged_bpf_disabled",
                "1",
                ParamCategory::Security,
                "Disable unprivileged BPF",
                "1",
            ),
            (
                "kernel.kexec_load_disabled",
                "1",
                ParamCategory::Security,
                "Disable kexec_load",
                "1",
            ),
            (
                "kernel.sysrq",
                "0",
                ParamCategory::Security,
                "Magic SysRq key (0=disable)",
                "0",
            ),
            (
                "kernel.core_uses_pid",
                "1",
                ParamCategory::Security,
                "Core dumps include PID",
                "1",
            ),
            (
                "kernel.modules_disabled",
                "0",
                ParamCategory::Security,
                "Disable module loading (0=allow)",
                "0",
            ),
            // Network parameters
            (
                "net.ipv4.tcp_syncookies",
                "1",
                ParamCategory::Network,
                "SYN flood protection",
                "1",
            ),
            (
                "net.ipv4.conf.all.rp_filter",
                "1",
                ParamCategory::Network,
                "Reverse path filtering",
                "1",
            ),
            (
                "net.ipv4.conf.all.accept_redirects",
                "0",
                ParamCategory::Network,
                "ICMP redirect acceptance",
                "0",
            ),
            (
                "net.ipv4.conf.all.send_redirects",
                "0",
                ParamCategory::Network,
                "ICMP redirect sending",
                "0",
            ),
            (
                "net.ipv4.conf.all.accept_source_route",
                "0",
                ParamCategory::Network,
                "Source routing",
                "0",
            ),
            (
                "net.ipv4.conf.all.log_martians",
                "1",
                ParamCategory::Network,
                "Log martian packets",
                "1",
            ),
            (
                "net.ipv4.tcp_max_syn_backlog",
                "4096",
                ParamCategory::Network,
                "Max SYN backlog",
                "4096",
            ),
            (
                "net.core.somaxconn",
                "4096",
                ParamCategory::Network,
                "Max socket backlog",
                "4096",
            ),
            (
                "net.ipv4.tcp_tw_reuse",
                "1",
                ParamCategory::Network,
                "TIME_WAIT socket reuse",
                "1",
            ),
            (
                "net.ipv4.tcp_fin_timeout",
                "15",
                ParamCategory::Network,
                "FIN timeout seconds",
                "15",
            ),
            (
                "net.core.rmem_max",
                "16777216",
                ParamCategory::Network,
                "Max receive buffer",
                "16777216",
            ),
            (
                "net.core.wmem_max",
                "16777216",
                ParamCategory::Network,
                "Max send buffer",
                "16777216",
            ),
            // VM/Memory parameters
            (
                "vm.swappiness",
                "60",
                ParamCategory::Vm,
                "Swappiness (0-200)",
                "60",
            ),
            (
                "vm.dirty_ratio",
                "20",
                ParamCategory::Vm,
                "Dirty page ratio (% of RAM)",
                "20",
            ),
            (
                "vm.dirty_background_ratio",
                "10",
                ParamCategory::Vm,
                "Background dirty ratio",
                "10",
            ),
            (
                "vm.overcommit_memory",
                "0",
                ParamCategory::Vm,
                "Memory overcommit (0=heuristic)",
                "0",
            ),
            (
                "vm.max_map_count",
                "65530",
                ParamCategory::Vm,
                "Max memory mappings",
                "65530",
            ),
            (
                "vm.vfs_cache_pressure",
                "100",
                ParamCategory::Vm,
                "VFS cache pressure",
                "100",
            ),
            (
                "vm.min_free_kbytes",
                "65536",
                ParamCategory::Vm,
                "Minimum free memory (kB)",
                "65536",
            ),
            // Filesystem parameters
            (
                "fs.file-max",
                "1048576",
                ParamCategory::FileSystem,
                "Max open files system-wide",
                "1048576",
            ),
            (
                "fs.inotify.max_user_watches",
                "524288",
                ParamCategory::FileSystem,
                "Max inotify watches per user",
                "524288",
            ),
        ];

        let mut params = Vec::new();
        for (name, _default, category, description, recommended) in &checks {
            let sysctl_path = format!("/proc/sys/{}", name.replace('.', "/"));
            // An unreadable sysctl has no value and nothing to judge. It used to
            // be given the value "N/A" and counted as not recommended.
            let value = std::fs::read_to_string(&sysctl_path)
                .ok()
                .map(|s| s.trim().to_string());

            let is_recommended = value
                .as_deref()
                .map(|v| Self::check_recommended(v, recommended));

            params.push(KernelParam {
                name: name.to_string(),
                value,
                category: *category,
                is_recommended,
                recommended: Some(recommended.to_string()),
                description: description.to_string(),
            });
        }
        params
    }

    #[cfg(target_os = "linux")]
    fn check_recommended(value: &str, recommended: &str) -> bool {
        // Numeric comparison
        if let (Ok(v), Ok(r)) = (value.parse::<i64>(), recommended.parse::<i64>()) {
            return v >= r; // For most params, >= recommended is fine
        }
        value == recommended
    }

    #[cfg(target_os = "windows")]
    fn read_params() -> Vec<KernelParam> {
        // Read some Windows-equivalent tuning via registry/powershell
        let mut params = Vec::new();

        // TCP auto-tuning.
        //
        // `Get-NetTCPSetting` returns one row per template, not one row for the
        // machine, and `Select-Object -First 1` took the `Automatic` template --
        // the selector, which carries no level of its own and returns an empty
        // string. Every other row on this host says `Normal`, so the reader
        // reported "no kernel parameter was readable here" about a setting the
        // machine states six times.
        //
        // The rows that carry a level are read, and their value is published
        // only when they agree. Templates that disagree describe different
        // destinations rather than one machine-wide level, and picking one of
        // them would answer a question nobody asked; that case is left absent.
        let output = std::process::Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                "Get-NetTCPSetting | ForEach-Object { $_.AutoTuningLevelLocal }",
            ])
            .output();

        if let Ok(out) = output {
            // A missing powershell, a failed cmdlet and a machine that genuinely
            // reports nothing all arrive here as no lines at all. Pushing the
            // parameter anyway published a named setting whose value was "",
            // which reads as a setting that exists and is blank rather than one
            // that was never read.
            if let Some(val) = agreed_tcp_level(&String::from_utf8_lossy(&out.stdout)) {
                params.push(KernelParam {
                    name: "net.tcp.autotuninglevel".into(),
                    value: Some(val.clone()),
                    category: ParamCategory::Network,
                    is_recommended: Some(val.to_lowercase() == "normal"),
                    recommended: Some("Normal".into()),
                    description: "TCP auto-tuning level, agreed by every template that states one"
                        .into(),
                });
            }
        }

        params
    }

    #[cfg(target_os = "macos")]
    fn read_params() -> Vec<KernelParam> {
        let checks = vec![
            (
                "kern.maxfiles",
                ParamCategory::FileSystem,
                "Max open files",
                "49152",
            ),
            (
                "kern.maxfilesperproc",
                ParamCategory::FileSystem,
                "Max files per process",
                "24576",
            ),
            (
                "net.inet.tcp.msl",
                ParamCategory::Network,
                "TCP MSL (milliseconds)",
                "15000",
            ),
            (
                "net.inet.tcp.delayed_ack",
                ParamCategory::Network,
                "Delayed ACK",
                "0",
            ),
            ("vm.swapusage", ParamCategory::Vm, "Swap usage", ""),
        ];

        let mut params = Vec::new();
        for (name, category, description, recommended) in &checks {
            let output = std::process::Command::new("sysctl")
                .arg("-n")
                .arg(name)
                .output();

            // A failed or empty read has no value. It used to be "N/A".
            let value = output
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                .filter(|s| !s.is_empty());

            // Nothing to compare against (`vm.swapusage`) is no judgement, and
            // neither is a value that was never read. Both used to be `true`.
            let is_recommended = value
                .as_deref()
                .filter(|_| !recommended.is_empty())
                .map(|v| {
                    if let (Ok(v_num), Ok(r)) = (v.parse::<i64>(), recommended.parse::<i64>()) {
                        v_num >= r
                    } else {
                        v == *recommended
                    }
                });

            params.push(KernelParam {
                name: name.to_string(),
                value,
                category: *category,
                is_recommended,
                recommended: if recommended.is_empty() {
                    None
                } else {
                    Some(recommended.to_string())
                },
                description: description.to_string(),
            });
        }
        params
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn read_params() -> Vec<KernelParam> {
        Vec::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_category_display() {
        assert_eq!(ParamCategory::Network.to_string(), "Network");
        assert_eq!(ParamCategory::Security.to_string(), "Security");
        assert_eq!(ParamCategory::Vm.to_string(), "VM/Memory");
    }

    #[test]
    fn test_security_scoring() {
        let params = vec![
            KernelParam {
                name: "a".into(),
                value: Some("2".into()),
                category: ParamCategory::Security,
                is_recommended: Some(true),
                recommended: Some("2".into()),
                description: "".into(),
            },
            KernelParam {
                name: "b".into(),
                value: Some("0".into()),
                category: ParamCategory::Security,
                is_recommended: Some(false),
                recommended: Some("1".into()),
                description: "".into(),
            },
        ];
        let score = KernelParamsMonitor::compute_security_score(&params);
        assert_eq!(score, Some(50));
    }

    fn judged(name: &str, value: Option<&str>, is_recommended: Option<bool>) -> KernelParam {
        KernelParam {
            name: name.into(),
            value: value.map(String::from),
            category: ParamCategory::Security,
            is_recommended,
            recommended: Some("1".into()),
            description: "".into(),
        }
    }

    #[test]
    fn nothing_to_score_is_no_score_not_fifty() {
        assert_eq!(KernelParamsMonitor::compute_security_score(&[]), None);
        let unread = [judged("a", None, None)];
        assert_eq!(KernelParamsMonitor::compute_security_score(&unread), None);
    }

    #[test]
    fn unread_parameters_do_not_move_the_score() {
        let params = [judged("a", Some("1"), Some(true)), judged("b", None, None)];
        assert_eq!(
            KernelParamsMonitor::compute_security_score(&params),
            Some(100)
        );
    }

    #[test]
    fn a_parameter_with_no_recommendation_is_not_judged() {
        let mut no_rec = judged("a", Some("0"), Some(false));
        no_rec.recommended = None;
        assert_eq!(KernelParamsMonitor::compute_network_score(&[no_rec]), None);
    }

    #[test]
    fn test_perfect_score() {
        let params = vec![
            KernelParam {
                name: "a".into(),
                value: Some("1".into()),
                category: ParamCategory::Security,
                is_recommended: Some(true),
                recommended: Some("1".into()),
                description: "".into(),
            },
            KernelParam {
                name: "b".into(),
                value: Some("1".into()),
                category: ParamCategory::Security,
                is_recommended: Some(true),
                recommended: Some("1".into()),
                description: "".into(),
            },
        ];
        let score = KernelParamsMonitor::compute_security_score(&params);
        assert_eq!(score, Some(100));
    }

    #[test]
    fn test_serialization() {
        let param = KernelParam {
            name: "net.ipv4.tcp_syncookies".into(),
            value: Some("1".into()),
            category: ParamCategory::Network,
            is_recommended: Some(true),
            recommended: Some("1".into()),
            description: "SYN cookies".into(),
        };
        let json = serde_json::to_string(&param).unwrap();
        assert!(json.contains("tcp_syncookies"));
        let _: KernelParam = serde_json::from_str(&json).unwrap();
    }
}

#[cfg(all(test, target_os = "windows"))]
mod windows_tcp_tests {
    use super::agreed_tcp_level;

    /// The cmdlet's output on the development host: the `Automatic` template
    /// first, stating nothing, and six templates stating `Normal`.
    #[test]
    fn the_empty_first_template_does_not_hide_the_six_that_answer() {
        let out = "\nNormal\nNormal\nNormal\nNormal\nNormal\nNormal\n";
        assert_eq!(agreed_tcp_level(out).as_deref(), Some("Normal"));
    }

    #[test]
    fn templates_that_disagree_state_nothing_machine_wide() {
        assert_eq!(agreed_tcp_level("Normal\nDisabled\n"), None);
    }

    #[test]
    fn no_output_is_no_reading() {
        assert_eq!(agreed_tcp_level(""), None);
        assert_eq!(agreed_tcp_level("\n  \n"), None);
    }
}