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
pub mod db;
pub mod http;
pub mod processing;
pub mod utils;

use malwaredb_api::ServerInfo;
//use utils::HashPath;

use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use anyhow::{bail, Result};
use duration_string::DurationString;
use sha2::{Digest, Sha256};

/// MDB version
pub const MDB_VERSION: &str = env!("CARGO_PKG_VERSION");

//const HASH_DEPTH: usize = 3;

pub struct State {
    /// The port which will be used to listen for connections.
    pub port: u16,

    /// The directory to store malware samples, if we're keeping them.
    pub directory: Option<PathBuf>,

    /// Maximum upload size
    pub max_upload: usize,

    /// The IP to use for listening for connections
    pub ip: IpAddr,

    /// Handle to the database connection
    pub db_type: db::DatabaseType,

    /// Start time of the server
    pub started: SystemTime,
}

impl State {
    pub async fn new(
        port: u16,
        directory: Option<PathBuf>,
        max_upload: usize,
        ip: IpAddr,
        db_string: &str,
    ) -> Result<Self> {
        if let Some(dir) = &directory {
            if !dir.exists() {
                bail!("data directory {dir:?} does not exist!");
            }
        }

        Ok(Self {
            port,
            directory,
            max_upload,
            ip,
            db_type: db::DatabaseType::from_string(db_string).await?,
            started: SystemTime::now(),
        })
    }

    /// Store the sample with a depth of three based on the sample's SHA-256 hash
    /// In the future, the depth and hash function could be configured and saved in the database.
    /// But a change of this configuration would require visiting and reprocessing all previously-stored files!
    pub fn store_bytes(&self, data: &[u8]) -> Result<bool> {
        if let Some(dest_path) = &self.directory {
            let mut hasher = Sha256::new();
            hasher.update(data);
            let sha256 = hex::encode(hasher.finalize());

            // Trait `HashPath` needs to be re-worked so it can work with Strings.
            // This code below ends up making the String into ASCII representations of the hash
            // See: https://github.com/malwaredb/malwaredb-rs/issues/60
            let hashed_path = format!(
                "{}/{}/{}/{}",
                &sha256[0..2],
                &sha256[2..4],
                &sha256[4..6],
                sha256
            );

            // The path which has the file name included, with the storage directory prepended.
            //let hashed_path = result.hashed_path(HASH_DEPTH);
            let mut dest_path = dest_path.clone();
            dest_path.push(hashed_path);

            // Remove the file name so we can just have the directory path.
            let mut just_the_dir = dest_path.clone();
            just_the_dir.pop();
            std::fs::create_dir_all(just_the_dir)?;

            std::fs::write(dest_path, data)?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Retrieve a sample given the SHA-256 hash
    /// Assumes that permissions have already been checked to ensure this is permitted.
    pub fn retrieve_bytes(&self, sha256: &String) -> Result<Vec<u8>> {
        if let Some(dest_path) = &self.directory {
            let path = format!(
                "{}/{}/{}/{}",
                &sha256[0..2],
                &sha256[2..4],
                &sha256[4..6],
                sha256
            );
            // Trait `HashPath` needs to be re-worked so it can work with Strings.
            // This code below ends up making the String into ASCII representations of the hash
            // See: https://github.com/malwaredb/malwaredb-rs/issues/60
            //let path = sha256.as_bytes().iter().hashed_path(HASH_DEPTH);
            let contents = std::fs::read(dest_path.join(path))?;
            Ok(contents)
        } else {
            bail!("files are not saved")
        }
    }

    pub fn since(&self) -> Duration {
        let now = SystemTime::now();
        now.duration_since(self.started).unwrap()
    }

    pub async fn get_info(&self) -> Result<ServerInfo> {
        let db_info = self.db_type.db_info().await?;

        let os_name = if cfg!(target_os = "linux") {
            "Linux"
        } else if cfg!(target_os = "macos") {
            "macOS"
        } else if cfg!(target_os = "windows") {
            "Windows"
        } else if cfg!(target_os = "freebsd") {
            "FreeBSD"
        } else if cfg!(target_os = "openbsd") {
            "OpenBSD"
        } else if cfg!(target_os = "netbsd") {
            "NetBSD"
        } else if cfg!(target_os = "wasi") {
            "WebAssembly WASI"
        } else {
            "unknown"
        };

        let mem_size = if cfg!(target_family = "unix") {
            if let Ok(statm) = std::fs::read_to_string("/proc/self/statm") {
                let mut parts = statm.split(' ');
                if let Some(total_memory) = parts.next() {
                    if let Ok(memory_integer) = u64::from_str(total_memory) {
                        humansize::SizeFormatter::new(memory_integer, humansize::BINARY).to_string()
                    } else {
                        "".into()
                    }
                } else {
                    "".into()
                }
            } else {
                "".into()
            }
        } else {
            "".into()
        };

        Ok(ServerInfo {
            os_name: os_name.into(),
            os_version: "".to_string(),
            memory_used: mem_size,
            num_samples: db_info.num_files,
            num_users: db_info.num_users,
            uptime: DurationString::from(self.since()),
            mdb_version: MDB_VERSION.into(),
            db_version: db_info.version,
            db_size: db_info.size,
        })
    }

    pub async fn serve(self) -> Result<()> {
        let socket = SocketAddr::new(self.ip, self.port);
        println!("Listening on {socket:?}");
        axum::Server::bind(&socket)
            .serve(http::app(Arc::new(self)).into_make_service())
            .await?;

        Ok(())
    }
}

pub fn init_tracing() {
    if std::env::var("RUST_LOG_JSON").is_ok() {
        tracing_subscriber::fmt::fmt()
            .json()
            .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
            .init();
    } else {
        tracing_subscriber::fmt::init();
    }
}