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
pub mod db;
pub mod http;
pub mod processing;
pub mod utils;
#[cfg(feature = "vt")]
pub mod vt;

use crate::db::MDBConfig;
use malwaredb_api::ServerInfo;
//use utils::HashPath;

use std::io::{Cursor, Read, Write};
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 chrono::Local;
use chrono_humanize::{Accuracy, HumanTime, Tense};
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use sha2::{Digest, Sha256};
use tokio::net::TcpListener;
#[cfg(feature = "vt")]
use zeroize::Zeroizing;

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

/// GZip magic number to see if a file is compressed
pub const GZIP_MAGIC: [u8; 2] = [0x1fu8, 0x8bu8];

//const HASH_DEPTH: usize = 3;

/// State & configuration of the running server instance
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,

    /// Configuration which is stored in the database
    pub db_config: MDBConfig,

    /// VirusTotal API key
    #[cfg(feature = "vt")]
    vt_api_key: Option<Zeroizing<String>>,
}

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

        let db_type = db::DatabaseType::from_string(db_string).await?;
        let db_config = db_type.get_config().await?;

        Ok(Self {
            port,
            directory,
            max_upload,
            ip,
            db_type,
            db_config,
            #[cfg(feature = "vt")]
            vt_api_key,
            started: SystemTime::now(),
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn new_first_run(
        port: u16,
        directory: Option<PathBuf>,
        max_upload: usize,
        ip: IpAddr,
        db_string: &str,
        #[cfg(feature = "vt")] vt_api_key: Option<Zeroizing<String>>,
        compress: bool,
        #[cfg(feature = "vt")] send_samples_to_vt: bool,
    ) -> Result<Self> {
        if let Some(dir) = &directory {
            if !dir.exists() {
                bail!("data directory {dir:?} does not exist!");
            }
        }

        let db_type = db::DatabaseType::from_string(db_string).await?;

        if db_type.first_run() {
            println!("Welcome to MalwareDB {}!", MDB_VERSION);
            if compress {
                db_type.enable_compression().await?;
            }
            #[cfg(feature = "vt")]
            if send_samples_to_vt {
                db_type.enable_vt_upload().await?;
            }
        } else {
            bail!("Attempting to set first-run options when not first-run");
        }

        let db_config = db_type.get_config().await?;

        Ok(Self {
            port,
            directory,
            max_upload,
            ip,
            db_type,
            db_config,
            #[cfg(feature = "vt")]
            vt_api_key,
            started: SystemTime::now(),
        })
    }

    /// Store the sample with a depth of three based on the sample's SHA-256 hash, even if compressed
    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)?;

            if self.db_config.compression {
                let mut compressor = GzEncoder::new(Vec::new(), Compression::default());
                compressor.write_all(data)?;
                let compressed_data = compressor.finish()?;
                std::fs::write(dest_path, compressed_data)?;
            } else {
                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))?;
            if contents.starts_with(&GZIP_MAGIC) {
                let buff = Cursor::new(contents);
                let mut decompressor = GzDecoder::new(buff);
                let mut decompressed: Vec<u8> = vec![];
                decompressor.read_to_end(&mut decompressed)?;
                Ok(decompressed)
            } else {
                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()
        };

        let uptime = Local::now() - self.since();

        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: HumanTime::from(uptime).to_text_en(Accuracy::Rough, Tense::Present),
            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);
        let listener = TcpListener::bind(socket).await.unwrap();
        println!("Listening on {socket:?}");
        axum::serve(listener, http::app(Arc::new(self)).into_make_service()).await?;

        Ok(())
    }
}