Skip to main content

exarch_core/security/
permissions.rs

1//! File permission validation and sanitization.
2
3use crate::SecurityConfig;
4
5/// A Unix permission mode exactly as an archive header records it.
6///
7/// The only consumer is `sanitize_permissions`, so a raw mode cannot be
8/// passed where a [`SanitizedMode`] is expected, and the reverse.
9///
10/// # Examples
11///
12/// ```
13/// use exarch_core::security::RawMode;
14///
15/// assert_eq!(RawMode::new(0o4755).get(), 0o4755);
16/// ```
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct RawMode(u32);
19
20impl RawMode {
21    /// Wraps the mode bits read from an archive header.
22    #[must_use]
23    pub const fn new(bits: u32) -> Self {
24        Self(bits)
25    }
26
27    /// Returns the unsanitized bits.
28    #[must_use]
29    pub const fn get(self) -> u32 {
30        self.0
31    }
32}
33
34/// A Unix permission mode that has already passed through
35/// `sanitize_permissions`.
36///
37/// This newtype closes the gap between "a raw mode read from an archive
38/// header" and "a mode safe to apply to an extracted file": both are
39/// otherwise a plain `u32`, so a caller could pass an unsanitized mode to
40/// permission-setting code by mistake, with the invariant living only in a
41/// doc comment. `SanitizedMode` can only be constructed by
42/// `sanitize_permissions` — its single field is private, so external
43/// callers (and other modules in this crate) cannot fabricate one that
44/// skipped the setuid/setgid/world-writable stripping.
45///
46/// # Examples
47///
48/// ```
49/// # #[cfg(feature = "testing")]
50/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
51/// use exarch_core::SecurityConfig;
52/// use exarch_core::security::RawMode;
53/// use exarch_core::security::sanitize_permissions;
54///
55/// let config = SecurityConfig::default();
56///
57/// // Setuid bit is stripped
58/// let sanitized = sanitize_permissions(RawMode::new(0o4755), &config);
59/// assert_eq!(sanitized.as_u32(), 0o755);
60/// # Ok(())
61/// # }
62/// # #[cfg(not(feature = "testing"))]
63/// # fn main() {}
64/// ```
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct SanitizedMode(u32);
67
68impl SanitizedMode {
69    /// Returns the sanitized mode as a raw Unix permission bitmask.
70    #[inline]
71    #[must_use]
72    pub fn as_u32(self) -> u32 {
73        self.0
74    }
75}
76
77/// Sanitizes file permissions by stripping dangerous bits.
78///
79/// This function removes security-sensitive permission bits that could
80/// lead to privilege escalation:
81/// - Setuid bit (04000): Allows execution with file owner's privileges
82/// - Setgid bit (02000): Allows execution with file group's privileges
83/// - World-writable bit (0002): Stripped by default unless
84///   `allow_world_writable` is set
85///
86/// The [`SanitizedMode`] return type is the only way to obtain a sanitized
87/// mode in this crate, so a caller cannot accidentally pass a raw,
88/// unsanitized mode to internal permission-setting code such as
89/// `VettedDir::create_new`.
90///
91/// # Performance
92///
93/// This is a pure computation with no I/O. Typical execution time: <10 ns.
94///
95/// # Examples
96///
97/// ```
98/// # #[cfg(feature = "testing")]
99/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
100/// use exarch_core::SecurityConfig;
101/// use exarch_core::security::RawMode;
102/// use exarch_core::security::sanitize_permissions;
103///
104/// let config = SecurityConfig::default();
105///
106/// // Setuid bit is stripped
107/// let sanitized = sanitize_permissions(RawMode::new(0o4755), &config);
108/// assert_eq!(sanitized.as_u32(), 0o755);
109///
110/// // Setgid bit is stripped
111/// let sanitized = sanitize_permissions(RawMode::new(0o2755), &config);
112/// assert_eq!(sanitized.as_u32(), 0o755);
113///
114/// // Both setuid and setgid bits stripped
115/// let sanitized = sanitize_permissions(RawMode::new(0o6755), &config);
116/// assert_eq!(sanitized.as_u32(), 0o755);
117///
118/// // World-writable bit is stripped by default
119/// let sanitized = sanitize_permissions(RawMode::new(0o777), &config);
120/// assert_eq!(sanitized.as_u32(), 0o775);
121/// # Ok(())
122/// # }
123/// # #[cfg(not(feature = "testing"))]
124/// # fn main() {}
125/// ```
126#[must_use]
127pub fn sanitize_permissions(mode: RawMode, config: &SecurityConfig) -> SanitizedMode {
128    let mut sanitized = mode.get();
129
130    // Strip setuid bit (04000)
131    sanitized &= !0o4000;
132
133    // Strip setgid bit (02000)
134    sanitized &= !0o2000;
135
136    // M-CODE-1: Strip world-writable bit (0002) unless explicitly allowed
137    if !config.allowed.world_writable.is_allowed() {
138        sanitized &= !0o002;
139    }
140
141    SanitizedMode(sanitized)
142}
143
144#[cfg(test)]
145#[allow(clippy::expect_used)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn test_sanitize_permissions_normal() {
151        let config = SecurityConfig::default();
152        assert_eq!(
153            sanitize_permissions(RawMode::new(0o644), &config).as_u32(),
154            0o644
155        );
156    }
157
158    #[test]
159    fn test_sanitize_permissions_executable() {
160        let config = SecurityConfig::default();
161        assert_eq!(
162            sanitize_permissions(RawMode::new(0o755), &config).as_u32(),
163            0o755
164        );
165    }
166
167    #[test]
168    fn test_sanitize_permissions_strip_setuid() {
169        let config = SecurityConfig::default();
170        assert_eq!(
171            sanitize_permissions(RawMode::new(0o4755), &config).as_u32(),
172            0o755
173        );
174    }
175
176    #[test]
177    fn test_sanitize_permissions_strip_setgid() {
178        let config = SecurityConfig::default();
179        assert_eq!(
180            sanitize_permissions(RawMode::new(0o2755), &config).as_u32(),
181            0o755
182        );
183    }
184
185    #[test]
186    fn test_sanitize_permissions_strip_both() {
187        let config = SecurityConfig::default();
188        assert_eq!(
189            sanitize_permissions(RawMode::new(0o6755), &config).as_u32(),
190            0o755
191        );
192    }
193
194    #[test]
195    fn test_sanitize_permissions_strip_world_writable() {
196        let config = SecurityConfig::default();
197        assert_eq!(
198            sanitize_permissions(RawMode::new(0o777), &config).as_u32(),
199            0o775
200        );
201    }
202
203    #[test]
204    fn test_sanitize_permissions_world_readable_ok() {
205        let config = SecurityConfig::default();
206        assert_eq!(
207            sanitize_permissions(RawMode::new(0o644), &config).as_u32(),
208            0o644
209        );
210    }
211
212    #[test]
213    fn test_sanitize_permissions_owner_writable_ok() {
214        let config = SecurityConfig::default();
215        assert_eq!(
216            sanitize_permissions(RawMode::new(0o600), &config).as_u32(),
217            0o600
218        );
219    }
220
221    #[test]
222    fn test_sanitize_permissions_group_writable_ok() {
223        let config = SecurityConfig::default();
224        assert_eq!(
225            sanitize_permissions(RawMode::new(0o664), &config).as_u32(),
226            0o664
227        );
228    }
229
230    #[test]
231    fn test_sanitize_permissions_edge_case_zero() {
232        let config = SecurityConfig::default();
233        assert_eq!(
234            sanitize_permissions(RawMode::new(0o000), &config).as_u32(),
235            0o000
236        );
237    }
238
239    #[test]
240    fn test_sticky_bit_preservation() {
241        let config = SecurityConfig::default();
242        let sanitized = sanitize_permissions(RawMode::new(0o1755), &config).as_u32();
243        assert_eq!(sanitized & 0o1000, 0o1000, "sticky bit should be preserved");
244        assert_eq!(sanitized, 0o1755, "full mode should be preserved");
245    }
246
247    #[test]
248    fn test_sticky_bit_with_setuid_stripped() {
249        let config = SecurityConfig::default();
250        let sanitized = sanitize_permissions(RawMode::new(0o7755), &config).as_u32();
251        assert_eq!(sanitized & 0o1000, 0o1000, "sticky bit should remain");
252        assert_eq!(sanitized & 0o4000, 0, "setuid should be stripped");
253        assert_eq!(sanitized & 0o2000, 0, "setgid should be stripped");
254        assert_eq!(sanitized, 0o1755, "result should be sticky + rwxr-xr-x");
255    }
256
257    // M-CODE-1: Test world-writable with config flag
258    #[test]
259    fn test_world_writable_allowed_with_config() {
260        let mut config = SecurityConfig::default();
261        config.allowed.world_writable = crate::Admit::Allow;
262        let sanitized = sanitize_permissions(RawMode::new(0o777), &config).as_u32();
263        assert_eq!(
264            sanitized & 0o002,
265            0o002,
266            "world-writable bit should be preserved"
267        );
268        assert_eq!(sanitized & 0o4000, 0, "setuid should be stripped");
269        assert_eq!(sanitized & 0o2000, 0, "setgid should be stripped");
270        assert_eq!(sanitized, 0o777, "result should be rwxrwxrwx");
271    }
272
273    #[test]
274    fn test_world_writable_stripped_by_default() {
275        let config = SecurityConfig::default();
276        assert_eq!(
277            sanitize_permissions(RawMode::new(0o777), &config).as_u32(),
278            0o775,
279            "world-writable bit should be stripped by default"
280        );
281    }
282
283    #[test]
284    fn test_world_writable_bit_only_stripped() {
285        let config = SecurityConfig::default();
286        // 0o666 = rw-rw-rw-, only other-write (0o002) should be stripped ->
287        // 0o664
288        assert_eq!(
289            sanitize_permissions(RawMode::new(0o666), &config).as_u32(),
290            0o664,
291            "only world-writable bit should be stripped, not group-write"
292        );
293    }
294}