Repository navigation
Expand file tree
/
Copy pathpolicy.rs
More file actions
1370 lines (1287 loc) · 52.7 KB
/
Copy pathpolicy.rs
File metadata and controls
1370 lines (1287 loc) · 52.7 KB
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Junos command/config policy — thin shim over `mecmcp-policy` (MEC-93).
//!
//! Two authorization models are available for the `commands` and
//! `pfe_commands` domains, chosen once for the whole compiled [`Policy`] via
//! [`mecmcp_policy::CommandMode`]:
//!
//! - **Allowlist (fail-closed, default).** A command is refused unless it is
//! a whole-token prefix of a configured `allow` entry. Abbreviations are
//! refused, never expanded. See [`mecmcp_policy::CommandMode::Allowlist`]
//! for the exact matching rules.
//! - **Blocklist (fail-open, legacy/opt-in).** The pre-MEC-92 behaviour: a
//! command is refused only if it matches a `deny` glob rule.
//!
//! The `config` domain (used by `load_and_commit_config` et al.) is
//! unaffected by the mode and is always a fail-open deny-pattern blocklist.
//!
//! # Why one `mecmcp_policy::Policy` per device
//!
//! `mecmcp_policy::CommandAllowlist` is a single value per `Policy` instance
//! — `check_command`/`check_pfe_command` under `CommandMode::Allowlist` do
//! not consult the `device` argument at all. To honour the spec's
//! requirement that per-router `allow`/`allowed_pipes` merge with defaults
//! the same way deny rules do, this module compiles one
//! `mecmcp_policy::Policy<Action>` **per device**, each sharing the same
//! `CommandMode` but carrying a device-tailored allowlist (defaults' `allow`
//! ∪ that device's own `allow`, same for `allowed_pipes`; `pfe_allow` and
//! `pfe_allowed_pipes` merge the same way, independently, for the
//! `pfe_commands` domain). Building one global `Policy` whose allowlist was
//! the union of every device's entries was considered and rejected: it
//! would let a command scoped as extra-allowed on device B silently also
//! work on device A, which is a real security regression, not a
//! convenience.
//!
//! The `pfe_commands` domain has its own `pfe_allow`/`pfe_allowed_pipes`
//! config keys (MEC-1303), independent from `commands`' `allow`/
//! `allowed_pipes` — a command allowlisted for `execute_junos_command` is
//! not implicitly allowlisted for `execute_junos_pfe_command` or vice
//! versa. A config with neither key set still fails closed under
//! `CommandMode::Allowlist` (empty allowlist), which was the behavior
//! before this config key existed and remains correct: fail-closed is the
//! safe default for an unconfigured domain.
//!
//! # Deny rules are a carve-out on top of the allowlist (MEC-1096 F1)
//!
//! `mecmcp_policy::Policy::check_command`/`check_pfe_command` never consult
//! the `commands`/`pfe_commands` blocklist once the mode is `Allowlist` — an
//! operator who writes `allow: ["request system"]` plus a
//! `commands: [{deny, "request system reboot*"}]` carve-out would otherwise
//! see the deny silently ignored (a wider hole than no carve-out at all: the
//! operator believes the destructive command is fenced off). `Policy::
//! check_command`/`check_pfe_command` in this module close that gap: an
//! `Allow` from the library's allowlist is re-checked against that device's
//! effective deny rules, which demotes it to `Deny` on a match. See
//! `Policy::check_command`.
use crate::error::JmcpError;
use crate::helpers::excerpt;
use crate::inventory::{Action, CommandModeConfig, RuleSpec};
use std::collections::HashMap;
// Re-export the upstream rule engine primitives and types callers match on.
pub use mecmcp_policy::{
AllowlistDenyReason, CommandMode, CompiledRule, Decision, RuleSource, count_literal_chars,
normalize_input,
};
/// Compile a list of `RuleSpec`s into `CompiledRule`s, attaching the given
/// `source` and a scope label used in compile-time error messages.
fn compile_rules(
rules: &[RuleSpec],
scope: &str,
source: RuleSource,
) -> Result<Vec<CompiledRule<Action>>, JmcpError> {
let pairs: Vec<(Action, String)> = rules
.iter()
.map(|r| (r.action, r.pattern.clone()))
.collect();
mecmcp_policy::compile_rules(&pairs, scope, source, |scope, pattern, err| {
JmcpError::BlocklistRuleInvalid {
scope,
pattern,
source: err,
}
})
}
/// Compile a list of raw `allow`/`allowed_pipes` strings into
/// `AllowlistEntry`s, attaching `scope` for error messages.
fn compile_allowlist(
entries: &[String],
scope: &str,
) -> Result<Vec<mecmcp_policy::AllowlistEntry>, JmcpError> {
mecmcp_policy::compile_allowlist_entries(entries, scope, |scope, entry, kind| {
let reason = match kind {
mecmcp_policy::AllowlistEntryErrorKind::GlobMetachar(c) => format!(
"contains glob metacharacter '{c}' (allowlist entries are literal \
whitespace-token prefixes, never globs)"
),
mecmcp_policy::AllowlistEntryErrorKind::Empty => {
"is empty or all-whitespace".to_string()
}
};
JmcpError::AllowlistEntryInvalid {
scope,
entry,
reason,
}
})
}
/// Compile one domain's defaults ⊕ (optional) single device's rules into a
/// `DomainRules<Action>`. `device` is `Some((name, rules))` for the device
/// this `DomainRules` is being built for; an empty per-device rule list does
/// not get inserted, matching the "empty per-device blocklist should not
/// inflate rule counts" behaviour from before MEC-93.
fn compile_domain_rules(
defaults: &[RuleSpec],
device: Option<(&str, &[RuleSpec])>,
domain_key: BlocklistDomain,
) -> Result<mecmcp_policy::DomainRules<Action>, JmcpError> {
let mut domain = mecmcp_policy::DomainRules {
defaults: compile_rules(
defaults,
&rule_location(RuleSource::Defaults, "", domain_key),
RuleSource::Defaults,
)?,
..Default::default()
};
if let Some((name, rules)) = device
&& !rules.is_empty()
{
let compiled = compile_rules(
rules,
&rule_location(RuleSource::Device, name, domain_key),
RuleSource::Device,
)?;
if !compiled.is_empty() {
domain.device_specific.insert(name.to_string(), compiled);
}
}
Ok(domain)
}
/// Compiled, per-device command/config policy. Built once at startup from
/// the parsed inventory. Internally one [`mecmcp_policy::Policy`] per known
/// device (see module docs for why), plus a defaults-only fallback used for
/// any device name not present at build time.
#[derive(Debug)]
pub struct Policy {
per_device: HashMap<String, mecmcp_policy::Policy<Action>>,
/// Defaults-only policy, consulted for a device name that wasn't in the
/// inventory at build time. Defensive: callers already validate the
/// device exists (`inventory().get()`) before consulting policy, so this
/// path should not normally be hit.
default_policy: mecmcp_policy::Policy<Action>,
command_mode: CommandMode,
default_commands_count: usize,
default_config_count: usize,
default_pfe_commands_count: usize,
devices_with_rules: usize,
}
impl Policy {
/// Compile every glob/allowlist entry in the inventory. Returns the
/// first compile error encountered, scoped to its source location.
///
/// Also decides the effective [`CommandMode`] (spec item 3, "migration"):
///
/// - `_blocklist_defaults.mode` explicitly set → use it.
/// - Unset, but `_blocklist_defaults` has any non-empty `commands`,
/// `config`, or `pfe_commands` rule list → this is a legacy
/// deny-only config; select [`CommandMode::Blocklist`] and log one
/// `tracing::warn!` explaining that blocklist mode is fail-open, with
/// a pointer to the migration docs in docs/REFERENCE.md.
/// - Otherwise (no `_blocklist_defaults` at all, an empty one, or `mode`
/// absent with no rules) → [`CommandMode::Allowlist`] (also just
/// `CommandMode::default()`).
pub fn build(inv: &crate::Inventory) -> Result<Self, JmcpError> {
let defaults = inv.blocklist_defaults();
let default_commands_specs: &[RuleSpec] =
defaults.map(|d| d.commands.as_slice()).unwrap_or(&[]);
let default_config_specs: &[RuleSpec] =
defaults.map(|d| d.config.as_slice()).unwrap_or(&[]);
let default_pfe_specs: &[RuleSpec] =
defaults.map(|d| d.pfe_commands.as_slice()).unwrap_or(&[]);
let default_allow: &[String] = defaults.map(|d| d.allow.as_slice()).unwrap_or(&[]);
let default_pipes: &[String] = defaults.map(|d| d.allowed_pipes.as_slice()).unwrap_or(&[]);
let default_pfe_allow: &[String] = defaults.map(|d| d.pfe_allow.as_slice()).unwrap_or(&[]);
let default_pfe_pipes: &[String] = defaults
.map(|d| d.pfe_allowed_pipes.as_slice())
.unwrap_or(&[]);
let command_mode = match defaults.and_then(|d| d.mode) {
Some(CommandModeConfig::Allowlist) => CommandMode::Allowlist,
Some(CommandModeConfig::Blocklist) => CommandMode::Blocklist,
None => {
// "Has deny rules" spans the whole config file, not just
// `_blocklist_defaults` — a config with no defaults section
// but a device-level `blocklist.commands` deny rule is still
// an existing deny-rule config that must keep working
// fail-open, not suddenly start refusing everything under
// the new fail-closed default.
let any_device_has_rules = inv.names().iter().any(|name| {
inv.get(name).is_ok_and(|entry| {
entry.blocklist.as_ref().is_some_and(|b| {
!b.commands.is_empty()
|| !b.config.is_empty()
|| !b.pfe_commands.is_empty()
})
})
});
let legacy_deny_only = !default_commands_specs.is_empty()
|| !default_config_specs.is_empty()
|| !default_pfe_specs.is_empty()
|| any_device_has_rules;
if legacy_deny_only {
tracing::warn!(
"_blocklist_defaults has deny rules but no explicit `mode` key; \
loading as legacy blocklist mode. Blocklist mode is fail-open \
(anything not explicitly denied is allowed) and is being phased \
out in favor of the fail-closed allowlist mode, which is now the \
default for configs that set no rules at all. See docs/REFERENCE.md, \
section '`execute_junos_command` authorization mode: allowlist \
(default) vs. blocklist', for how to migrate to an explicit \
`mode: allowlist` with an `allow` list."
);
CommandMode::Blocklist
} else {
CommandMode::Allowlist
}
}
};
// Compile defaults first so a bad default entry is reported against
// `_blocklist_defaults`, not against the first device that merges it.
let default_allow_entries = compile_allowlist(
default_allow,
&rule_location(RuleSource::Defaults, "", BlocklistDomain::Allow),
)?;
let default_pipe_entries = compile_allowlist(
default_pipes,
&rule_location(RuleSource::Defaults, "", BlocklistDomain::AllowedPipes),
)?;
let default_pfe_allow_entries = compile_allowlist(
default_pfe_allow,
&rule_location(RuleSource::Defaults, "", BlocklistDomain::PfeAllow),
)?;
let default_pfe_pipe_entries = compile_allowlist(
default_pfe_pipes,
&rule_location(RuleSource::Defaults, "", BlocklistDomain::PfeAllowedPipes),
)?;
let mut per_device = HashMap::new();
let mut devices_with_rules = 0usize;
for name in inv.names() {
let entry = inv.get(&name)?;
let device_bl = entry.blocklist.as_ref();
let has_own_rules = device_bl.is_some_and(|b| {
!b.commands.is_empty() || !b.config.is_empty() || !b.pfe_commands.is_empty()
});
if has_own_rules {
devices_with_rules += 1;
}
let commands_rules = compile_domain_rules(
default_commands_specs,
device_bl.map(|b| (name.as_str(), b.commands.as_slice())),
BlocklistDomain::Commands,
)?;
let config_rules = compile_domain_rules(
default_config_specs,
device_bl.map(|b| (name.as_str(), b.config.as_slice())),
BlocklistDomain::Config,
)?;
let pfe_rules = compile_domain_rules(
default_pfe_specs,
device_bl.map(|b| (name.as_str(), b.pfe_commands.as_slice())),
BlocklistDomain::PfeCommands,
)?;
let merged_allow: Vec<String> = default_allow
.iter()
.cloned()
.chain(device_bl.map(|b| b.allow.clone()).unwrap_or_default())
.collect();
let merged_pipes: Vec<String> = default_pipes
.iter()
.cloned()
.chain(
device_bl
.map(|b| b.allowed_pipes.clone())
.unwrap_or_default(),
)
.collect();
let allow_entries = compile_allowlist(
&merged_allow,
&rule_location(RuleSource::Device, name.as_str(), BlocklistDomain::Allow),
)?;
let pipe_entries = compile_allowlist(
&merged_pipes,
&rule_location(
RuleSource::Device,
name.as_str(),
BlocklistDomain::AllowedPipes,
),
)?;
let merged_pfe_allow: Vec<String> = default_pfe_allow
.iter()
.cloned()
.chain(device_bl.map(|b| b.pfe_allow.clone()).unwrap_or_default())
.collect();
let merged_pfe_pipes: Vec<String> = default_pfe_pipes
.iter()
.cloned()
.chain(
device_bl
.map(|b| b.pfe_allowed_pipes.clone())
.unwrap_or_default(),
)
.collect();
let pfe_allow_entries = compile_allowlist(
&merged_pfe_allow,
&rule_location(RuleSource::Device, name.as_str(), BlocklistDomain::PfeAllow),
)?;
let pfe_pipe_entries = compile_allowlist(
&merged_pfe_pipes,
&rule_location(
RuleSource::Device,
name.as_str(),
BlocklistDomain::PfeAllowedPipes,
),
)?;
let commands_domain = mecmcp_policy::CommandDomain {
blocklist: commands_rules,
allowlist: mecmcp_policy::CommandAllowlist {
entries: allow_entries,
allowed_pipes: pipe_entries,
},
};
let pfe_domain = mecmcp_policy::CommandDomain {
blocklist: pfe_rules,
allowlist: mecmcp_policy::CommandAllowlist {
entries: pfe_allow_entries,
allowed_pipes: pfe_pipe_entries,
},
};
let lib_policy =
mecmcp_policy::Policy::new(command_mode, commands_domain, config_rules, pfe_domain);
per_device.insert(name.clone(), lib_policy);
}
let default_commands_rules =
compile_domain_rules(default_commands_specs, None, BlocklistDomain::Commands)?;
let default_config_rules =
compile_domain_rules(default_config_specs, None, BlocklistDomain::Config)?;
let default_pfe_rules =
compile_domain_rules(default_pfe_specs, None, BlocklistDomain::PfeCommands)?;
let default_policy = mecmcp_policy::Policy::new(
command_mode,
mecmcp_policy::CommandDomain {
blocklist: default_commands_rules,
allowlist: mecmcp_policy::CommandAllowlist {
entries: default_allow_entries,
allowed_pipes: default_pipe_entries,
},
},
default_config_rules,
mecmcp_policy::CommandDomain {
blocklist: default_pfe_rules,
allowlist: mecmcp_policy::CommandAllowlist {
entries: default_pfe_allow_entries,
allowed_pipes: default_pfe_pipe_entries,
},
},
);
Ok(Self {
per_device,
default_policy,
command_mode,
default_commands_count: default_commands_specs.len(),
default_config_count: default_config_specs.len(),
default_pfe_commands_count: default_pfe_specs.len(),
devices_with_rules,
})
}
fn policy_for(&self, router: &str) -> &mecmcp_policy::Policy<Action> {
self.per_device.get(router).unwrap_or(&self.default_policy)
}
/// The effective [`CommandMode`] this policy was built with.
pub fn command_mode(&self) -> CommandMode {
self.command_mode
}
/// Decide whether `command` is allowed on `router`.
///
/// Under [`CommandMode::Allowlist`], an `Allow` from the library's
/// prefix-match allowlist is still subject to this device's `commands`
/// deny rules as a carve-out (see module docs / MEC-1096 F1): an
/// operator who writes `allow: ["request system"]` plus a
/// `commands: [{deny, "request system reboot*"}]` carve-out expects the
/// deny to win, but `mecmcp_policy::Policy::check_command` never
/// consults the blocklist once the mode is `Allowlist`.
pub fn check_command<'a>(&'a self, router: &str, command: &str) -> Decision<'a, Action> {
let policy = self.policy_for(router);
if let Some(decision) = self.deny_disallowed_character(command) {
return decision;
}
let decision = policy.check_command(router, command, Action::Deny);
self.apply_allowlist_deny_carveout(policy, router, command, decision, |p, d| {
p.command_rules_for(d)
})
}
/// Decide whether `pfe_command` is allowed on `router`. Independent from
/// `check_command`. See `check_command`'s docs for the allowlist deny
/// carve-out.
pub fn check_pfe_command<'a>(
&'a self,
router: &str,
pfe_command: &str,
) -> Decision<'a, Action> {
let policy = self.policy_for(router);
if let Some(decision) = self.deny_disallowed_character(pfe_command) {
return decision;
}
let decision = policy.check_pfe_command(router, pfe_command, Action::Deny);
self.apply_allowlist_deny_carveout(policy, router, pfe_command, decision, |p, d| {
p.pfe_command_rules_for(d)
})
}
/// Under [`CommandMode::Allowlist`], refuse a command outright unless
/// every character is printable ASCII or the literal ASCII space
/// (`' '`) used as the token separator (MEC-1337). Returns `None`
/// outside [`CommandMode::Allowlist`] and when `raw` is already
/// entirely printable ASCII plus space.
fn deny_disallowed_character<'a>(&'a self, raw: &str) -> Option<Decision<'a, Action>> {
if self.command_mode != CommandMode::Allowlist {
return None;
}
if !raw.chars().any(|c| c != ' ' && !c.is_ascii_graphic()) {
return None;
}
Some(Decision::DenyAllowlist {
mode: CommandMode::Allowlist,
reason: AllowlistDenyReason::ForbiddenMetachar,
normalized: normalize_input(raw),
})
}
/// Under [`CommandMode::Allowlist`], demote an `Allow` decision to
/// `Deny` if a `commands`/`pfe_commands` deny rule (picked by
/// `rules_for`) also matches. A no-op under [`CommandMode::Blocklist`]
/// (the library already consulted those same rules to produce
/// `decision`) or when `decision` is already a denial.
fn apply_allowlist_deny_carveout<'a>(
&'a self,
policy: &'a mecmcp_policy::Policy<Action>,
router: &str,
raw_input: &str,
decision: Decision<'a, Action>,
rules_for: impl FnOnce(&'a mecmcp_policy::Policy<Action>, &str) -> Vec<&'a CompiledRule<Action>>,
) -> Decision<'a, Action> {
if self.command_mode != CommandMode::Allowlist || !decision.is_allowed() {
return decision;
}
let rules = rules_for(policy, router);
let normalized = normalize_input(raw_input);
match mecmcp_policy::evaluate(&rules, &normalized) {
Some(rule) if rule.action == Action::Deny => Decision::Deny {
rule,
source: rule.source,
line_number: None,
},
_ => decision,
}
}
/// Decide whether `config_text` is allowed on `router` for the given
/// `config_format`. Returns `Err` if `config_format != "set"` and the
/// device has any effective config rules. Always a fail-open blocklist;
/// never returns `Decision::DenyAllowlist`.
pub fn check_config<'a>(
&'a self,
router: &str,
config_format: &str,
config_text: &str,
) -> Result<Decision<'a, Action>, JmcpError> {
self.policy_for(router).check_config(
router,
config_format,
config_text,
Action::Deny,
"set",
|format| JmcpError::ConfigFormatNotAllowedWithRules { format },
)
}
/// True if the per-router effective config rule list is non-empty.
pub fn has_config_rules_for(&self, router: &str) -> bool {
self.policy_for(router).has_config_rules_for(router)
}
/// Counts for the startup info log.
pub fn rule_counts(&self) -> PolicyCounts {
PolicyCounts {
default_commands: self.default_commands_count,
default_config: self.default_config_count,
default_pfe_commands: self.default_pfe_commands_count,
devices_with_rules: self.devices_with_rules,
}
}
}
/// Policy key a rule or allowlist entry lives under: the domain a denial came
/// from, or a listing-only key (`allow*`) shown by `get_device_list`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlocklistDomain {
/// `commands` rules.
Commands,
/// `config` rules.
Config,
/// `pfe_commands` rules.
PfeCommands,
/// `allow` entries (listing only; never a denial source).
Allow,
/// `allowed_pipes` entries (listing only; never a denial source).
AllowedPipes,
/// `pfe_allow` entries (listing only; never a denial source).
PfeAllow,
/// `pfe_allowed_pipes` entries (listing only; never a denial source).
PfeAllowedPipes,
}
impl BlocklistDomain {
/// Inventory key name of the domain.
pub fn as_str(self) -> &'static str {
match self {
Self::Commands => "commands",
Self::Config => "config",
Self::PfeCommands => "pfe_commands",
Self::Allow => "allow",
Self::AllowedPipes => "allowed_pipes",
Self::PfeAllow => "pfe_allow",
Self::PfeAllowedPipes => "pfe_allowed_pipes",
}
}
}
/// Where a blocklist rule lives, for denial messages (inventory keys only,
/// never file paths). The match on `rule_source` is exhaustive so a new
/// source variant cannot silently be reported as defaults.
pub fn rule_location(rule_source: RuleSource, device: &str, domain: BlocklistDomain) -> String {
let domain = domain.as_str();
match rule_source {
RuleSource::Device => format!("inventory entry '{device}'.blocklist.{domain}"),
RuleSource::Defaults => format!("_blocklist_defaults.{domain}"),
}
}
/// The allow-list key a `DeniedAllowlist` refusal checked, from the policy
/// domain and the machine-readable denial reason.
pub fn allowlist_checked_domain(domain: BlocklistDomain, reason: &str) -> BlocklistDomain {
match (
domain,
reason == mecmcp_policy::AllowlistDenyReason::PipeNotAllowlisted.as_str(),
) {
(BlocklistDomain::Commands, true) => BlocklistDomain::AllowedPipes,
(BlocklistDomain::Commands, false) => BlocklistDomain::Allow,
(BlocklistDomain::PfeCommands, true) => BlocklistDomain::PfeAllowedPipes,
(BlocklistDomain::PfeCommands, false) => BlocklistDomain::PfeAllow,
// Allowlists only gate the commands and pfe_commands domains.
(other, _) => other,
}
}
/// Turn a commands/pfe_commands-domain [`Decision`] into `Ok(())` or an
/// audit-ready [`JmcpError`], warn-logging the refusal either way. Shared by
/// every `execute_junos_command`-shaped call site so the three-variant
/// `Decision` match lives in exactly one place — see the module docs on
/// `mecmcp_policy::Decision` for why matching only `Deny` (and treating
/// `DenyAllowlist` as an implicit allow) is a live vulnerability.
///
/// `domain` is the policy key a `Deny` came from; it is carried into the error
/// so the denial message can name where the matching rule lives.
pub fn enforce_decision(
decision: Decision<'_, Action>,
tool: &'static str,
router: &str,
raw_input: &str,
domain: BlocklistDomain,
) -> Result<(), JmcpError> {
match decision {
Decision::Allow => Ok(()),
Decision::Deny { rule, source, .. } => {
let pattern = rule.pattern.clone();
let source_str = source.as_str();
tracing::warn!(
tool,
router = %router,
matched_rule = %pattern,
rule_source = %source_str,
input_excerpt = %excerpt(raw_input),
"blocklist denied request",
);
Err(JmcpError::Denied {
tool,
router: router.to_string(),
pattern,
rule_source: source,
domain,
input_excerpt: excerpt(raw_input).into(),
line_number: None,
})
}
Decision::DenyAllowlist {
reason, normalized, ..
} => {
let reason_str = reason.as_str();
tracing::warn!(
tool,
router = %router,
reason = %reason_str,
normalized = %normalized,
"allowlist denied request",
);
Err(JmcpError::DeniedAllowlist {
tool,
router: router.to_string(),
reason: reason_str,
domain,
input_excerpt: excerpt(&normalized),
})
}
}
}
/// Summary numbers for startup logging.
///
/// Reports how many rules are active from defaults and how many devices have
/// device-specific overrides. Used to log policy coverage at server boot.
#[derive(Debug, Clone, Copy)]
pub struct PolicyCounts {
/// Number of default command rules active across all devices.
pub default_commands: usize,
/// Number of default config rules active across all devices.
pub default_config: usize,
/// Number of default PFE command rules active across all devices.
pub default_pfe_commands: usize,
/// Number of devices that have at least one device-specific rule.
pub devices_with_rules: usize,
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn spec(action: Action, pattern: &str) -> RuleSpec {
RuleSpec {
action,
pattern: pattern.into(),
}
}
#[test]
fn count_literals_handles_wildcards_and_classes() {
assert_eq!(count_literal_chars("request system reboot"), 21);
assert_eq!(count_literal_chars("request system *"), 15);
assert_eq!(count_literal_chars("*"), 0);
assert_eq!(count_literal_chars("?abc"), 3);
assert_eq!(count_literal_chars("ab[cd]ef"), 4); // class doesn't count
assert_eq!(count_literal_chars(r"\*literal"), 8); // escaped * counts as literal
}
#[test]
fn compile_rules_succeeds_on_valid_globs() {
let r = vec![
spec(Action::Deny, "request system *"),
spec(Action::Allow, "show version"),
];
let compiled = compile_rules(&r, "test", RuleSource::Defaults).unwrap();
assert_eq!(compiled.len(), 2);
assert_eq!(compiled[0].specificity, (15, 16));
assert_eq!(compiled[0].source, RuleSource::Defaults);
}
#[test]
fn compile_rules_errors_with_scope_on_bad_glob() {
let r = vec![spec(Action::Deny, "[unterminated")];
let err =
compile_rules(&r, "_blocklist_defaults.commands", RuleSource::Defaults).unwrap_err();
match err {
JmcpError::BlocklistRuleInvalid { scope, pattern, .. } => {
assert_eq!(scope, "_blocklist_defaults.commands");
assert_eq!(pattern, "[unterminated");
}
_ => panic!("expected BlocklistRuleInvalid, got {err:?}"),
}
}
/// Scope string of the compile error `Policy::build` returns for a device
/// whose `blocklist` is `blocklist_json`.
fn device_compile_error_scope(blocklist_json: &str) -> String {
let inv = inv_from(&format!(
r#"{{"r1":{{"ip":"1.1.1.1","username":"u","auth":{{"type":"password","password":"x"}},
"blocklist":{blocklist_json}}}}}"#
));
match Policy::build(&inv).unwrap_err() {
JmcpError::BlocklistRuleInvalid { scope, .. }
| JmcpError::AllowlistEntryInvalid { scope, .. } => scope,
other => panic!("expected a compile error, got {other:?}"),
}
}
#[test]
fn device_compile_errors_use_rule_location_spelling() {
for key in ["commands", "config", "pfe_commands"] {
let scope = device_compile_error_scope(&format!(
r#"{{"{key}":[{{"action":"deny","pattern":"[bad"}}]}}"#
));
assert_eq!(scope, format!("inventory entry 'r1'.blocklist.{key}"));
}
for key in ["allow", "allowed_pipes", "pfe_allow", "pfe_allowed_pipes"] {
let scope = device_compile_error_scope(&format!(r#"{{"{key}":["show *"]}}"#));
assert_eq!(scope, format!("inventory entry 'r1'.blocklist.{key}"));
}
}
#[test]
fn bad_default_allow_entry_is_reported_against_defaults() {
let inv = inv_from(
r#"{"_blocklist_defaults":{"allow":["show *"]},
"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
match Policy::build(&inv).unwrap_err() {
JmcpError::AllowlistEntryInvalid { scope, .. } => {
assert_eq!(scope, "_blocklist_defaults.allow");
}
other => panic!("expected AllowlistEntryInvalid, got {other:?}"),
}
}
#[test]
fn compile_allowlist_rejects_glob_star() {
let err = compile_allowlist(&["show *".to_string()], "scope").unwrap_err();
match err {
JmcpError::AllowlistEntryInvalid { scope, entry, .. } => {
assert_eq!(scope, "scope");
assert_eq!(entry, "show *");
}
_ => panic!("expected AllowlistEntryInvalid, got {err:?}"),
}
}
use crate::Inventory;
use std::io::Write;
fn inv_from(json: &str) -> Inventory {
let mut f = tempfile::NamedTempFile::new().unwrap();
f.write_all(json.as_bytes()).unwrap();
Inventory::load(f.path()).unwrap()
}
fn build_policy(json: &str) -> Policy {
Policy::build(&inv_from(json)).unwrap()
}
// --- Legacy migration: deny-only config, no `mode` key -> Blocklist + warn ---
#[derive(Clone, Default)]
struct VecWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for VecWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for VecWriter {
type Writer = VecWriter;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
#[test]
fn legacy_deny_only_config_selects_blocklist_and_warns() {
let buf = VecWriter::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(buf.clone())
.with_max_level(tracing::Level::WARN)
.with_ansi(false)
.finish();
let inv = inv_from(
r#"{
"_blocklist_defaults": {
"commands": [{"action":"deny","pattern":"request system *"}]
},
"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
let policy = tracing::subscriber::with_default(subscriber, || Policy::build(&inv).unwrap());
assert_eq!(policy.command_mode(), CommandMode::Blocklist);
let logged = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap();
assert!(
logged.contains("legacy blocklist mode"),
"expected a migration WARN, got: {logged}"
);
}
#[test]
fn no_blocklist_defaults_selects_allowlist_and_refuses_everything() {
let p = build_policy(
r#"{"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
assert_eq!(p.command_mode(), CommandMode::Allowlist);
assert!(
!p.check_command("r1", "request system reboot").is_allowed(),
"empty allowlist must refuse a destructive command"
);
assert!(
!p.check_command("r1", "show version").is_allowed(),
"empty allowlist must refuse even a benign read"
);
}
#[test]
fn explicit_mode_allowlist_with_allow_list_permits_exact_prefix_only() {
let p = build_policy(
r#"{
"_blocklist_defaults": {
"mode": "allowlist",
"allow": ["show version"]
},
"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
assert!(p.check_command("r1", "show version").is_allowed());
match p.check_command("r1", "sh ver") {
Decision::DenyAllowlist {
reason: AllowlistDenyReason::NotAllowlisted,
..
} => {}
other => {
panic!("expected DenyAllowlist(NotAllowlisted) for abbreviation, got {other:?}")
}
}
}
#[test]
fn allowlist_mode_deny_rule_carves_out_of_a_broader_allow_prefix() {
// MEC-1096 F1: mecmcp_policy::Policy::check_command never consults
// the blocklist under CommandMode::Allowlist, so a broad `allow`
// prefix plus an explicit deny carve-out used to silently allow the
// denied command. Verify the carve-out now wins.
let p = build_policy(
r#"{
"_blocklist_defaults": {
"mode": "allowlist",
"allow": ["request system"],
"commands": [{"action":"deny","pattern":"request system reboot*"}]
},
"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
assert!(
p.check_command("r1", "request system software validate")
.is_allowed(),
"commands allowed by the prefix but not denied must still be allowed"
);
match p.check_command("r1", "request system reboot") {
Decision::Deny { rule, .. } => assert_eq!(rule.pattern, "request system reboot*"),
other => panic!("expected Deny (carve-out), got {other:?}"),
}
}
// --- MEC-1303: pfe_commands gets its own allow/allowed_pipes keys ---
#[test]
fn no_blocklist_defaults_selects_allowlist_and_refuses_all_pfe_commands() {
// Pre-fix baseline (MEC-1303): a fresh config with no policy section
// at all defaults to CommandMode::Allowlist (MEC-93) and, since
// `pfe_allow` defaults to empty, refuses every PFE command. This is
// the documented fail-closed regression the issue describes — still
// correct behavior for an unconfigured domain, just worth pinning so
// a future change that accidentally widens the default is caught.
let p = build_policy(
r#"{"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}}"#,
);
assert_eq!(p.command_mode(), CommandMode::Allowlist);
assert!(
!p.check_pfe_command("r1", "show cos").is_allowed(),
"empty pfe_allow must refuse even a benign PFE read"
);
}
#[test]
fn pfe_allow_permits_listed_command_and_refuses_unlisted_with_audit_reason() {
let p = build_policy(
r#"{
"_blocklist_defaults": {
"mode": "allowlist",
"pfe_allow": ["show cos"]
},
"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
assert!(
p.check_pfe_command("r1", "show cos classifier")
.is_allowed()
);
match p.check_pfe_command("r1", "show route") {
Decision::DenyAllowlist {
reason: AllowlistDenyReason::NotAllowlisted,
..
} => {}
other => panic!("expected DenyAllowlist(NotAllowlisted), got {other:?}"),
}
let decision = p.check_pfe_command("r1", "show route");
let err = enforce_decision(
decision,
"execute_junos_pfe_command",
"r1",
"show route",
BlocklistDomain::PfeCommands,
)
.unwrap_err();
match err {
JmcpError::DeniedAllowlist { reason, .. } => assert_eq!(reason, "not_allowlisted"),
other => panic!("expected DeniedAllowlist, got {other:?}"),
}
}
#[test]
fn pfe_allow_and_commands_allow_are_independent_domains() {
let p = build_policy(
r#"{
"_blocklist_defaults": {
"mode": "allowlist",
"allow": ["show version"],
"pfe_allow": ["show cos"]
},
"r1":{"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
assert!(
!p.check_pfe_command("r1", "show version").is_allowed(),
"commands allow must not leak into the pfe_commands domain"
);
assert!(
!p.check_command("r1", "show cos").is_allowed(),
"pfe_allow must not leak into the commands domain"
);
}
#[test]
fn per_device_pfe_allow_merges_with_defaults() {
let p = build_policy(
r#"{
"_blocklist_defaults": {"mode":"allowlist","pfe_allow":["show cos"]},
"r1":{
"ip":"1.1.1.1","username":"u","auth":{"type":"password","password":"x"},
"blocklist": {"pfe_allow": ["show route forwarding-table"]}
},
"r2":{"ip":"1.1.1.2","username":"u","auth":{"type":"password","password":"x"}}
}"#,
);
assert!(p.check_pfe_command("r1", "show cos").is_allowed());
assert!(
p.check_pfe_command("r1", "show route forwarding-table")
.is_allowed()
);
assert!(p.check_pfe_command("r2", "show cos").is_allowed());
assert!(
!p.check_pfe_command("r2", "show route forwarding-table")
.is_allowed(),
"device-scoped pfe_allow must not leak to other devices"
);
}
#[test]
fn pfe_allowed_pipes_gates_piped_pfe_commands() {
let p = build_policy(
r#"{
"_blocklist_defaults": {
"mode": "allowlist",
"pfe_allow": ["show cos"],
"pfe_allowed_pipes": ["match foo"]