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
use extract::{Context, Error, Extract, Immediate};
use std::ffi::{OsStr, OsString};
use std::path::{self, Path, PathBuf};
use util::buf_stream::BufStream;
fn check_for_path_traversal(path: &Path) -> Result<(), Error> {
use self::path::Component::*;
let path_traversal_error = || Error::invalid_argument(&"Path traversal detected");
let mut depth = 0u32;
for c in path.components() {
match c {
Prefix(_) | RootDir => {
Err(path_traversal_error())?
}
CurDir => {
}
ParentDir => {
depth = match depth.checked_sub(1) {
Some(v) => v,
None => Err(path_traversal_error())?,
}
}
Normal(_) => {
depth += 1;
}
}
}
Ok(())
}
fn decode(s: &OsStr) -> Result<PathBuf, Error> {
let path = PathBuf::from(s);
check_for_path_traversal(&path)?;
Ok(path)
}
impl<B: BufStream> Extract<B> for PathBuf {
type Future = Immediate<Self>;
fn extract(ctx: &Context) -> Self::Future {
use extract::ExtractFuture;
let s = <OsString as Extract<B>>::extract(ctx).extract();
Immediate::result(decode(&s))
}
}
#[cfg(test)]
mod test {
use super::*;
use std::path::Path;
#[test]
fn extract() {
assert_eq!(
decode(OsStr::new("hello, world")).unwrap(),
Path::new("hello, world")
);
}
#[test]
fn disallows_path_traversal() {
assert!(decode(OsStr::new("/")).unwrap_err().is_invalid_argument());
assert!(decode(OsStr::new("..")).unwrap_err().is_invalid_argument());
assert_eq!(decode(OsStr::new("a/..")).unwrap(), Path::new("a/.."));
assert!(
decode(OsStr::new("../a"))
.unwrap_err()
.is_invalid_argument()
);
assert!(
decode(OsStr::new("../a/b"))
.unwrap_err()
.is_invalid_argument()
);
assert_eq!(decode(OsStr::new("a/../b")).unwrap(), Path::new("a/../b"));
assert_eq!(decode(OsStr::new("a/b/..")).unwrap(), Path::new("a/b/.."));
}
}