1#![doc = include_str!("../README.md")]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![deny(missing_docs)]
6#![deny(clippy::all)]
7#![deny(clippy::pedantic)]
8#![forbid(unsafe_code)]
9
10#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
12#[cfg(feature = "blocking")]
13pub mod blocking;
14
15pub use malwaredb_api;
16use malwaredb_api::{
17 GetAPIKeyResponse, GetUserInfoResponse, Labels, PartialHashSearchType, Report, SearchRequest,
18 SearchRequestParameters, SearchResponse, SearchType, ServerInfo, ServerResponse,
19 SimilarSamplesResponse, Sources, SupportedFileTypes, YaraSearchRequest,
20 YaraSearchRequestResponse, YaraSearchResponse, digest::HashType,
21};
22use malwaredb_types::exec::pe32::EXE;
23use malwaredb_types::utils::entropy_calc;
24
25use std::collections::HashSet;
26use std::fmt::{Debug, Display, Formatter};
27use std::fs::OpenOptions;
28use std::io::{Cursor, Write};
29use std::path::{Path, PathBuf};
30use std::sync::LazyLock;
31
32use anyhow::{Context, Result, bail, ensure};
33use base64::Engine;
34use base64::engine::general_purpose;
35use cart_container::JsonMap;
36use fuzzyhash::FuzzyHash;
37use home::home_dir;
38use malwaredb_lzjd2::lzjd::LzDigest;
39use mdns_sd::{ServiceDaemon, ServiceEvent};
40use reqwest::Certificate;
41use serde::{Deserialize, Serialize};
42use sha2::{Digest, Sha256, Sha384, Sha512};
43use tlsh_fixed::TlshBuilder;
44use tracing::{debug, error, info, trace, warn};
45use uuid::Uuid;
46use zeroize::{Zeroize, ZeroizeOnDrop};
47
48const MDB_CLIENT_DIR: &str = "malwaredb_client";
50
51pub(crate) const MDB_CLIENT_ERROR_CONTEXT: &str =
53 "Network error connecting to MalwareDB, or failure to decode server response.";
54
55const MDB_CLIENT_CONFIG_TOML: &str = "mdb_client.toml";
57
58pub const MDB_VERSION: &str = env!("CARGO_PKG_VERSION");
60
61pub static MDB_VERSION_SEMVER: LazyLock<semver::Version> =
63 LazyLock::new(|| semver::Version::parse(MDB_VERSION).unwrap());
64
65#[cfg(target_os = "macos")]
67pub(crate) mod macos {
68 use crate::CertificateType;
69
70 use anyhow::Result;
71 use reqwest::Certificate;
72 use security_framework::os::macos::keychain::SecKeychain;
73 use tracing::error;
74
75 const KEYCHAIN_ID: &str = "malwaredb-client";
77
78 const KEYCHAIN_URL: &str = "URL";
80
81 const KEYCHAIN_API_KEY: &str = "API_KEY";
83
84 const KEYCHAIN_CERTIFICATE_PEM: &str = "CERT_PEM";
86
87 const KEYCHAIN_CERTIFICATE_DER: &str = "CERT_DER";
89
90 #[derive(Clone)]
91 pub(crate) struct CertificateData {
92 pub cert_type: CertificateType,
93 pub cert_bytes: Vec<u8>,
94 }
95
96 impl CertificateData {
97 pub(crate) fn as_cert(&self) -> Result<Certificate> {
98 Ok(match self.cert_type {
99 CertificateType::PEM => Certificate::from_pem(&self.cert_bytes)?,
100 CertificateType::DER => Certificate::from_der(&self.cert_bytes)?,
101 })
102 }
103 }
104
105 pub fn save_credentials(url: &str, key: &str, cert: Option<CertificateData>) -> Result<()> {
107 let keychain = SecKeychain::default()?;
108
109 keychain.add_generic_password(KEYCHAIN_ID, KEYCHAIN_URL, url.as_bytes())?;
110 keychain.add_generic_password(KEYCHAIN_ID, KEYCHAIN_API_KEY, key.as_bytes())?;
111
112 if let Some(cert) = cert {
113 match cert.cert_type {
114 CertificateType::PEM => keychain.add_generic_password(
115 KEYCHAIN_ID,
116 KEYCHAIN_CERTIFICATE_PEM,
117 &cert.cert_bytes,
118 )?,
119 CertificateType::DER => keychain.add_generic_password(
120 KEYCHAIN_ID,
121 KEYCHAIN_CERTIFICATE_DER,
122 &cert.cert_bytes,
123 )?,
124 }
125 }
126
127 Ok(())
128 }
129
130 pub fn retrieve_credentials() -> Result<(String, String, Option<CertificateData>)> {
132 let keychain = SecKeychain::default()?;
133 let (api_key, _item) = keychain.find_generic_password(KEYCHAIN_ID, KEYCHAIN_API_KEY)?;
134 let api_key = String::from_utf8(api_key.as_ref().to_vec())?;
135 let (url, _item) = keychain.find_generic_password(KEYCHAIN_ID, KEYCHAIN_URL)?;
136 let url = String::from_utf8(url.as_ref().to_vec())?;
137
138 if let Ok((cert, _item)) =
139 keychain.find_generic_password(KEYCHAIN_ID, KEYCHAIN_CERTIFICATE_PEM)
140 {
141 let cert = CertificateData {
142 cert_type: CertificateType::PEM,
143 cert_bytes: cert.to_vec(),
144 };
145 return Ok((api_key, url, Some(cert)));
146 }
147
148 if let Ok((cert, _item)) =
149 keychain.find_generic_password(KEYCHAIN_ID, KEYCHAIN_CERTIFICATE_DER)
150 {
151 let cert = CertificateData {
152 cert_type: CertificateType::DER,
153 cert_bytes: cert.to_vec(),
154 };
155 return Ok((api_key, url, Some(cert)));
156 }
157
158 Ok((api_key, url, None))
159 }
160
161 pub fn clear_credentials() {
163 if let Ok(keychain) = SecKeychain::default() {
164 for element in [
165 KEYCHAIN_API_KEY,
166 KEYCHAIN_URL,
167 KEYCHAIN_CERTIFICATE_PEM,
168 KEYCHAIN_CERTIFICATE_DER,
169 ] {
170 if let Ok((_, item)) = keychain.find_generic_password(KEYCHAIN_ID, element) {
171 item.delete();
172 }
173 }
174 } else {
175 error!("Failed to get access to the Keychain to clear credentials");
176 }
177 }
178}
179
180#[allow(clippy::upper_case_acronyms)]
181#[derive(Copy, Clone, PartialEq, Eq)]
182enum CertificateType {
183 DER,
184 PEM,
185}
186
187#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
189pub struct MdbClient {
190 pub url: String,
192
193 api_key: String,
196
197 #[zeroize(skip)]
199 #[serde(skip)]
200 client: reqwest::Client,
201
202 #[cfg(target_os = "macos")]
204 #[zeroize(skip)]
205 #[serde(skip)]
206 cert: Option<macos::CertificateData>,
207}
208
209impl MdbClient {
210 pub fn new(url: String, api_key: String, cert_path: Option<PathBuf>) -> Result<Self> {
217 let mut url = url;
218 let url = if url.ends_with('/') {
219 url.pop();
220 url
221 } else {
222 url
223 };
224
225 let cert = if let Some(path) = cert_path {
226 Some((path_load_cert(&path)?, path))
227 } else {
228 None
229 };
230
231 let builder = reqwest::ClientBuilder::new()
232 .deflate(true)
233 .gzip(true)
234 .zstd(true)
235 .use_rustls_tls()
236 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
237
238 let client = if let Some(((_cert_type, cert), _cert_path)) = &cert {
239 builder.add_root_certificate(cert.clone()).build()
240 } else {
241 builder.build()
242 }?;
243
244 #[cfg(target_os = "macos")]
245 let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
246 Some(macos::CertificateData {
247 cert_type: *cert_type,
248 cert_bytes: std::fs::read(cert_path)?,
249 })
250 } else {
251 None
252 };
253
254 Ok(Self {
255 url,
256 api_key,
257 client,
258
259 #[cfg(target_os = "macos")]
260 cert,
261 })
262 }
263
264 pub async fn anonymous(url: String, save: bool, cert_path: Option<PathBuf>) -> Result<Self> {
270 let mut url = url;
271 let url = if url.ends_with('/') {
272 url.pop();
273 url
274 } else {
275 url
276 };
277
278 let builder = reqwest::ClientBuilder::new()
279 .gzip(true)
280 .zstd(true)
281 .use_rustls_tls()
282 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
283
284 let cert = if let Some(path) = cert_path {
285 Some((path_load_cert(&path)?, path))
286 } else {
287 None
288 };
289
290 let client = if let Some(((_cert_type, cert), _cert_path)) = &cert {
291 builder.add_root_certificate(cert.clone()).build()
292 } else {
293 builder.build()
294 }?;
295
296 let info = client
297 .get(format!("{url}{}", malwaredb_api::USER_INFO_URL))
298 .send()
299 .await?
300 .json::<ServerResponse<GetUserInfoResponse>>()
301 .await
302 .context(MDB_CLIENT_ERROR_CONTEXT)?;
303
304 if let ServerResponse::Success(info) = info {
305 ensure!(info.id > 0);
306 } else {
307 bail!("Anonymous access is not allowed");
308 }
309
310 #[cfg(target_os = "macos")]
311 let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
312 Some(macos::CertificateData {
313 cert_type: *cert_type,
314 cert_bytes: std::fs::read(cert_path)?,
315 })
316 } else {
317 None
318 };
319
320 let client = Self {
321 url,
322 api_key: "anonymous".to_string(),
323 client,
324
325 #[cfg(target_os = "macos")]
326 cert,
327 };
328
329 let server_info = client.server_info().await?;
330 if server_info.mdb_version > *MDB_VERSION_SEMVER {
331 warn!(
332 "Server version {:?} is newer than client {:?}, consider updating.",
333 server_info.mdb_version, MDB_VERSION_SEMVER
334 );
335 }
336
337 if save && let Err(e) = client.save() {
338 error!("Anonymous connection successful but failed to save config: {e}");
339 bail!("Anonymous connection successful but failed to save config: {e}");
340 }
341
342 Ok(client)
343 }
344
345 pub async fn login(
352 url: String,
353 username: String,
354 password: String,
355 save: bool,
356 cert_path: Option<PathBuf>,
357 ) -> Result<Self> {
358 let mut url = url;
359 let url = if url.ends_with('/') {
360 url.pop();
361 url
362 } else {
363 url
364 };
365
366 let api_request = malwaredb_api::GetAPIKeyRequest {
367 user: username,
368 password,
369 };
370
371 let builder = reqwest::ClientBuilder::new()
372 .gzip(true)
373 .zstd(true)
374 .use_rustls_tls()
375 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
376
377 let cert = if let Some(path) = cert_path {
378 Some((path_load_cert(&path)?, path))
379 } else {
380 None
381 };
382
383 let client = if let Some(((_cert_type, cert), _cert_path)) = &cert {
384 builder.add_root_certificate(cert.clone()).build()
385 } else {
386 builder.build()
387 }?;
388
389 let res = client
390 .post(format!("{url}{}", malwaredb_api::USER_LOGIN_URL))
391 .json(&api_request)
392 .send()
393 .await?
394 .json::<ServerResponse<GetAPIKeyResponse>>()
395 .await
396 .context(MDB_CLIENT_ERROR_CONTEXT)?;
397
398 let res = match res {
399 ServerResponse::Success(res) => res,
400 ServerResponse::Error(err) => return Err(err.into()),
401 };
402
403 #[cfg(target_os = "macos")]
404 let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
405 Some(macos::CertificateData {
406 cert_type: *cert_type,
407 cert_bytes: std::fs::read(cert_path)?,
408 })
409 } else {
410 None
411 };
412
413 let client = MdbClient {
414 url,
415 api_key: res.key.clone(),
416 client,
417
418 #[cfg(target_os = "macos")]
419 cert,
420 };
421
422 let server_info = client.server_info().await?;
423 if server_info.mdb_version > *MDB_VERSION_SEMVER {
424 warn!(
425 "Server version {:?} is newer than client {:?}, consider updating.",
426 server_info.mdb_version, MDB_VERSION_SEMVER
427 );
428 }
429
430 if save && let Err(e) = client.save() {
431 error!("Login successful but failed to save config: {e}");
432 bail!("Login successful but failed to save config: {e}");
433 }
434 Ok(client)
435 }
436
437 pub async fn reset_key(&self) -> Result<()> {
443 let response = self
444 .client
445 .get(format!("{}{}", self.url, malwaredb_api::USER_LOGOUT_URL))
446 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
447 .send()
448 .await
449 .context(MDB_CLIENT_ERROR_CONTEXT)?;
450 if !response.status().is_success() {
451 bail!("failed to reset API key, was it correct?");
452 }
453 Ok(())
454 }
455
456 pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
463 let name = path.as_ref().display();
464 let config =
465 std::fs::read_to_string(&path).context(format!("failed to read config file {name}"))?;
466 let cfg: MdbClient =
467 toml::from_str(&config).context(format!("failed to parse config file {name}"))?;
468 Ok(cfg)
469 }
470
471 pub fn load() -> Result<Self> {
480 #[cfg(target_os = "macos")]
481 {
482 if let Ok((api_key, url, cert)) = macos::retrieve_credentials() {
483 let builder = reqwest::ClientBuilder::new()
484 .gzip(true)
485 .zstd(true)
486 .use_rustls_tls()
487 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
488
489 let client = if let Some(cert) = &cert {
490 builder.add_root_certificate(cert.as_cert()?).build()
491 } else {
492 builder.build()
493 }?;
494
495 return Ok(Self {
496 url,
497 api_key,
498 client,
499 cert,
500 });
501 }
502 }
503
504 let path = get_config_path(false)?;
505 if path.exists() {
506 return Self::from_file(path);
507 }
508 bail!("config file not found")
509 }
510
511 pub fn save(&self) -> Result<()> {
519 #[cfg(target_os = "macos")]
520 {
521 if macos::save_credentials(&self.url, &self.api_key, self.cert.clone()).is_ok() {
522 return Ok(());
523 }
524 }
525
526 let toml = toml::to_string(self)?;
527 let path = get_config_path(true)?;
528
529 let mut options = OpenOptions::new();
530 options
531 .write(true)
532 .create(true)
533 .append(false)
534 .truncate(false);
535
536 #[cfg(target_family = "unix")]
537 {
538 use std::os::unix::fs::OpenOptionsExt;
539
540 options.mode(0o600);
541 }
542
543 let mut file = options.open(&path)?;
544 write!(file, "{toml}").context(format!("failed to write mdb config to {}", path.display()))
545 }
546
547 pub fn delete(&self) -> Result<()> {
554 #[cfg(target_os = "macos")]
555 macos::clear_credentials();
556
557 let path = get_config_path(false)?;
558 if path.exists() {
559 std::fs::remove_file(&path)
560 .context(format!("failed to delete client config file {}", path.display()))?;
561 }
562 Ok(())
563 }
564
565 pub async fn server_info(&self) -> Result<ServerInfo> {
573 let response = self
574 .client
575 .get(format!("{}{}", self.url, malwaredb_api::SERVER_INFO_URL))
576 .send()
577 .await?
578 .json::<ServerResponse<ServerInfo>>()
579 .await
580 .context(MDB_CLIENT_ERROR_CONTEXT)?;
581
582 match response {
583 ServerResponse::Success(info) => Ok(info),
584 ServerResponse::Error(e) => Err(e.into()),
585 }
586 }
587
588 pub async fn supported_types(&self) -> Result<SupportedFileTypes> {
594 let response = self
595 .client
596 .get(format!("{}{}", self.url, malwaredb_api::SUPPORTED_FILE_TYPES_URL))
597 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
598 .send()
599 .await?
600 .json::<ServerResponse<SupportedFileTypes>>()
601 .await
602 .context(MDB_CLIENT_ERROR_CONTEXT)?;
603
604 match response {
605 ServerResponse::Success(types) => Ok(types),
606 ServerResponse::Error(e) => Err(e.into()),
607 }
608 }
609
610 pub async fn whoami(&self) -> Result<GetUserInfoResponse> {
617 let response = self
618 .client
619 .get(format!("{}{}", self.url, malwaredb_api::USER_INFO_URL))
620 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
621 .send()
622 .await?
623 .json::<ServerResponse<GetUserInfoResponse>>()
624 .await
625 .context(MDB_CLIENT_ERROR_CONTEXT)?;
626
627 match response {
628 ServerResponse::Success(info) => Ok(info),
629 ServerResponse::Error(e) => Err(e.into()),
630 }
631 }
632
633 pub async fn labels(&self) -> Result<Labels> {
640 let response = self
641 .client
642 .get(format!("{}{}", self.url, malwaredb_api::LIST_LABELS_URL))
643 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
644 .send()
645 .await?
646 .json::<ServerResponse<Labels>>()
647 .await
648 .context(MDB_CLIENT_ERROR_CONTEXT)?;
649
650 match response {
651 ServerResponse::Success(labels) => Ok(labels),
652 ServerResponse::Error(e) => Err(e.into()),
653 }
654 }
655
656 pub async fn sources(&self) -> Result<Sources> {
663 let response = self
664 .client
665 .get(format!("{}{}", self.url, malwaredb_api::LIST_SOURCES_URL))
666 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
667 .send()
668 .await?
669 .json::<ServerResponse<Sources>>()
670 .await
671 .context(MDB_CLIENT_ERROR_CONTEXT)?;
672
673 match response {
674 ServerResponse::Success(sources) => Ok(sources),
675 ServerResponse::Error(e) => Err(e.into()),
676 }
677 }
678
679 pub async fn submit(
686 &self,
687 contents: impl AsRef<[u8]>,
688 file_name: impl AsRef<str>,
689 source_id: u32,
690 ) -> Result<bool> {
691 let mut hasher = Sha256::new();
692 hasher.update(&contents);
693 let result = hasher.finalize();
694
695 let encoded = general_purpose::STANDARD.encode(contents);
696
697 let payload = malwaredb_api::NewSampleB64 {
698 file_name: file_name.as_ref().to_string(),
699 source_id,
700 file_contents_b64: encoded,
701 sha256: hex::encode(result),
702 };
703
704 match self
705 .client
706 .post(format!("{}{}", self.url, malwaredb_api::UPLOAD_SAMPLE_JSON_URL))
707 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
708 .json(&payload)
709 .send()
710 .await
711 {
712 Ok(res) => {
713 if !res.status().is_success() {
714 info!("Code {} sending {}", res.status(), payload.file_name);
715 }
716 Ok(res.status().is_success())
717 }
718 Err(e) => {
719 let status: String = e
720 .status()
721 .map(|s| s.as_str().to_string())
722 .unwrap_or_default();
723 error!("Error{status} sending {}: {e}", payload.file_name);
724 bail!(e.to_string())
725 }
726 }
727 }
728
729 pub async fn submit_as_cbor(
737 &self,
738 contents: impl AsRef<[u8]>,
739 file_name: impl AsRef<str>,
740 source_id: u32,
741 ) -> Result<bool> {
742 let mut hasher = Sha256::new();
743 hasher.update(&contents);
744 let result = hasher.finalize();
745
746 let payload = malwaredb_api::NewSampleBytes {
747 file_name: file_name.as_ref().to_string(),
748 source_id,
749 file_contents: contents.as_ref().to_vec(),
750 sha256: hex::encode(result),
751 };
752
753 let mut bytes = Vec::with_capacity(payload.file_contents.len());
754 ciborium::ser::into_writer(&payload, &mut bytes)?;
755
756 match self
757 .client
758 .post(format!("{}{}", self.url, malwaredb_api::UPLOAD_SAMPLE_CBOR_URL))
759 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
760 .header("content-type", "application/cbor")
761 .body(bytes)
762 .send()
763 .await
764 {
765 Ok(res) => {
766 if !res.status().is_success() {
767 info!("Code {} sending {}", res.status(), payload.file_name);
768 }
769 Ok(res.status().is_success())
770 }
771 Err(e) => {
772 let status: String = e
773 .status()
774 .map(|s| s.as_str().to_string())
775 .unwrap_or_default();
776 error!("Error{status} sending {}: {e}", payload.file_name);
777 bail!(e.to_string())
778 }
779 }
780 }
781
782 pub async fn partial_search(
788 &self,
789 partial_hash: Option<(PartialHashSearchType, String)>,
790 name: Option<String>,
791 response: PartialHashSearchType,
792 limit: u32,
793 ) -> Result<SearchResponse> {
794 let query = SearchRequest {
795 search: SearchType::Search(SearchRequestParameters {
796 partial_hash,
797 file_name: name,
798 response,
799 limit,
800 labels: None,
801 file_type: None,
802 magic: None,
803 }),
804 };
805
806 self.do_search_request(&query).await
807 }
808
809 #[allow(clippy::too_many_arguments)]
815 pub async fn partial_search_labels_type(
816 &self,
817 partial_hash: Option<(PartialHashSearchType, String)>,
818 name: Option<String>,
819 response: PartialHashSearchType,
820 labels: Option<Vec<String>>,
821 file_type: Option<String>,
822 magic: Option<String>,
823 limit: u32,
824 ) -> Result<SearchResponse> {
825 let query = SearchRequest {
826 search: SearchType::Search(SearchRequestParameters {
827 partial_hash,
828 file_name: name,
829 response,
830 limit,
831 file_type,
832 magic,
833 labels,
834 }),
835 };
836
837 self.do_search_request(&query).await
838 }
839
840 pub async fn next_page_search(&self, response: &SearchResponse) -> Result<SearchResponse> {
846 if let Some(uuid) = response.pagination {
847 let request = SearchRequest {
848 search: SearchType::Continuation(uuid),
849 };
850 return self.do_search_request(&request).await;
851 }
852
853 bail!("Pagination not available")
854 }
855
856 async fn do_search_request(&self, query: &SearchRequest) -> Result<SearchResponse> {
857 ensure!(
858 query.is_valid(),
859 "Query isn't valid: hash isn't hexidecimal or both the hashes and file name are empty"
860 );
861
862 let response = self
863 .client
864 .post(format!("{}{}", self.url, malwaredb_api::SEARCH_URL))
865 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
866 .json(query)
867 .send()
868 .await?
869 .json::<ServerResponse<SearchResponse>>()
870 .await
871 .context(MDB_CLIENT_ERROR_CONTEXT)?;
872
873 match response {
874 ServerResponse::Success(search) => Ok(search),
875 ServerResponse::Error(e) => Err(e.into()),
876 }
877 }
878
879 pub async fn retrieve(&self, hash: &str, cart: bool) -> Result<Vec<u8>> {
886 let api_endpoint = if cart {
887 format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE_CART_URL)
888 } else {
889 format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE_URL)
890 };
891
892 let res = self
893 .client
894 .get(format!("{}{api_endpoint}", self.url))
895 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
896 .send()
897 .await?;
898
899 if !res.status().is_success() {
900 bail!("Received code {}", res.status());
901 }
902
903 let content_digest = res.headers().get("content-digest").map(ToOwned::to_owned);
904 let body = res.bytes().await?;
905 let bytes = body.to_vec();
906
907 if let Some(digest) = content_digest {
909 let hash = HashType::from_content_digest_header(digest.to_str()?)?;
910 if hash.verify(&bytes) {
911 trace!("Hash verified for sample {hash}");
912 } else {
913 error!("Hash mismatch for sample {hash}");
914 }
915 } else {
916 warn!("No content digest header received for sample {hash}");
917 }
918
919 Ok(bytes)
920 }
921
922 pub async fn report(&self, hash: &str) -> Result<Report> {
929 let response = self
930 .client
931 .get(format!("{}{}/{hash}", self.url, malwaredb_api::SAMPLE_REPORT_URL))
932 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
933 .send()
934 .await?
935 .json::<ServerResponse<Report>>()
936 .await
937 .context(MDB_CLIENT_ERROR_CONTEXT)?;
938
939 match response {
940 ServerResponse::Success(report) => Ok(report),
941 ServerResponse::Error(e) => Err(e.into()),
942 }
943 }
944
945 pub async fn similar(&self, contents: &[u8]) -> Result<SimilarSamplesResponse> {
953 let mut hashes = vec![];
954 let ssdeep_hash = FuzzyHash::new(contents);
955
956 let lzjd_str = LzDigest::from(contents).to_string();
957 hashes.push((malwaredb_api::SimilarityHashType::LZJD, lzjd_str));
958 hashes.push((malwaredb_api::SimilarityHashType::SSDeep, ssdeep_hash.to_string()));
959
960 let mut builder = TlshBuilder::new(
961 tlsh_fixed::BucketKind::Bucket256,
962 tlsh_fixed::ChecksumKind::ThreeByte,
963 tlsh_fixed::Version::Version4,
964 );
965
966 builder.update(contents);
967 if let Ok(hasher) = builder.build() {
968 hashes.push((malwaredb_api::SimilarityHashType::TLSH, hasher.hash()));
969 }
970
971 if let Ok(exe) = EXE::from(contents)
972 && let Some(imports) = exe.imports
973 {
974 hashes
975 .push((malwaredb_api::SimilarityHashType::ImportHash, hex::encode(imports.hash())));
976 hashes.push((malwaredb_api::SimilarityHashType::FuzzyImportHash, imports.fuzzy_hash()));
977 }
978
979 let request = malwaredb_api::SimilarSamplesRequest { hashes };
980
981 let response = self
982 .client
983 .post(format!("{}{}", self.url, malwaredb_api::SIMILAR_SAMPLES_URL))
984 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
985 .json(&request)
986 .send()
987 .await?
988 .json::<ServerResponse<SimilarSamplesResponse>>()
989 .await
990 .context(MDB_CLIENT_ERROR_CONTEXT)?;
991
992 match response {
993 ServerResponse::Success(similar) => Ok(similar),
994 ServerResponse::Error(e) => Err(e.into()),
995 }
996 }
997
998 pub async fn yara_search(&self, yara: &str) -> Result<YaraSearchRequestResponse> {
1004 let yara = YaraSearchRequest {
1005 rules: vec![yara.to_string()],
1006 response: PartialHashSearchType::SHA256,
1007 };
1008
1009 let response = self
1010 .client
1011 .post(format!("{}{}", self.url, malwaredb_api::YARA_SEARCH_URL))
1012 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
1013 .json(&yara)
1014 .send()
1015 .await?
1016 .json::<ServerResponse<YaraSearchRequestResponse>>()
1017 .await?;
1018
1019 match response {
1020 ServerResponse::Success(sources) => Ok(sources),
1021 ServerResponse::Error(e) => Err(e.into()),
1022 }
1023 }
1024
1025 pub async fn yara_result(&self, uuid: Uuid) -> Result<YaraSearchResponse> {
1031 let response = self
1032 .client
1033 .get(format!("{}{}/{uuid}", self.url, malwaredb_api::YARA_SEARCH_URL))
1034 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
1035 .send()
1036 .await?
1037 .json::<ServerResponse<YaraSearchResponse>>()
1038 .await?;
1039
1040 match response {
1041 ServerResponse::Success(sources) => Ok(sources),
1042 ServerResponse::Error(e) => Err(e.into()),
1043 }
1044 }
1045}
1046
1047impl Debug for MdbClient {
1048 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1049 writeln!(f, "MDB Client v{MDB_VERSION}: {}", self.url)
1050 }
1051}
1052
1053pub fn encode_to_cart(data: &[u8]) -> Result<Vec<u8>> {
1062 let mut input_buffer = Cursor::new(data);
1063 let mut output_buffer = Cursor::new(vec![]);
1064 let mut output_metadata = JsonMap::new();
1065
1066 let mut sha384 = Sha384::new();
1067 sha384.update(data);
1068 let sha384 = hex::encode(sha384.finalize());
1069
1070 let mut sha512 = Sha512::new();
1071 sha512.update(data);
1072 let sha512 = hex::encode(sha512.finalize());
1073
1074 output_metadata.insert("sha384".into(), sha384.into());
1075 output_metadata.insert("sha512".into(), sha512.into());
1076 output_metadata.insert("entropy".into(), entropy_calc(data).into());
1077 cart_container::pack_stream(
1078 &mut input_buffer,
1079 &mut output_buffer,
1080 Some(output_metadata),
1081 None,
1082 cart_container::digesters::default_digesters(),
1083 None,
1084 )?;
1085
1086 Ok(output_buffer.into_inner())
1087}
1088
1089pub fn decode_from_cart(data: &[u8]) -> Result<(Vec<u8>, Option<JsonMap>, Option<JsonMap>)> {
1098 let mut input_buffer = Cursor::new(data);
1099 let mut output_buffer = Cursor::new(vec![]);
1100 let (header, footer) =
1101 cart_container::unpack_stream(&mut input_buffer, &mut output_buffer, None)?;
1102 Ok((output_buffer.into_inner(), header, footer))
1103}
1104
1105fn path_load_cert(path: &Path) -> Result<(CertificateType, Certificate)> {
1112 if !path.exists() {
1113 bail!("Certificate {} does not exist.", path.display());
1114 }
1115 let cert = match path
1116 .extension()
1117 .context("can't determine file extension")?
1118 .to_str()
1119 .context("unable to parse file extension")?
1120 {
1121 "pem" => {
1122 let contents = std::fs::read(path)?;
1123 (CertificateType::PEM, Certificate::from_pem(&contents)?)
1124 }
1125 "der" => {
1126 let contents = std::fs::read(path)?;
1127 (CertificateType::DER, Certificate::from_der(&contents)?)
1128 }
1129 ext => {
1130 bail!("Unknown extension {ext:?}")
1131 }
1132 };
1133 Ok(cert)
1134}
1135
1136#[inline]
1144pub(crate) fn get_config_path(create: bool) -> Result<PathBuf> {
1145 let config = PathBuf::from(MDB_CLIENT_CONFIG_TOML);
1147 if config.exists() {
1148 return Ok(config);
1149 }
1150
1151 #[cfg(target_os = "haiku")]
1152 {
1153 let mut settings = PathBuf::from("/boot/home/config/settings/malwaredb");
1154 if create && !settings.exists() {
1155 std::fs::create_dir_all(&settings)?;
1156 }
1157 settings.push(MDB_CLIENT_CONFIG_TOML);
1158 return Ok(settings);
1159 }
1160
1161 #[cfg(unix)]
1162 {
1163 if let Some(xdg_home) = std::env::var_os("XDG_CONFIG_HOME") {
1165 let mut xdg_config_home = PathBuf::from(xdg_home);
1166 xdg_config_home.push(MDB_CLIENT_DIR);
1167 if create && !xdg_config_home.exists() {
1168 std::fs::create_dir_all(&xdg_config_home)?;
1169 }
1170 xdg_config_home.push(MDB_CLIENT_CONFIG_TOML);
1171 return Ok(xdg_config_home);
1172 }
1173 }
1174
1175 if let Some(mut home_config) = home_dir() {
1176 home_config.push(".config");
1177 home_config.push(MDB_CLIENT_DIR);
1178 if create && !home_config.exists() {
1179 std::fs::create_dir_all(&home_config)?;
1180 }
1181 home_config.push(MDB_CLIENT_CONFIG_TOML);
1182 return Ok(home_config);
1183 }
1184
1185 Ok(PathBuf::from(MDB_CLIENT_CONFIG_TOML))
1186}
1187
1188#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1190pub struct MalwareDBServer {
1191 pub host: String,
1193
1194 pub port: u16,
1196
1197 pub ssl: bool,
1199
1200 pub name: String,
1202}
1203
1204impl Display for MalwareDBServer {
1205 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1206 if self.ssl {
1207 write!(f, "https://{}:{}", self.host, self.port)
1208 } else {
1209 write!(f, "http://{}:{}", self.host, self.port)
1210 }
1211 }
1212}
1213
1214impl MalwareDBServer {
1215 pub async fn server_info(&self) -> Result<ServerInfo> {
1221 let client = reqwest::ClientBuilder::new()
1222 .gzip(true)
1223 .zstd(true)
1224 .use_rustls_tls()
1225 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")))
1226 .build()?;
1227
1228 let response = client
1229 .get(format!("{self}{}", malwaredb_api::SERVER_INFO_URL))
1230 .send()
1231 .await?
1232 .json::<ServerResponse<ServerInfo>>()
1233 .await
1234 .context(MDB_CLIENT_ERROR_CONTEXT)?;
1235
1236 match response {
1237 ServerResponse::Success(info) => Ok(info),
1238 ServerResponse::Error(e) => Err(e.into()),
1239 }
1240 }
1241
1242 #[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
1252 #[cfg(feature = "blocking")]
1253 pub fn server_info_blocking(&self) -> Result<ServerInfo> {
1254 let client = reqwest::blocking::ClientBuilder::new()
1255 .gzip(true)
1256 .zstd(true)
1257 .use_rustls_tls()
1258 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")))
1259 .build()?;
1260
1261 let response = client
1262 .get(format!("{self}{}", malwaredb_api::SERVER_INFO_URL))
1263 .send()?
1264 .json::<ServerResponse<ServerInfo>>()
1265 .context(MDB_CLIENT_ERROR_CONTEXT)?;
1266
1267 match response {
1268 ServerResponse::Success(similar) => Ok(similar),
1269 ServerResponse::Error(e) => Err(e.into()),
1270 }
1271 }
1272}
1273
1274pub fn discover_servers() -> Result<Vec<MalwareDBServer>> {
1280 const MAX_ITERS: usize = 5;
1281 let mdns = ServiceDaemon::new()?;
1282 let mut servers = HashSet::new();
1283 let receiver = mdns.browse(malwaredb_api::MDNS_NAME)?;
1284
1285 let mut counter = 0;
1286 while let Ok(event) = receiver.recv() {
1287 if let ServiceEvent::ServiceResolved(resolved) = event {
1288 let host = resolved.host.replace(".local.", "");
1289 let ssl = if let Some(ssl) = resolved.txt_properties.get("ssl") {
1290 ssl.val_str() == "true"
1291 } else {
1292 debug!(
1293 "MalwareDB entry for {host}:{} doesn't specify ssl, assuming not",
1294 resolved.port
1295 );
1296 false
1297 };
1298
1299 let server = MalwareDBServer {
1300 host,
1301 port: resolved.port,
1302 ssl,
1303 name: resolved.fullname.replace(malwaredb_api::MDNS_NAME, ""),
1304 };
1305
1306 servers.insert(server);
1307 }
1308 counter += 1;
1309 if counter > MAX_ITERS {
1310 break;
1311 }
1312 }
1313
1314 if mdns.shutdown().is_err() {
1315 }
1317 Ok(servers.into_iter().collect())
1318}
1319
1320#[cfg(test)]
1321mod tests {
1322 use super::*;
1323
1324 #[test]
1325 fn cart() {
1326 const BYTES: &[u8] = include_bytes!("../../crates/types/testdata/elf/elf_haiku_x86.cart");
1327 const ORIGINAL_SHA256: &str =
1328 "de10ba5e5402b46ea975b5cb8a45eb7df9e81dc81012fd4efd145ed2dce3a740";
1329
1330 let (decoded, header, footer) = decode_from_cart(BYTES).unwrap();
1331
1332 let mut sha256 = Sha256::new();
1333 sha256.update(&decoded);
1334 let sha256 = hex::encode(sha256.finalize());
1335 assert_eq!(sha256, ORIGINAL_SHA256);
1336
1337 let header = header.unwrap();
1338 let entropy = header.get("entropy").unwrap().as_f64().unwrap();
1339 assert!(entropy > 4.0 && entropy < 4.1);
1340
1341 let footer = footer.unwrap();
1342 assert_eq!(footer.get("length").unwrap(), "5093");
1343 assert_eq!(footer.get("sha256").unwrap(), ORIGINAL_SHA256);
1344 }
1345}