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
pub mod digest;

use chrono::serde::ts_seconds_option;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};

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

/// Login API endpoint, POST
pub const USER_LOGIN_URL: &str = "/v1/users/getkey";

/// User logs in with username and password
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetAPIKeyRequest {
    pub user: String,
    pub password: String,
}

/// Logout API endpoint, POST
pub const USER_LOGOUT_URL: &str = "/v1/users/clearkey";

/// Response includes the key, if the credentials were correct,
/// and possibly show a message related to errors or warnings.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetAPIKeyResponse {
    pub key: Option<String>,
    pub message: Option<String>,
}

/// User's get self information API endpoint, POST
/// User `EmptyAuthenticatingPost` to authenticate
pub const USER_INFO_URL: &str = "/v1/users/info";

/// User gets information about their account
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetUserInfoResponse {
    pub id: i32,
    pub username: String,
    pub groups: Vec<String>,
    pub sources: Vec<String>,
    pub is_admin: bool,
}

/// Server information, request is empty, GET
pub const SERVER_INFO: &str = "/v1/server/info";

/// Information about the server
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct ServerInfo {
    pub os_name: String,
    pub os_version: String,
    pub memory_used: String,
    pub mdb_version: String,
    pub db_version: String,
    pub db_size: String,
    pub num_samples: u64,
    pub num_users: u32,
    pub uptime: String,
}

/// File types supported by MalwareDB, request is empty, GET
pub const SUPPORTED_FILE_TYPES: &str = "/v1/server/types";

/// One record of supported file types
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SupportedFileType {
    pub name: String,
    pub magic: Vec<String>,
    pub is_executable: bool,
    pub description: Option<String>,
}

/// All of the supported types, the response
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SupportedFileTypes {
    pub types: Vec<SupportedFileType>,
    pub message: Option<String>,
}

/// Endpoint for the sources, per-user, POST
pub const GET_SOURCES: &str = "/v1/sources/list";

/// Generic POST for authenticating with the API key
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct EmptyAuthenticatingPost {
    pub key: String,
}

/// Source record
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SourceInfo {
    pub id: u64,
    pub name: String,
    pub description: Option<String>,
    pub url: Option<String>,
    #[serde(with = "ts_seconds_option")]
    pub first_acquisition: Option<DateTime<Utc>>,
}

/// Sources response
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Sources {
    pub sources: Vec<SourceInfo>,
    pub message: Option<String>,
}

/// API endpoint for uploading a sample, POST
pub const UPLOAD_SAMPLE: &str = "/v1/samples/upload";

/// New file sample being sent to MalwareDB
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct NewSample {
    /// The original file name, might not be known
    pub file_name: String,

    /// User's API key, must be validated before anything else
    pub key: String,

    /// ID of the source for this sample
    pub source_id: u32,

    /// Base64 encoding of the binary file
    pub file_contents_b64: String,

    /// SHA-256 of the sample being sent, for server-side validation
    pub sha256: String,
}

/// API endpoint for downloading a sample, POST
/// Response is raw bytes of the file, or HTTP 404 if not found
pub const DOWNLOAD_SAMPLE: &str = "/v1/samples/download";

/// API endpoint for downloading a sample as a CaRT file, POST
/// Response is the file encoded in a CaRT container file, or HTTP 404 if not found
pub const DOWNLOAD_SAMPLE_CART: &str = "/v1/samples/download/cart";

/// Requesting a sample from MalwareDB
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DownloadSampleRequest {
    /// User's API key, must be validated before anything else
    pub key: String,

    /// The hash of the requested sample
    pub hash: digest::HashType,
}

/// API endpoint to get a report for a given sample, use `DownloadSampleRequest` as the request structure
pub const SAMPLE_REPORT: &str = "/v1/samples/report";

// TODO: Add sections for parsed fields for documents, executables
/// All the data for a sample known to MalwareDB
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Report {
    pub md5: String,
    pub sha1: String,
    pub sha256: String,
    pub sha384: String,
    pub sha512: String,
    pub lzjd: Option<String>,
    pub tlsh: Option<String>,
    pub ssdeep: Option<String>,
    pub sdhash: Option<String>,
    pub humanhash: Option<String>,
    pub filecommand: Option<String>,
    pub bytes: u32,
    pub size: String,
    pub entropy: f32,
}

impl Display for Report {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Size: {} bytes, or {}", self.bytes, self.size)?;
        writeln!(f, "Entropy: {}", self.entropy)?;
        if let Some(filecmd) = &self.filecommand {
            writeln!(f, "File command: {filecmd}")?;
        }
        writeln!(f, "MD5: {}", self.md5)?;
        writeln!(f, "SHA-1: {}", self.sha1)?;
        writeln!(f, "SHA256: {}", self.sha256)
    }
}

/// API endpoint for finding samples which are similar to specific file, POST
pub const SIMILAR_SAMPLES: &str = "/v1/samples/similar";

/// The hash by which a sample is identified
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[non_exhaustive]
pub enum SimilarityHashType {
    SSDeep,
    SDHash,
    LZJD,
    TLSH,
    PEHash,
    ImportHash,
    FuzzyImportHash,
}

impl SimilarityHashType {
    /// For a similarity hash type, return:
    /// * The database table & field which stores the hash
    /// * If applicable, the similarity hash function (Postgres extension) which calculates the similarity
    pub fn get_table_field_simfunc(&self) -> (&'static str, Option<&'static str>) {
        match self {
            SimilarityHashType::SSDeep => ("file.ssdeep", Some("fuzzy_hash_compare")),
            SimilarityHashType::SDHash => ("file.sdhash", Some("sdhash_compare")),
            SimilarityHashType::LZJD => ("file.lzjd", Some("lzjd_compare")),
            SimilarityHashType::TLSH => ("file.tlsh", Some("tlsh_compare")),
            SimilarityHashType::PEHash => ("executable.pehash", None),
            SimilarityHashType::ImportHash => ("executable.importhash", None),
            SimilarityHashType::FuzzyImportHash => {
                ("executable.importhashfuzzy", Some("fuzzy_hash_compare"))
            }
        }
    }
}
/*
impl TryFrom<String> for SimilarityHashType {
    type Error = &'static str;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        let lower = value.to_ascii_lowercase();

        if lower == "lzjd" {
            return Ok(SimilarityHashType::LZJD);
        }
        if lower == "ssdeep" {
            return Ok(SimilarityHashType::SSDeep);
        }
        if lower == "sdhash" {
            return Ok(SimilarityHashType::SDHash);
        }
        if lower == "tlsh" {
            return Ok(SimilarityHashType::TLSH);
        }
        if lower == "pehash" {
            return Ok(SimilarityHashType::PEHash);
        }
        if lower == "importhash" {
            return Ok(SimilarityHashType::ImportHash);
        }
        if lower == "importhashfuzzy" {
            return Ok(SimilarityHashType::FuzzyImportHash);
        }

        Err("known similarity hash type")
    }
}*/

impl Display for SimilarityHashType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            SimilarityHashType::SSDeep => write!(f, "SSDeep"),
            SimilarityHashType::SDHash => write!(f, "SDHash"),
            SimilarityHashType::LZJD => write!(f, "LZJD"),
            SimilarityHashType::TLSH => write!(f, "TLSH"),
            SimilarityHashType::PEHash => write!(f, "PeHash"),
            SimilarityHashType::ImportHash => write!(f, "Import Hash (IMPHASH)"),
            SimilarityHashType::FuzzyImportHash => write!(f, "Fuzzy Import hash"),
        }
    }
}

/// Requesting a sample from MalwareDB
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SimilarSamplesRequest {
    /// User's API key, must be validated before anything else
    pub key: String,

    /// The hash of the requested sample
    pub hash: Vec<(SimilarityHashType, String)>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SimilarSample {
    /// The SHA-256 hash of the found sample
    pub sha256: String,

    /// Matches from the requested sample to this sample by algorithm and score
    pub algorithms: Vec<(SimilarityHashType, f32)>,
}

/// Response indicating samples which are similar
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SimilarSamplesResponse {
    /// The responses
    pub results: Vec<SimilarSample>,

    /// Possible messages from the server, if any
    pub message: Option<String>,
}

/// API endpoint for finding samples which are similar to specific file, POST
pub const LIST_LABELS: &str = "/v1/labels";

/// A label, used for sources and samples
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Label {
    /// Label ID
    pub id: u64,

    /// Label value
    pub name: String,

    /// Label parent
    pub parent: Option<String>,
}

/// One or more labels
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Labels(pub Vec<Label>);

// Convenience functions
impl Labels {
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Display for Labels {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.is_empty() {
            return writeln!(f, "No labels.");
        }
        for label in &self.0 {
            let parent = if let Some(parent) = &label.parent {
                format!(", parent: {parent}")
            } else {
                String::new()
            };
            writeln!(f, "{}: {}{parent}", label.id, label.name)?;
        }
        Ok(())
    }
}