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
use blocking::{unblock, Unblock};
use log::trace;
use std::fs::{self, File};
use std::io;
use std::net::SocketAddr;
use std::path::Component;
use std::path::{Path, PathBuf};

use crate::error::{Error, Result};
use crate::packet;

/// Handler that serves read requests for a directory.
pub struct DirHandler {
    dir: PathBuf,
    serve_rrq: bool,
    serve_wrq: bool,
}

pub enum DirHandlerMode {
    /// Serve only read requests.
    ReadOnly,
    /// Serve only write requests.
    WriteOnly,
    /// Server read and write requests.
    ReadWrite,
}

impl DirHandler {
    /// Create new handler for directory.
    pub fn new<P>(dir: P, flags: DirHandlerMode) -> Result<Self>
    where
        P: AsRef<Path>,
    {
        let dir = fs::canonicalize(dir.as_ref())?;

        if !dir.is_dir() {
            return Err(Error::NotDir(dir));
        }

        trace!("TFTP directory: {}", dir.display());

        let serve_rrq = match flags {
            DirHandlerMode::ReadOnly => true,
            DirHandlerMode::WriteOnly => false,
            DirHandlerMode::ReadWrite => true,
        };

        let serve_wrq = match flags {
            DirHandlerMode::ReadOnly => false,
            DirHandlerMode::WriteOnly => true,
            DirHandlerMode::ReadWrite => true,
        };

        Ok(DirHandler {
            dir,
            serve_rrq,
            serve_wrq,
        })
    }
}

#[crate::async_trait]
impl crate::server::Handler for DirHandler {
    type Reader = Unblock<File>;
    type Writer = Unblock<File>;

    async fn read_req_open(
        &mut self,
        _client: &SocketAddr,
        path: &Path,
    ) -> Result<(Self::Reader, Option<u64>), packet::Error> {
        if !self.serve_rrq {
            return Err(packet::Error::IllegalOperation);
        }

        let path = secure_path(&self.dir, path)?;

        // Send only regular files
        if !path.is_file() {
            return Err(packet::Error::FileNotFound);
        }

        let path_clone = path.clone();
        let (file, len) = unblock(move || open_file_ro(path_clone)).await?;
        let reader = Unblock::new(file);

        trace!("TFTP sending file: {}", path.display());

        Ok((reader, len))
    }

    async fn write_req_open(
        &mut self,
        _client: &SocketAddr,
        path: &Path,
        size: Option<u64>,
    ) -> Result<Self::Writer, packet::Error> {
        if !self.serve_wrq {
            return Err(packet::Error::IllegalOperation);
        }

        let path = secure_path(&self.dir, path)?;

        let path_clone = path.clone();
        let file = unblock(move || open_file_wo(path_clone, size)).await?;
        let writer = Unblock::new(file);

        trace!("TFTP receiving file: {}", path.display());

        Ok(writer)
    }
}

fn secure_path(
    restricted_dir: &Path,
    path: &Path,
) -> Result<PathBuf, packet::Error> {
    // Strip `/` and `./` prefixes
    let path = path
        .strip_prefix("/")
        .or_else(|_| path.strip_prefix("./"))
        .unwrap_or(path);

    // Avoid directory traversal attack by filtering `../`.
    if path.components().any(|x| x == Component::ParentDir) {
        return Err(packet::Error::PermissionDenied);
    }

    // Path should not start from root dir or have any Windows prefixes.
    // i.e. We accept only normal path components.
    match path.components().next() {
        Some(Component::Normal(_)) => {}
        _ => return Err(packet::Error::PermissionDenied),
    }

    Ok(restricted_dir.join(path))
}

fn open_file_ro(path: PathBuf) -> io::Result<(File, Option<u64>)> {
    let file = File::open(&path)?;
    let len = file.metadata().ok().map(|m| m.len());
    Ok((file, len))
}

fn open_file_wo(path: PathBuf, size: Option<u64>) -> io::Result<File> {
    let file = File::create(path)?;

    if let Some(size) = size {
        file.set_len(size)?;
    }

    Ok(file)
}