malwaredb_client/
lib.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]

use malwaredb_lzjd::{LZDict, Murmur3HashState};
use malwaredb_types::exec::pe32::EXE;
use malwaredb_types::utils::entropy_calc;

use std::fmt::{Debug, Formatter};
use std::io::Cursor;
use std::path::Path;

use anyhow::{bail, Context, Result};
use base64::engine::general_purpose;
use base64::Engine;
use cart_container::JsonMap;
use fuzzyhash::FuzzyHash;
use home::home_dir;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256, Sha384, Sha512};
use tlsh_fixed::TlshBuilder;
use tracing::{error, warn};
use zeroize::{Zeroize, ZeroizeOnDrop};

/// Config file name expected by MalwareDB Client
const DOT_MDB_CLIENT_TOML: &str = ".mdb_client.toml";

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

/// MalwareDB Client Configuration and connection
#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
pub struct MdbClient {
    /// URL of MalwareDB, including http and port number, ending without a slash
    pub url: String,

    /// User's API key for MalwareDB
    api_key: String,
}

impl MdbClient {
    /// MDB Client from components, doesn't test connectivity
    pub fn new(url: String, api_key: String) -> Self {
        let mut url = url;
        let url = if url.ends_with('/') {
            url.pop();
            url
        } else {
            url
        };

        Self { url, api_key }
    }

    /// Generate a client which already knows to send the API key, and asks for gzip responses.
    fn client() -> reqwest::Result<reqwest::Client> {
        reqwest::ClientBuilder::new().gzip(true).build()
    }

    /// Login to a server, optionally save the config file, and return a client object
    pub async fn login(
        url: String,
        username: String,
        password: String,
        save: bool,
    ) -> Result<Self> {
        let mut url = url;
        let url = if url.ends_with('/') {
            url.pop();
            url
        } else {
            url
        };

        let api_request = malwaredb_api::GetAPIKeyRequest {
            user: username,
            password,
        };

        let res = MdbClient::client()?
            .post(format!("{url}{}", malwaredb_api::USER_LOGIN_URL))
            .json(&api_request)
            .send()
            .await?
            .json::<malwaredb_api::GetAPIKeyResponse>()
            .await?;

        if let Some(key) = &res.key {
            let client = MdbClient {
                url,
                api_key: key.clone(),
            };

            if save {
                if let Err(e) = client.save() {
                    error!("Login successful but failed to save config: {e}");
                    bail!("Login successful but failed to save config: {e}");
                }
            }
            Ok(client)
        } else {
            if let Some(msg) = &res.message {
                error!("Login failed, response: {msg}");
            }
            bail!("server error or bad credentials");
        }
    }

    /// Reset one's own API key to effectively logout & disable all clients who are using the key
    pub async fn reset_key(&self) -> Result<()> {
        let response = MdbClient::client()?
            .get(format!("{}{}", self.url, malwaredb_api::USER_LOGOUT_URL))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .send()
            .await
            .context("server error, or invalid API key")?;
        if response.status().is_success() {
            bail!("failed to reset API key, was it correct?");
        }
        Ok(())
    }

    /// MDB Client loaded from a specified path
    pub fn from_file(path: &std::path::PathBuf) -> Result<Self> {
        let config = std::fs::read_to_string(path)
            .context(format!("failed to read config file {}", path.display()))?;
        let cfg: MdbClient = toml::from_str(&config)
            .context(format!("failed to parse config file {}", path.display()))?;
        Ok(cfg)
    }

    /// MDB Client from user's home directory
    pub fn load() -> Result<Self> {
        let config = Path::new("mdb_client.toml");
        if config.exists() {
            return Self::from_file(&config.to_path_buf());
        }

        if let Some(mut home_config) = home_dir() {
            home_config.push(DOT_MDB_CLIENT_TOML);
            if home_config.exists() {
                return Self::from_file(&home_config);
            }
        }
        bail!("config file not found")
    }

    /// Save MDB Client to the user's home directory
    pub fn save(&self) -> Result<()> {
        let toml = toml::to_string(self)?;
        if let Some(mut home_config) = home_dir() {
            home_config.push(DOT_MDB_CLIENT_TOML);
            std::fs::write(&home_config, toml).context(format!(
                "Unable to write config file at {}",
                &home_config.display()
            ))?;
            return Ok(());
        }

        std::fs::write("mdb_client.toml", toml).context("failed to write mdb config")
    }

    /// Delete the MalwareDB client config file
    pub fn delete(&self) -> Result<()> {
        if let Some(mut home_config) = home_dir() {
            home_config.push(DOT_MDB_CLIENT_TOML);
            if home_config.exists() {
                std::fs::remove_file(home_config)?;
            }
        }
        Ok(())
    }

    // Actions of the client

    /// Get information about the server, unauthenticated
    pub async fn server_info(&self) -> Result<malwaredb_api::ServerInfo> {
        MdbClient::client()?
            .get(format!("{}{}", self.url, malwaredb_api::SERVER_INFO))
            .send()
            .await?
            .json::<malwaredb_api::ServerInfo>()
            .await
            .context("failed to receive or decode server info")
    }

    /// Get file types supported by the server, unauthenticated
    pub async fn supported_types(&self) -> Result<malwaredb_api::SupportedFileTypes> {
        MdbClient::client()?
            .get(format!(
                "{}{}",
                self.url,
                malwaredb_api::SUPPORTED_FILE_TYPES
            ))
            .send()
            .await?
            .json::<malwaredb_api::SupportedFileTypes>()
            .await
            .context("failed to receive or decode server-supported file types")
    }

    /// Get information about the user
    pub async fn whoami(&self) -> Result<malwaredb_api::GetUserInfoResponse> {
        MdbClient::client()?
            .get(format!("{}{}", self.url, malwaredb_api::USER_INFO_URL))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .send()
            .await?
            .json::<malwaredb_api::GetUserInfoResponse>()
            .await
            .context("failed to receive or decode user info, or invalid API key")
    }

    /// Get the sample labels known to the server
    pub async fn labels(&self) -> Result<malwaredb_api::Labels> {
        MdbClient::client()?
            .get(format!("{}{}", self.url, malwaredb_api::LIST_LABELS))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .send()
            .await?
            .json::<malwaredb_api::Labels>()
            .await
            .context("failed to receive or decode available labels, or invalid API key")
    }

    /// Get the sources available to the current user
    pub async fn sources(&self) -> Result<malwaredb_api::Sources> {
        MdbClient::client()?
            .get(format!("{}{}", self.url, malwaredb_api::LIST_SOURCES))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .send()
            .await?
            .json::<malwaredb_api::Sources>()
            .await
            .context("failed to receive or decode available labels, or invalid API key")
    }

    /// Submit one file to MalwareDB: provide the contents, file name, and source ID
    pub async fn submit(
        &self,
        contents: impl AsRef<[u8]>,
        file_name: &str,
        source_id: u32,
    ) -> Result<bool> {
        let mut hasher = Sha256::new();
        hasher.update(&contents);
        let result = hasher.finalize();

        let encoded = general_purpose::STANDARD.encode(contents);

        let payload = malwaredb_api::NewSample {
            file_name: file_name.to_string(),
            source_id,
            file_contents_b64: encoded,
            sha256: hex::encode(result),
        };

        match MdbClient::client()?
            .post(format!("{}{}", self.url, malwaredb_api::UPLOAD_SAMPLE))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .json(&payload)
            .send()
            .await
        {
            Ok(res) => {
                if !res.status().is_success() {
                    warn!("Code {} sending {file_name}", res.status());
                }
                Ok(res.status().is_success())
            }
            Err(e) => {
                let status: String = e
                    .status()
                    .map(|s| s.as_str().to_string())
                    .unwrap_or_default();
                error!("Error{status} sending {file_name}: {e}");
                bail!(e.to_string())
            }
        }
    }

    /// Retrieve sample by hash, optionally in the CaRT format
    pub async fn retrieve(&self, hash: &str, cart: bool) -> Result<Vec<u8>> {
        let api_endpoint = if cart {
            format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE_CART)
        } else {
            format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE)
        };

        let res = MdbClient::client()?
            .get(format!("{}{api_endpoint}", self.url))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .send()
            .await?;

        if !res.status().is_success() {
            bail!("Received code {}", res.status());
        }

        let body = res.bytes().await?;
        Ok(body.to_vec())
    }

    /// Fetch a report for a sample
    pub async fn report(&self, hash: &str) -> Result<malwaredb_api::Report> {
        MdbClient::client()?
            .get(format!(
                "{}{}/{hash}",
                self.url,
                malwaredb_api::SAMPLE_REPORT
            ))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .send()
            .await?
            .json::<malwaredb_api::Report>()
            .await
            .context("failed to receive or decode sample report, or invalid API key")
    }

    /// Find similar samples in MalwareDB based on the contents of a given file.
    /// This does not submit the sample to MalwareDB.
    pub async fn similar(&self, contents: &[u8]) -> Result<malwaredb_api::SimilarSamplesResponse> {
        let mut hashes = vec![];
        let ssdeep_hash = FuzzyHash::new(contents);

        let build_hasher = Murmur3HashState::default();
        let lzjd_str =
            LZDict::from_bytes_stream(contents.iter().copied(), &build_hasher).to_string();
        hashes.push((malwaredb_api::SimilarityHashType::LZJD, lzjd_str));
        hashes.push((
            malwaredb_api::SimilarityHashType::SSDeep,
            ssdeep_hash.to_string(),
        ));

        let mut builder = TlshBuilder::new(
            tlsh_fixed::BucketKind::Bucket256,
            tlsh_fixed::ChecksumKind::ThreeByte,
            tlsh_fixed::Version::Version4,
        );

        builder.update(contents);
        if let Ok(hasher) = builder.build() {
            hashes.push((malwaredb_api::SimilarityHashType::TLSH, hasher.hash()));
        }

        if let Ok(exe) = EXE::from(contents) {
            if let Some(imports) = exe.imports {
                hashes.push((
                    malwaredb_api::SimilarityHashType::ImportHash,
                    hex::encode(imports.hash()),
                ));
                hashes.push((
                    malwaredb_api::SimilarityHashType::FuzzyImportHash,
                    imports.fuzzy_hash(),
                ));
            }
        }

        let request = malwaredb_api::SimilarSamplesRequest { hashes };

        MdbClient::client()?
            .post(format!("{}{}", self.url, malwaredb_api::SIMILAR_SAMPLES))
            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
            .json(&request)
            .send()
            .await?
            .json::<malwaredb_api::SimilarSamplesResponse>()
            .await
            .context("failed to receive or decode similarity response, or invalid API key")
    }
}

impl Debug for MdbClient {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "MDB Client v{MDB_VERSION}: {}", self.url)
    }
}

/// Convenience function for encoding bytes into a CaRT file using the default key. This also
/// adds SHA-384 and SHA-512 hashes plus the entropy of the original file.
/// See https://github.com/CybercentreCanada/cart for more information.
pub fn encode_to_cart(data: &[u8]) -> Result<Vec<u8>> {
    let mut input_buffer = Cursor::new(data);
    let mut output_buffer = Cursor::new(vec![]);
    let mut output_metadata = JsonMap::new();

    let mut sha384 = Sha384::new();
    sha384.update(data);
    let sha384 = hex::encode(sha384.finalize());

    let mut sha512 = Sha512::new();
    sha512.update(data);
    let sha512 = hex::encode(sha512.finalize());

    output_metadata.insert("sha384".into(), sha384.into());
    output_metadata.insert("sha512".into(), sha512.into());
    output_metadata.insert("entropy".into(), entropy_calc(data).into());
    cart_container::pack_stream(
        &mut input_buffer,
        &mut output_buffer,
        Some(output_metadata),
        None,
        cart_container::digesters::default_digesters(),
        None,
    )?;

    Ok(output_buffer.into_inner())
}

/// Convenience function for decoding a CaRT file using the default key, returning the bytes plus the
/// optional header & footer metadata, if present.
/// See https://github.com/CybercentreCanada/cart for more information.
pub fn decode_from_cart(data: &[u8]) -> Result<(Vec<u8>, Option<JsonMap>, Option<JsonMap>)> {
    let mut input_buffer = Cursor::new(data);
    let mut output_buffer = Cursor::new(vec![]);
    let (header, footer) =
        cart_container::unpack_stream(&mut input_buffer, &mut output_buffer, None)?;
    Ok((output_buffer.into_inner(), header, footer))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cart() {
        const BYTES: &[u8] = include_bytes!("../../crates/types/testdata/elf/elf_haiku_x86.cart");
        const ORIGINAL_SHA256: &str =
            "de10ba5e5402b46ea975b5cb8a45eb7df9e81dc81012fd4efd145ed2dce3a740";

        let (decoded, header, footer) = decode_from_cart(BYTES).unwrap();

        let mut sha256 = Sha256::new();
        sha256.update(&decoded);
        let sha256 = hex::encode(sha256.finalize());
        assert_eq!(sha256, ORIGINAL_SHA256);

        let header = header.unwrap();
        let entropy = header.get("entropy").unwrap().as_f64().unwrap();
        assert!(entropy > 4.0 && entropy < 4.1);

        let footer = footer.unwrap();
        assert_eq!(footer.get("length").unwrap(), "5093");
        assert_eq!(footer.get("sha256").unwrap(), ORIGINAL_SHA256);
    }
}