1#![doc = include_str!("../README.md")]
4#![deny(missing_docs)]
5#![deny(clippy::all)]
6#![deny(clippy::pedantic)]
7#![forbid(unsafe_code)]
8
9pub mod digest;
11
12use crate::digest::HashType;
13
14use std::collections::HashMap;
15use std::error::Error;
16use std::fmt::{Display, Formatter};
17
18use chrono::serde::ts_seconds_option;
19use chrono::{DateTime, Utc};
20use serde::{Deserialize, Serialize};
21use zeroize::{Zeroize, ZeroizeOnDrop};
22
23pub const MDB_VERSION: &str = env!("CARGO_PKG_VERSION");
25
26pub const MDB_API_HEADER: &str = "mdb-api-key";
28
29pub const USER_LOGIN_URL: &str = "/v1/users/getkey";
31
32pub const MDNS_NAME: &str = "_malwaredb._tcp.local.";
34
35pub const MDB_API_KEY_LENGTH_BYTES: usize = 64;
37
38#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
40pub struct GetAPIKeyRequest {
41 pub user: String,
43
44 pub password: String,
46}
47
48pub const USER_LOGOUT_URL: &str = "/v1/users/clearkey";
50
51#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
54pub struct GetAPIKeyResponse {
55 pub key: String,
57
58 pub message: Option<String>,
60}
61
62#[derive(Clone, Debug, Deserialize, Serialize)]
71pub enum ServerResponse<D> {
72 #[serde(alias = "success")]
74 Success(D),
75
76 #[serde(alias = "error")]
78 Error(ServerError),
79}
80
81impl<D> ServerResponse<D> {
82 #[inline]
88 pub fn unwrap(self) -> D {
89 match self {
90 ServerResponse::Success(d) => d,
91 ServerResponse::Error(e) => panic!("forced ServerResponse::unwrap() on error: {e}"),
92 }
93 }
94
95 #[inline]
101 pub fn into_result(self) -> Result<D, ServerError> {
102 match self {
103 ServerResponse::Success(d) => Ok(d),
104 ServerResponse::Error(e) => Err(e),
105 }
106 }
107
108 #[inline]
110 pub const fn is_successful(&self) -> bool {
111 matches!(*self, ServerResponse::Success(_))
112 }
113
114 #[inline]
116 pub const fn is_err(&self) -> bool {
117 matches!(*self, ServerResponse::Error(_))
118 }
119}
120
121#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
123pub enum ServerError {
124 NoSamples,
126
127 NotFound,
129
130 ServerError,
132
133 Unauthorized,
135
136 Unsupported,
138}
139
140impl Display for ServerError {
141 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
142 match self {
143 ServerError::NoSamples => write!(f, "NoSamples"),
144 ServerError::NotFound => write!(f, "NotFound"),
145 ServerError::ServerError => write!(f, "ServerError"),
146 ServerError::Unauthorized => write!(f, "Unauthorized"),
147 ServerError::Unsupported => write!(f, "Unsupported"),
148 }
149 }
150}
151
152impl Error for ServerError {}
153
154pub const USER_INFO_URL: &str = "/v1/users/info";
156
157#[derive(Clone, Debug, Deserialize, Serialize)]
159pub struct GetUserInfoResponse {
160 pub id: u32,
162
163 pub username: String,
165
166 pub groups: Vec<String>,
168
169 pub sources: Vec<String>,
171
172 pub is_admin: bool,
174
175 pub created: DateTime<Utc>,
177
178 pub is_readonly: bool,
180}
181
182pub const SERVER_INFO_URL: &str = "/v1/server/info";
184
185#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
187pub struct ServerInfo {
188 pub os_name: String,
190
191 pub memory_used: String,
193
194 pub mdb_version: semver::Version,
196
197 pub db_version: String,
199
200 pub db_size: String,
202
203 pub num_samples: u64,
205
206 pub num_users: u32,
208
209 pub uptime: String,
211
212 pub instance_name: String,
214
215 pub vt_support: bool,
217
218 pub yara_enabled: bool,
220}
221
222pub const SUPPORTED_FILE_TYPES_URL: &str = "/v1/server/types";
224
225#[derive(Clone, Debug, Deserialize, Serialize)]
227pub struct SupportedFileType {
228 pub name: String,
230
231 pub magic: Vec<String>,
233
234 pub is_executable: bool,
236
237 pub description: Option<String>,
239}
240
241#[derive(Clone, Debug, Deserialize, Serialize)]
243pub struct SupportedFileTypes {
244 pub types: Vec<SupportedFileType>,
246
247 pub message: Option<String>,
249}
250
251pub const LIST_SOURCES_URL: &str = "/v1/sources/list";
253
254#[derive(Clone, Debug, Deserialize, Serialize)]
256pub struct SourceInfo {
257 pub id: u32,
259
260 pub name: String,
262
263 pub description: Option<String>,
265
266 pub url: Option<String>,
268
269 pub first_acquisition: DateTime<Utc>,
271
272 pub malicious: Option<bool>,
274}
275
276#[derive(Clone, Debug, Deserialize, Serialize)]
278pub struct Sources {
279 pub sources: Vec<SourceInfo>,
281
282 pub message: Option<String>,
284}
285
286pub const UPLOAD_SAMPLE_JSON_URL: &str = "/v1/samples/json/upload";
288
289pub const UPLOAD_SAMPLE_CBOR_URL: &str = "/v1/samples/cbor/upload";
291
292#[derive(Clone, Debug, Deserialize, Serialize)]
294pub struct NewSampleB64 {
295 pub file_name: String,
298
299 pub source_id: u32,
301
302 pub file_contents_b64: String,
304
305 pub sha256: String,
307}
308
309#[derive(Clone, Debug, Deserialize, Serialize)]
311pub struct NewSampleBytes {
312 pub file_name: String,
315
316 pub source_id: u32,
318
319 pub file_contents: Vec<u8>,
321
322 pub sha256: String,
324}
325
326pub const DOWNLOAD_SAMPLE_URL: &str = "/v1/samples/download";
330
331pub const DOWNLOAD_SAMPLE_CART_URL: &str = "/v1/samples/download/cart";
335
336pub const SAMPLE_REPORT_URL: &str = "/v1/samples/report";
339
340#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
342pub struct VirusTotalSummary {
343 pub hits: u32,
345
346 pub total: u32,
348
349 #[serde(default)]
351 pub detail: Option<serde_json::Value>,
352
353 #[serde(default, with = "ts_seconds_option")]
355 pub last_analysis_date: Option<DateTime<Utc>>,
356}
357
358#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
361pub struct Report {
362 pub md5: String,
364
365 pub sha1: String,
367
368 pub sha256: String,
370
371 pub sha384: String,
373
374 pub sha512: String,
376
377 pub lzjd: Option<String>,
380
381 pub tlsh: Option<String>,
384
385 pub ssdeep: Option<String>,
388
389 pub humanhash: Option<String>,
392
393 pub filecommand: Option<String>,
396
397 pub bytes: u64,
399
400 pub size: String,
402
403 pub entropy: f32,
405
406 #[serde(default)]
409 pub vt: Option<VirusTotalSummary>,
410}
411
412impl Display for Report {
413 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
414 writeln!(f, "Size: {} bytes, or {}", self.bytes, self.size)?;
415 writeln!(f, "Entropy: {}", self.entropy)?;
416 if let Some(filecmd) = &self.filecommand {
417 writeln!(f, "File command: {filecmd}")?;
418 }
419 if let Some(vt) = &self.vt {
420 writeln!(f, "VT Hits: {}/{}", vt.hits, vt.total)?;
421 }
422 writeln!(f, "MD5: {}", self.md5)?;
423 writeln!(f, "SHA-1: {}", self.sha1)?;
424 writeln!(f, "SHA256: {}", self.sha256)
425 }
426}
427
428pub const SIMILAR_SAMPLES_URL: &str = "/v1/samples/similar";
430
431#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
433#[non_exhaustive]
434pub enum SimilarityHashType {
435 SSDeep,
437
438 LZJD,
440
441 TLSH,
443
444 PEHash,
446
447 ImportHash,
449
450 FuzzyImportHash,
452}
453
454impl SimilarityHashType {
455 #[must_use]
459 pub fn get_table_field_simfunc(&self) -> (&'static str, Option<&'static str>) {
460 match self {
461 SimilarityHashType::SSDeep => ("file.ssdeep", Some("fuzzy_hash_compare")),
462 SimilarityHashType::LZJD => ("file.lzjd", Some("lzjd_compare")),
463 SimilarityHashType::TLSH => ("file.tlsh", Some("tlsh_compare")),
464 SimilarityHashType::PEHash => ("executable.pehash", None),
465 SimilarityHashType::ImportHash => ("executable.importhash", None),
466 SimilarityHashType::FuzzyImportHash => {
467 ("executable.importhashfuzzy", Some("fuzzy_hash_compare"))
468 }
469 }
470 }
471}
472
473impl Display for SimilarityHashType {
474 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
475 match self {
476 SimilarityHashType::SSDeep => write!(f, "SSDeep"),
477 SimilarityHashType::LZJD => write!(f, "LZJD"),
478 SimilarityHashType::TLSH => write!(f, "TLSH"),
479 SimilarityHashType::PEHash => write!(f, "PeHash"),
480 SimilarityHashType::ImportHash => write!(f, "Import Hash (IMPHASH)"),
481 SimilarityHashType::FuzzyImportHash => write!(f, "Fuzzy Import hash"),
482 }
483 }
484}
485
486#[derive(Clone, Debug, Deserialize, Serialize)]
488pub struct SimilarSamplesRequest {
489 pub hashes: Vec<(SimilarityHashType, String)>,
491}
492
493#[derive(Clone, Debug, Deserialize, Serialize)]
495pub struct SimilarSample {
496 pub sha256: String,
498
499 pub algorithms: Vec<(SimilarityHashType, f32)>,
501}
502
503#[derive(Clone, Debug, Deserialize, Serialize)]
505pub struct SimilarSamplesResponse {
506 pub results: Vec<SimilarSample>,
508
509 pub message: Option<String>,
511}
512
513pub const SEARCH_URL: &str = "/v1/search";
515
516#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
518pub enum SearchType {
519 Continuation(uuid::Uuid),
521
522 Search(SearchRequestParameters),
524}
525
526#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
533pub struct SearchRequestParameters {
534 pub partial_hash: Option<(PartialHashSearchType, String)>,
536
537 pub file_name: Option<String>,
539
540 pub limit: u32,
542
543 pub file_type: Option<String>,
545
546 pub magic: Option<String>,
548
549 pub labels: Option<Vec<String>>,
551
552 pub response: PartialHashSearchType,
555}
556
557impl SearchRequestParameters {
558 #[must_use]
563 #[inline]
564 pub fn is_valid(&self) -> bool {
565 if self.limit == 0 {
566 return false;
567 }
568
569 if let Some((_hash_type, partial_hash)) = &self.partial_hash {
570 let hex = hex::decode(partial_hash);
571 return hex.is_ok();
572 }
573
574 self.partial_hash.is_some()
575 || self.file_name.is_some()
576 || self.file_type.is_some()
577 || self.magic.is_some()
578 || self.labels.is_some()
579 }
580}
581
582impl Default for SearchRequestParameters {
584 fn default() -> Self {
585 Self {
586 partial_hash: None,
587 file_name: None,
588 limit: 100,
589 labels: None,
590 file_type: None,
591 magic: None,
592 response: PartialHashSearchType::default(),
593 }
594 }
595}
596
597#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
600pub struct SearchRequest {
601 pub search: SearchType,
603}
604
605impl SearchRequest {
606 #[must_use]
610 #[inline]
611 pub fn is_valid(&self) -> bool {
612 if let SearchType::Search(search) = &self.search {
613 search.is_valid()
614 } else {
615 true
616 }
617 }
618}
619
620#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
622pub struct SearchResponse {
623 pub hashes: Vec<String>,
625
626 pub pagination: Option<uuid::Uuid>,
628
629 pub total_results: u64,
631
632 pub message: Option<String>,
634}
635
636#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
638pub enum PartialHashSearchType {
639 Any,
641
642 MD5,
644
645 SHA1,
647
648 #[default]
650 SHA256,
651
652 SHA384,
654
655 SHA512,
657}
658
659impl Display for PartialHashSearchType {
660 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
661 match self {
662 PartialHashSearchType::Any => write!(f, "any"),
663 PartialHashSearchType::MD5 => write!(f, "md5"),
664 PartialHashSearchType::SHA1 => write!(f, "sha1"),
665 PartialHashSearchType::SHA256 => write!(f, "sha256"),
666 PartialHashSearchType::SHA384 => write!(f, "sha384"),
667 PartialHashSearchType::SHA512 => write!(f, "sha512"),
668 }
669 }
670}
671
672impl TryInto<PartialHashSearchType> for &str {
673 type Error = String;
674
675 fn try_into(self) -> Result<PartialHashSearchType, Self::Error> {
676 match self {
677 "any" => Ok(PartialHashSearchType::Any),
678 "md5" => Ok(PartialHashSearchType::MD5),
679 "sha1" => Ok(PartialHashSearchType::SHA1),
680 "sha256" => Ok(PartialHashSearchType::SHA256),
681 "sha384" => Ok(PartialHashSearchType::SHA384),
682 "sha512" => Ok(PartialHashSearchType::SHA512),
683 x => Err(format!("Invalid hash type {x}")),
684 }
685 }
686}
687
688impl TryInto<PartialHashSearchType> for Option<&str> {
689 type Error = String;
690
691 fn try_into(self) -> Result<PartialHashSearchType, Self::Error> {
692 if let Some(hash) = self {
693 hash.try_into()
694 } else {
695 Ok(PartialHashSearchType::SHA256)
696 }
697 }
698}
699
700pub const YARA_SEARCH_URL: &str = "/v1/yara";
704
705#[derive(Clone, Debug, Deserialize, Serialize)]
707pub struct YaraSearchRequest {
708 pub rules: Vec<String>,
710
711 pub response: PartialHashSearchType,
714}
715
716#[derive(Clone, Debug, Deserialize, Serialize)]
718pub struct YaraSearchRequestResponse {
719 pub uuid: uuid::Uuid,
721}
722
723#[derive(Clone, Debug, Deserialize, Serialize)]
725pub struct YaraSearchResponse {
726 pub results: HashMap<String, Vec<HashType>>,
728}
729
730pub const LIST_LABELS_URL: &str = "/v1/labels";
732
733#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
735pub struct Label {
736 pub id: u64,
738
739 pub name: String,
741
742 pub parent: Option<String>,
744}
745
746#[derive(Clone, Debug, Default, Deserialize, Serialize)]
748pub struct Labels(pub Vec<Label>);
749
750impl Labels {
752 #[must_use]
754 pub fn len(&self) -> usize {
755 self.0.len()
756 }
757
758 #[must_use]
760 pub fn is_empty(&self) -> bool {
761 self.0.is_empty()
762 }
763}
764
765impl Display for Labels {
766 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
767 if self.is_empty() {
768 return writeln!(f, "No labels.");
769 }
770 for label in &self.0 {
771 let parent = if let Some(parent) = &label.parent {
772 format!(", parent: {parent}")
773 } else {
774 String::new()
775 };
776 writeln!(f, "{}: {}{parent}", label.id, label.name)?;
777 }
778 Ok(())
779 }
780}