kanidm_lib_file_permissions/
unix.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
303
304
305
use std::fs::Metadata;

#[cfg(target_os = "freebsd")]
use std::os::freebsd::fs::MetadataExt;

#[cfg(target_os = "linux")]
use std::os::linux::fs::MetadataExt;

#[cfg(target_os = "macos")]
use std::os::macos::fs::MetadataExt;

#[cfg(target_os = "illumos")]
use std::os::illumos::fs::MetadataExt;

use kanidm_utils_users::{get_current_gid, get_current_uid};

use std::fmt;
use std::path::{Path, PathBuf};

/// Check a given file's metadata is read-only for the current user (true = read-only)
pub fn readonly(meta: &Metadata) -> bool {
    // Who are we running as?
    let cuid = get_current_uid();
    let cgid = get_current_gid();

    // Who owns the file?
    // Who is the group owner of the file?
    let f_gid = meta.st_gid();
    let f_uid = meta.st_uid();

    let f_mode = meta.st_mode();

    !(
        // If we are the owner, we have write perms as we can alter the DAC rights
        cuid == f_uid ||
        // If we are the group owner, check the mode bits do not have write.
        (cgid == f_gid && (f_mode & 0o0020) != 0) ||
        // Finally, check that everyone bits don't have write.
        ((f_mode & 0o0002) != 0)
    )
}

#[derive(Debug)]
pub enum PathStatus {
    Dir {
        f_gid: u32,
        f_uid: u32,
        f_mode: u32,
        access: bool,
    },
    Link {
        f_gid: u32,
        f_uid: u32,
        f_mode: u32,
        access: bool,
    },
    File {
        f_gid: u32,
        f_uid: u32,
        f_mode: u32,
        access: bool,
    },
    Error(std::io::Error),
}

#[derive(Debug)]
pub struct Diagnosis {
    cuid: u32,
    cgid: u32,
    path: PathBuf,
    abs_path: Result<PathBuf, std::io::Error>,
    ancestors: Vec<(PathBuf, PathStatus)>,
}

impl fmt::Display for Diagnosis {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "-- diagnosis for path: {}", self.path.to_string_lossy())?;
        let indent = match &self.abs_path {
            Ok(abs) => {
                let abs_str = abs.to_string_lossy();
                writeln!(f, "canonicalised to: {}", abs_str)?;
                abs_str.len() + 1
            }
            Err(_) => {
                writeln!(f, "unable to canonicalise path")?;
                self.path.to_string_lossy().len() + 1
            }
        };

        writeln!(f, "running as: {}:{}", self.cuid, self.cgid)?;

        writeln!(f, "path permissions\n")?;
        for (anc, status) in &self.ancestors {
            match &status {
                PathStatus::Dir {
                    f_gid,
                    f_uid,
                    f_mode,
                    access,
                } => {
                    writeln!(
                        f,
                        "  {:indent$}: DIR access: {} owner: {} group: {} mode: {}",
                        anc.to_string_lossy(),
                        access,
                        f_uid,
                        f_gid,
                        mode_to_string(*f_mode)
                    )?;
                }
                PathStatus::Link {
                    f_gid,
                    f_uid,
                    f_mode,
                    access,
                } => {
                    writeln!(
                        f,
                        "  {:indent$}: LINK access: {} owner: {} group: {} mode: {}",
                        anc.to_string_lossy(),
                        access,
                        f_uid,
                        f_gid,
                        mode_to_string(*f_mode)
                    )?;
                }
                PathStatus::File {
                    f_gid,
                    f_uid,
                    f_mode,
                    access,
                } => {
                    writeln!(
                        f,
                        "  {:indent$}: FILE access: {} owner: {} group: {} mode: {}",
                        anc.to_string_lossy(),
                        access,
                        f_uid,
                        f_gid,
                        mode_to_string(*f_mode)
                    )?;
                }
                PathStatus::Error(err) => {
                    writeln!(f, "  {:indent$}: ERROR: {:?}", anc.to_string_lossy(), err)?;
                }
            }
        }

        writeln!(
            f,
            "\n  note that accessibility does not account for ACL's or MAC"
        )?;
        writeln!(f, "-- end diagnosis")
    }
}

pub fn diagnose_path(path: &Path) -> Diagnosis {
    // Who are we?
    let cuid = get_current_uid();
    let cgid = get_current_gid();

    // clone the path
    let path: PathBuf = path.into();

    // Display the abs/resolved path.
    let abs_path = path.canonicalize();

    // For each segment, from the root inc root
    // show the path -> owner/group mode
    //      or show that we have permission denied.
    let mut all_ancestors: Vec<_> = match &abs_path {
        Ok(ap) => ap.ancestors().collect(),
        Err(_) => path.ancestors().collect(),
    };

    let mut ancestors = Vec::with_capacity(all_ancestors.len());

    // Now pop from the right to start from the root.
    while let Some(anc) = all_ancestors.pop() {
        let status = match anc.metadata() {
            Ok(meta) => {
                let f_gid = meta.st_gid();
                let f_uid = meta.st_uid();
                let f_mode = meta.st_mode();
                if meta.is_dir() {
                    let access = x_accessible(cuid, cgid, f_uid, f_gid, f_mode);

                    PathStatus::Dir {
                        f_gid,
                        f_uid,
                        f_mode,
                        access,
                    }
                } else if meta.is_symlink() {
                    let access = x_accessible(cuid, cgid, f_uid, f_gid, f_mode);

                    PathStatus::Link {
                        f_gid,
                        f_uid,
                        f_mode,
                        access,
                    }
                } else {
                    let access = accessible(cuid, cgid, f_uid, f_gid, f_mode);

                    PathStatus::File {
                        f_gid,
                        f_uid,
                        f_mode,
                        access,
                    }
                }
            }
            Err(e) => PathStatus::Error(e),
        };

        ancestors.push((anc.into(), status))
    }

    Diagnosis {
        cuid,
        cgid,
        path,
        abs_path,
        ancestors,
    }
}

fn x_accessible(cuid: u32, cgid: u32, f_uid: u32, f_gid: u32, f_mode: u32) -> bool {
    (cuid == f_uid && f_mode & 0o500 == 0o500)
        || (cgid == f_gid && f_mode & 0o050 == 0o050)
        || f_mode & 0o005 == 0o005
}

fn accessible(cuid: u32, cgid: u32, f_uid: u32, f_gid: u32, f_mode: u32) -> bool {
    (cuid == f_uid && f_mode & 0o400 == 0o400)
        || (cgid == f_gid && f_mode & 0o040 == 0o040)
        || f_mode & 0o004 == 0o004
}

fn mode_to_string(mode: u32) -> String {
    let mut mode_str = String::with_capacity(9);
    if mode & 0o400 != 0 {
        mode_str.push('r')
    } else {
        mode_str.push('-')
    }

    if mode & 0o200 != 0 {
        mode_str.push('w')
    } else {
        mode_str.push('-')
    }

    if mode & 0o100 != 0 {
        mode_str.push('x')
    } else {
        mode_str.push('-')
    }

    if mode & 0o040 != 0 {
        mode_str.push('r')
    } else {
        mode_str.push('-')
    }

    if mode & 0o020 != 0 {
        mode_str.push('w')
    } else {
        mode_str.push('-')
    }

    if mode & 0o010 != 0 {
        mode_str.push('x')
    } else {
        mode_str.push('-')
    }

    if mode & 0o004 != 0 {
        mode_str.push('r')
    } else {
        mode_str.push('-')
    }

    if mode & 0o002 != 0 {
        mode_str.push('w')
    } else {
        mode_str.push('-')
    }

    if mode & 0o001 != 0 {
        mode_str.push('x')
    } else {
        mode_str.push('-')
    }

    mode_str
}

#[test]
fn test_readonly() {
    let meta = std::fs::metadata("Cargo.toml").expect("Can't find Cargo.toml");
    println!("meta={:?} -> readonly={:?}", meta, readonly(&meta));
    assert!(!readonly(&meta));
}