Skip to main content

malwaredb_client/
blocking.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::fmt::{Debug, Formatter};
4use std::fs::OpenOptions;
5use std::io::Write;
6use std::path::{Path, PathBuf};
7
8use crate::{MDB_CLIENT_ERROR_CONTEXT, get_config_path};
9use malwaredb_api::{
10    GetAPIKeyResponse, GetUserInfoResponse, Labels, PartialHashSearchType, Report, SearchRequest,
11    SearchRequestParameters, SearchResponse, SearchType, ServerInfo, ServerResponse,
12    SimilarSamplesResponse, Sources, SupportedFileTypes, YaraSearchRequest,
13    YaraSearchRequestResponse, YaraSearchResponse, digest::HashType,
14};
15use malwaredb_types::exec::pe32::EXE;
16
17use anyhow::{Context, Result, bail, ensure};
18use base64::Engine;
19use base64::engine::general_purpose;
20use fuzzyhash::FuzzyHash;
21use malwaredb_lzjd2::lzjd::LzDigest;
22use serde::{Deserialize, Serialize};
23use sha2::{Digest, Sha256};
24use tlsh_fixed::TlshBuilder;
25use tracing::{error, info, trace, warn};
26use uuid::Uuid;
27use zeroize::{Zeroize, ZeroizeOnDrop};
28
29/// Blocking Malware DB Client Configuration and connection which requires the `blocking` feature
30#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
31#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
32pub struct MdbClient {
33    /// URL of the Malware DB server, including http and port number, ending without a slash
34    pub url: String,
35
36    /// User's API key for Malware DB
37    api_key: String,
38
39    /// Blocking http client which stores the optional server certificate
40    #[zeroize(skip)]
41    #[serde(skip)]
42    client: reqwest::blocking::Client,
43
44    /// Server's certificate
45    #[cfg(target_os = "macos")]
46    #[zeroize(skip)]
47    #[serde(skip)]
48    cert: Option<crate::macos::CertificateData>,
49}
50
51impl MdbClient {
52    /// MDB Client from components, doesn't test connectivity
53    ///
54    /// # Errors
55    ///
56    /// Returns an error if a list of certificates was passed and any were not in the expected
57    /// DER or PEM format or could not be parsed.
58    ///
59    /// # Panics
60    ///
61    /// This method panics if called from within an async runtime.
62    pub fn new(url: String, api_key: String, cert_path: Option<PathBuf>) -> Result<Self> {
63        let mut url = url;
64        let url = if url.ends_with('/') {
65            url.pop();
66            url
67        } else {
68            url
69        };
70
71        let cert = if let Some(path) = cert_path {
72            Some((crate::path_load_cert(&path)?, path))
73        } else {
74            None
75        };
76
77        let builder = reqwest::blocking::ClientBuilder::new()
78            .deflate(true)
79            .gzip(true)
80            .zstd(true)
81            .use_rustls_tls()
82            .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
83
84        let client = if let Some(((_cert_type, cert), _path)) = &cert {
85            builder.add_root_certificate(cert.clone()).build()
86        } else {
87            builder.build()
88        }?;
89
90        #[cfg(target_os = "macos")]
91        let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
92            Some(crate::macos::CertificateData {
93                cert_type: *cert_type,
94                cert_bytes: std::fs::read(cert_path)?,
95            })
96        } else {
97            None
98        };
99
100        Ok(Self {
101            url,
102            api_key,
103            client,
104
105            #[cfg(target_os = "macos")]
106            cert,
107        })
108    }
109
110    /// Connect to a server anonymously.
111    ///
112    /// # Errors
113    ///
114    /// Networking errors may result, and there will be an error if the server doesn't support anonymous connections.
115    pub fn anonymous(url: String, save: bool, cert_path: Option<PathBuf>) -> Result<Self> {
116        let mut url = url;
117        let url = if url.ends_with('/') {
118            url.pop();
119            url
120        } else {
121            url
122        };
123
124        let builder = reqwest::blocking::ClientBuilder::new()
125            .gzip(true)
126            .zstd(true)
127            .use_rustls_tls()
128            .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
129
130        let cert = if let Some(path) = cert_path {
131            Some((crate::path_load_cert(&path)?, path))
132        } else {
133            None
134        };
135
136        let client = if let Some(((_cert_type, cert), _cert_path)) = &cert {
137            builder.add_root_certificate(cert.clone()).build()
138        } else {
139            builder.build()
140        }?;
141
142        let info = client
143            .get(format!("{url}{}", malwaredb_api::USER_INFO_URL))
144            .send()?
145            .json::<ServerResponse<GetUserInfoResponse>>()
146            .context(MDB_CLIENT_ERROR_CONTEXT)?;
147
148        if let ServerResponse::Success(info) = info {
149            ensure!(info.id > 0);
150        } else {
151            bail!("Anonymous access is not allowed");
152        }
153
154        #[cfg(target_os = "macos")]
155        let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
156            Some(crate::macos::CertificateData {
157                cert_type: *cert_type,
158                cert_bytes: std::fs::read(cert_path)?,
159            })
160        } else {
161            None
162        };
163
164        let client = Self {
165            url,
166            api_key: "anonymous".to_string(),
167            client,
168
169            #[cfg(target_os = "macos")]
170            cert,
171        };
172
173        let server_info = client.server_info()?;
174        if server_info.mdb_version > *crate::MDB_VERSION_SEMVER {
175            warn!(
176                "Server version {:?} is newer than client {:?}, consider updating.",
177                server_info.mdb_version,
178                crate::MDB_VERSION_SEMVER
179            );
180        }
181
182        if save && let Err(e) = client.save() {
183            error!("Anonymous connection successful but failed to save config: {e}");
184            bail!("Anonymous connection successful but failed to save config: {e}");
185        }
186
187        Ok(client)
188    }
189
190    /// Login to a server, optionally save the configuration file, and return a client object
191    ///
192    /// # Errors
193    ///
194    /// Returns an error if the server URL, username, or password were incorrect, or if a network
195    /// issue occurred.
196    ///
197    /// # Panics
198    ///
199    /// This method panics if called from within an async runtime.
200    pub fn login(
201        url: String,
202        username: String,
203        password: String,
204        save: bool,
205        cert_path: Option<PathBuf>,
206    ) -> Result<Self> {
207        let mut url = url;
208        let url = if url.ends_with('/') {
209            url.pop();
210            url
211        } else {
212            url
213        };
214
215        let api_request = malwaredb_api::GetAPIKeyRequest {
216            user: username,
217            password,
218        };
219
220        let builder = reqwest::blocking::ClientBuilder::new()
221            .gzip(true)
222            .zstd(true)
223            .use_rustls_tls()
224            .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
225
226        let cert = if let Some(path) = cert_path {
227            Some((crate::path_load_cert(&path)?, path))
228        } else {
229            None
230        };
231
232        let client = if let Some(((_cert_type, cert), _path)) = &cert {
233            builder.add_root_certificate(cert.clone()).build()
234        } else {
235            builder.build()
236        }?;
237
238        let res = client
239            .post(format!("{url}{}", malwaredb_api::USER_LOGIN_URL))
240            .json(&api_request)
241            .send()?
242            .json::<ServerResponse<GetAPIKeyResponse>>()
243            .context(MDB_CLIENT_ERROR_CONTEXT)?;
244
245        let res = match res {
246            ServerResponse::Success(res) => res,
247            ServerResponse::Error(err) => return Err(err.into()),
248        };
249
250        #[cfg(target_os = "macos")]
251        let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
252            Some(crate::macos::CertificateData {
253                cert_type: *cert_type,
254                cert_bytes: std::fs::read(cert_path)?,
255            })
256        } else {
257            None
258        };
259
260        let client = MdbClient {
261            url,
262            api_key: res.key.clone(),
263            client,
264
265            #[cfg(target_os = "macos")]
266            cert,
267        };
268
269        let server_info = client.server_info()?;
270        if server_info.mdb_version > *crate::MDB_VERSION_SEMVER {
271            warn!(
272                "Server version {:?} is newer than client {:?}, consider updating.",
273                server_info.mdb_version,
274                crate::MDB_VERSION_SEMVER
275            );
276        }
277
278        if save && let Err(e) = client.save() {
279            error!("Login successful but failed to save config: {e}");
280            bail!("Login successful but failed to save config: {e}");
281        }
282        Ok(client)
283    }
284
285    /// Reset one's own API key to effectively logout & disable all clients who are using the key
286    ///
287    /// # Errors
288    ///
289    /// Returns an error if there was a network issue or the user wasn't properly logged in.
290    pub fn reset_key(&self) -> Result<()> {
291        let response = self
292            .client
293            .get(format!("{}{}", self.url, malwaredb_api::USER_LOGOUT_URL))
294            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
295            .send()
296            .context(MDB_CLIENT_ERROR_CONTEXT)?;
297        if !response.status().is_success() {
298            bail!("failed to reset API key, was it correct?");
299        }
300        Ok(())
301    }
302
303    /// Malware DB Client configuration loaded from a specified path
304    ///
305    /// # Errors
306    ///
307    /// Returns an error if the configuration file cannot be read, possibly because it
308    /// doesn't exist or due to a permission error or a parsing error.
309    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
310        let name = path.as_ref().display();
311        let config =
312            std::fs::read_to_string(&path).context(format!("failed to read config file {name}"))?;
313        let cfg: MdbClient =
314            toml::from_str(&config).context(format!("failed to parse config file {name}"))?;
315        Ok(cfg)
316    }
317
318    /// Malware DB Client configuration from user's home directory
319    ///
320    /// On macOS, it will attempt to load this information in the Keychain, which isn't required.
321    ///
322    /// # Errors
323    ///
324    /// Returns an error if the configuration file cannot be read, possibly because it
325    /// doesn't exist or due to a permission error or a parsing error.
326    ///
327    /// # Panics
328    ///
329    /// This method panics if called from within an async runtime.
330    pub fn load() -> Result<Self> {
331        #[cfg(target_os = "macos")]
332        {
333            if let Ok((api_key, url, cert)) = crate::macos::retrieve_credentials() {
334                let builder = reqwest::blocking::ClientBuilder::new()
335                    .gzip(true)
336                    .zstd(true)
337                    .use_rustls_tls()
338                    .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
339
340                let client = if let Some(cert) = &cert {
341                    builder.add_root_certificate(cert.as_cert()?).build()
342                } else {
343                    builder.build()
344                }?;
345
346                return Ok(Self {
347                    url,
348                    api_key,
349                    client,
350                    cert,
351                });
352            }
353        }
354
355        let path = get_config_path(false)?;
356        if path.exists() {
357            return Self::from_file(path);
358        }
359        bail!("config file not found")
360    }
361
362    /// Save Malware DB Client configuration to the user's home directory
363    ///
364    /// On macOS, it will attempt to save this information in the Keychain, which isn't required.
365    ///
366    /// # Errors
367    ///
368    /// Returns an error if there was a problem saving the configuration file.
369    pub fn save(&self) -> Result<()> {
370        #[cfg(target_os = "macos")]
371        {
372            if crate::macos::save_credentials(&self.url, &self.api_key, self.cert.clone()).is_ok() {
373                return Ok(());
374            }
375        }
376
377        let toml = toml::to_string(self)?;
378        let path = get_config_path(true)?;
379
380        let mut options = OpenOptions::new();
381        options
382            .write(true)
383            .create(true)
384            .append(false)
385            .truncate(false);
386
387        #[cfg(target_family = "unix")]
388        {
389            use std::os::unix::fs::OpenOptionsExt;
390
391            options.mode(0o600);
392        }
393
394        let mut file = options.open(&path)?;
395        write!(file, "{toml}").context(format!("failed to write mdb config to {}", path.display()))
396    }
397
398    /// Delete the Malware DB client configuration file
399    ///
400    /// # Errors
401    ///
402    /// Returns an error if there isn't a configuration file to delete, or if it cannot be deleted,
403    /// possibly due to a permissions error.
404    pub fn delete(&self) -> Result<()> {
405        #[cfg(target_os = "macos")]
406        crate::macos::clear_credentials();
407
408        let path = get_config_path(false)?;
409        if path.exists() {
410            std::fs::remove_file(&path)
411                .context(format!("failed to delete client config file {}", path.display()))?;
412        }
413        Ok(())
414    }
415
416    // Actions of the client
417
418    /// Get information about the server, unauthenticated
419    ///
420    /// # Errors
421    ///
422    /// This may return an error if there's a network situation.
423    pub fn server_info(&self) -> Result<ServerInfo> {
424        let response = self
425            .client
426            .get(format!("{}{}", self.url, malwaredb_api::SERVER_INFO_URL))
427            .send()?
428            .json::<ServerResponse<ServerInfo>>()
429            .context(MDB_CLIENT_ERROR_CONTEXT)?;
430
431        match response {
432            ServerResponse::Success(info) => Ok(info),
433            ServerResponse::Error(e) => Err(e.into()),
434        }
435    }
436
437    /// Get file types supported by the server, unauthenticated
438    ///
439    /// # Errors
440    ///
441    /// This may return an error if there's a network situation.
442    pub fn supported_types(&self) -> Result<SupportedFileTypes> {
443        let response = self
444            .client
445            .get(format!("{}{}", self.url, malwaredb_api::SUPPORTED_FILE_TYPES_URL))
446            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
447            .send()?
448            .json::<ServerResponse<SupportedFileTypes>>()
449            .context(MDB_CLIENT_ERROR_CONTEXT)?;
450
451        match response {
452            ServerResponse::Success(types) => Ok(types),
453            ServerResponse::Error(e) => Err(e.into()),
454        }
455    }
456
457    /// Get information about the user
458    ///
459    /// # Errors
460    ///
461    /// This may return an error if there's a network situation or if the user is not logged in
462    /// or not properly authorized to connect.
463    pub fn whoami(&self) -> Result<GetUserInfoResponse> {
464        let response = self
465            .client
466            .get(format!("{}{}", self.url, malwaredb_api::USER_INFO_URL))
467            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
468            .send()?
469            .json::<ServerResponse<GetUserInfoResponse>>()
470            .context(MDB_CLIENT_ERROR_CONTEXT)?;
471
472        match response {
473            ServerResponse::Success(info) => Ok(info),
474            ServerResponse::Error(e) => Err(e.into()),
475        }
476    }
477
478    /// Get the sample labels known to the server
479    ///
480    /// # Errors
481    ///
482    /// This may return an error if there's a network situation or if the user is not logged in
483    /// or not properly authorized to connect.
484    pub fn labels(&self) -> Result<Labels> {
485        let response = self
486            .client
487            .get(format!("{}{}", self.url, malwaredb_api::LIST_LABELS_URL))
488            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
489            .send()?
490            .json::<ServerResponse<Labels>>()
491            .context(MDB_CLIENT_ERROR_CONTEXT)?;
492
493        match response {
494            ServerResponse::Success(labels) => Ok(labels),
495            ServerResponse::Error(e) => Err(e.into()),
496        }
497    }
498
499    /// Get the sources available to the current user
500    ///
501    /// # Errors
502    ///
503    /// This may return an error if there's a network situation or if the user is not logged in
504    /// or not properly authorized to connect.
505    pub fn sources(&self) -> Result<Sources> {
506        let response = self
507            .client
508            .get(format!("{}{}", self.url, malwaredb_api::LIST_SOURCES_URL))
509            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
510            .send()?
511            .json::<ServerResponse<Sources>>()
512            .context(MDB_CLIENT_ERROR_CONTEXT)?;
513
514        match response {
515            ServerResponse::Success(sources) => Ok(sources),
516            ServerResponse::Error(e) => Err(e.into()),
517        }
518    }
519
520    /// Submit one file to Malware DB: provide the contents, file name, and source ID
521    ///
522    /// # Errors
523    ///
524    /// This may return an error if there's a network situation or if the user is not logged in
525    /// or not properly authorized to connect.
526    pub fn submit(
527        &self,
528        contents: impl AsRef<[u8]>,
529        file_name: String,
530        source_id: u32,
531    ) -> Result<bool> {
532        let mut hasher = Sha256::new();
533        hasher.update(&contents);
534        let result = hasher.finalize();
535
536        let encoded = general_purpose::STANDARD.encode(contents);
537
538        let payload = malwaredb_api::NewSampleB64 {
539            file_name,
540            source_id,
541            file_contents_b64: encoded,
542            sha256: hex::encode(result),
543        };
544
545        match self
546            .client
547            .post(format!("{}{}", self.url, malwaredb_api::UPLOAD_SAMPLE_JSON_URL))
548            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
549            .json(&payload)
550            .send()
551        {
552            Ok(res) => {
553                if !res.status().is_success() {
554                    info!("Code {} sending {}", res.status(), payload.file_name);
555                }
556                Ok(res.status().is_success())
557            }
558            Err(e) => {
559                let status: String = e
560                    .status()
561                    .map(|s| s.as_str().to_string())
562                    .unwrap_or_default();
563                error!("Error{status} sending {}: {e}", payload.file_name);
564                bail!(e.to_string())
565            }
566        }
567    }
568
569    /// Submit one file to Malware DB: provide the contents, file name, and source ID
570    /// Experimental! May be removed at any point.
571    ///
572    /// # Errors
573    ///
574    /// This may return an error if there's a network situation or if the user is not logged in
575    /// or not properly authorized to connect.
576    pub fn submit_as_cbor(
577        &self,
578        contents: impl AsRef<[u8]>,
579        file_name: String,
580        source_id: u32,
581    ) -> Result<bool> {
582        let mut hasher = Sha256::new();
583        hasher.update(&contents);
584        let result = hasher.finalize();
585
586        let payload = malwaredb_api::NewSampleBytes {
587            file_name,
588            source_id,
589            file_contents: contents.as_ref().to_vec(),
590            sha256: hex::encode(result),
591        };
592
593        let mut bytes = Vec::with_capacity(payload.file_contents.len());
594        ciborium::ser::into_writer(&payload, &mut bytes)?;
595
596        match self
597            .client
598            .post(format!("{}{}", self.url, malwaredb_api::UPLOAD_SAMPLE_CBOR_URL))
599            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
600            .header("content-type", "application/cbor")
601            .body(bytes)
602            .send()
603        {
604            Ok(res) => {
605                if !res.status().is_success() {
606                    info!("Code {} sending {}", res.status(), payload.file_name);
607                }
608                Ok(res.status().is_success())
609            }
610            Err(e) => {
611                let status: String = e
612                    .status()
613                    .map(|s| s.as_str().to_string())
614                    .unwrap_or_default();
615                error!("Error{status} sending {}: {e}", payload.file_name);
616                bail!(e.to_string())
617            }
618        }
619    }
620
621    /// Search for a file based on partial hash and/or partial file name, returns a list of hashes
622    ///
623    /// # Errors
624    ///
625    /// * This may return an error if there's a network situation or if the user is not logged in or the request isn't valid
626    pub fn partial_search(
627        &self,
628        partial_hash: Option<(PartialHashSearchType, String)>,
629        name: Option<String>,
630        response: PartialHashSearchType,
631        limit: u32,
632    ) -> Result<SearchResponse> {
633        let query = SearchRequest {
634            search: SearchType::Search(SearchRequestParameters {
635                partial_hash,
636                file_name: name,
637                response,
638                limit,
639                labels: None,
640                file_type: None,
641                magic: None,
642            }),
643        };
644
645        self.do_search_request(&query)
646    }
647
648    /// Search for a file based on partial hash and/or partial file name, labels, file type; returns a list of hashes
649    ///
650    /// # Errors
651    ///
652    /// * This may return an error if there's a network situation or if the user is not logged in or the request isn't valid
653    #[allow(clippy::too_many_arguments)]
654    pub fn partial_search_labels_type(
655        &self,
656        partial_hash: Option<(PartialHashSearchType, String)>,
657        name: Option<String>,
658        response: PartialHashSearchType,
659        labels: Option<Vec<String>>,
660        file_type: Option<String>,
661        magic: Option<String>,
662        limit: u32,
663    ) -> Result<SearchResponse> {
664        let query = SearchRequest {
665            search: SearchType::Search(SearchRequestParameters {
666                partial_hash,
667                file_name: name,
668                response,
669                limit,
670                file_type,
671                magic,
672                labels,
673            }),
674        };
675
676        self.do_search_request(&query)
677    }
678
679    /// Return the next page from the search result
680    ///
681    /// # Errors
682    ///
683    /// Returns an error if there is a network problem, or pagination not available
684    pub fn next_page_search(&self, response: &SearchResponse) -> Result<SearchResponse> {
685        if let Some(uuid) = response.pagination {
686            let request = SearchRequest {
687                search: SearchType::Continuation(uuid),
688            };
689            return self.do_search_request(&request);
690        }
691
692        bail!("Pagination not available")
693    }
694
695    fn do_search_request(&self, query: &SearchRequest) -> Result<SearchResponse> {
696        ensure!(
697            query.is_valid(),
698            "Query isn't valid: hash isn't hexidecimal or both the hashes and file name are empty"
699        );
700
701        let response = self
702            .client
703            .post(format!("{}{}", self.url, malwaredb_api::SEARCH_URL))
704            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
705            .json(query)
706            .send()?
707            .json::<ServerResponse<SearchResponse>>()
708            .context(MDB_CLIENT_ERROR_CONTEXT)?;
709
710        match response {
711            ServerResponse::Success(search) => Ok(search),
712            ServerResponse::Error(e) => Err(e.into()),
713        }
714    }
715
716    /// Retrieve sample by hash, optionally in the `CaRT` format
717    ///
718    /// # Errors
719    ///
720    /// This may return an error if there's a network situation or if the user is not logged in
721    /// or not properly authorized to connect.
722    pub fn retrieve(&self, hash: &str, cart: bool) -> Result<Vec<u8>> {
723        let api_endpoint = if cart {
724            format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE_CART_URL)
725        } else {
726            format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE_URL)
727        };
728
729        let res = self
730            .client
731            .get(format!("{}{api_endpoint}", self.url))
732            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
733            .send()?;
734
735        if !res.status().is_success() {
736            bail!("Received code {}", res.status());
737        }
738
739        let content_digest = res.headers().get("content-digest").map(ToOwned::to_owned);
740        let body = res.bytes()?;
741        let bytes = body.to_vec();
742
743        // TODO: Make this required in v0.3
744        if let Some(digest) = content_digest {
745            let hash = HashType::from_content_digest_header(digest.to_str()?)?;
746            if hash.verify(&bytes) {
747                trace!("Hash verified for sample {hash}");
748            } else {
749                error!("Hash mismatch for sample {hash}");
750            }
751        } else {
752            warn!("No content digest header received for sample {hash}");
753        }
754
755        Ok(bytes)
756    }
757
758    /// Fetch a report for a sample
759    ///
760    /// # Errors
761    ///
762    /// This may return an error if there's a network situation or if the user is not logged in
763    /// or not properly authorized to connect.
764    pub fn report(&self, hash: &str) -> Result<Report> {
765        let response = self
766            .client
767            .get(format!("{}{}/{hash}", self.url, malwaredb_api::SAMPLE_REPORT_URL))
768            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
769            .send()?
770            .json::<ServerResponse<Report>>()
771            .context(MDB_CLIENT_ERROR_CONTEXT)?;
772
773        match response {
774            ServerResponse::Success(report) => Ok(report),
775            ServerResponse::Error(e) => Err(e.into()),
776        }
777    }
778
779    /// Find similar samples in `MalwareDB` based on the contents of a given file.
780    /// This does not submit the sample to `MalwareDB`.
781    ///
782    /// # Errors
783    ///
784    /// This may return an error if there's a network situation or if the user is not logged in
785    /// or not properly authorized to connect.
786    pub fn similar(&self, contents: &[u8]) -> Result<SimilarSamplesResponse> {
787        let mut hashes = vec![];
788        let ssdeep_hash = FuzzyHash::new(contents);
789
790        let lzjd_str = LzDigest::from(contents).to_string();
791        hashes.push((malwaredb_api::SimilarityHashType::LZJD, lzjd_str));
792        hashes.push((malwaredb_api::SimilarityHashType::SSDeep, ssdeep_hash.to_string()));
793
794        let mut builder = TlshBuilder::new(
795            tlsh_fixed::BucketKind::Bucket256,
796            tlsh_fixed::ChecksumKind::ThreeByte,
797            tlsh_fixed::Version::Version4,
798        );
799
800        builder.update(contents);
801        if let Ok(hasher) = builder.build() {
802            hashes.push((malwaredb_api::SimilarityHashType::TLSH, hasher.hash()));
803        }
804
805        if let Ok(exe) = EXE::from(contents)
806            && let Some(imports) = exe.imports
807        {
808            hashes
809                .push((malwaredb_api::SimilarityHashType::ImportHash, hex::encode(imports.hash())));
810            hashes.push((malwaredb_api::SimilarityHashType::FuzzyImportHash, imports.fuzzy_hash()));
811        }
812
813        let request = malwaredb_api::SimilarSamplesRequest { hashes };
814
815        let response = self
816            .client
817            .post(format!("{}{}", self.url, malwaredb_api::SIMILAR_SAMPLES_URL))
818            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
819            .json(&request)
820            .send()?
821            .json::<ServerResponse<SimilarSamplesResponse>>()
822            .context(MDB_CLIENT_ERROR_CONTEXT)?;
823
824        match response {
825            ServerResponse::Success(similar) => Ok(similar),
826            ServerResponse::Error(e) => Err(e.into()),
827        }
828    }
829
830    /// Submit a Yara rule and return the UUID of the search for later retrieval.
831    ///
832    /// # Errors
833    ///
834    /// Network or authentication errors
835    pub fn yara_search(&self, yara: &str) -> Result<YaraSearchRequestResponse> {
836        let yara = YaraSearchRequest {
837            rules: vec![yara.to_string()],
838            response: PartialHashSearchType::SHA256,
839        };
840
841        let response = self
842            .client
843            .post(format!("{}{}", self.url, malwaredb_api::YARA_SEARCH_URL))
844            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
845            .json(&yara)
846            .send()?
847            .json::<ServerResponse<YaraSearchRequestResponse>>()?;
848
849        match response {
850            ServerResponse::Success(similar) => Ok(similar),
851            ServerResponse::Error(e) => Err(e.into()),
852        }
853    }
854
855    /// Get the result from a Yara search
856    ///
857    /// # Errors
858    ///
859    /// Network or authentication errors
860    pub fn yara_result(&self, uuid: Uuid) -> Result<YaraSearchResponse> {
861        let response = self
862            .client
863            .get(format!("{}{}/{uuid}", self.url, malwaredb_api::YARA_SEARCH_URL))
864            .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
865            .send()?
866            .json::<ServerResponse<YaraSearchResponse>>()?;
867
868        match response {
869            ServerResponse::Success(sources) => Ok(sources),
870            ServerResponse::Error(e) => Err(e.into()),
871        }
872    }
873}
874
875impl Debug for MdbClient {
876    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
877        use crate::MDB_VERSION;
878
879        writeln!(f, "MDB Client v{MDB_VERSION}: {}", self.url)
880    }
881}
882
883/// Wrapper around search results for iterating over resulting hashes with the blocking client
884///
885/// ```rust,no_run
886/// use malwaredb_client::blocking::{MdbClient, IterableHashSearchResult};
887/// use malwaredb_client::malwaredb_api::{PartialHashSearchType, SearchType};
888///
889/// let client = MdbClient::load().expect("Failed to load client or parse config file");
890///
891/// // Get the first 100 files where the file name contains "foo", returning hashes as SHA-256
892/// let search_result = client.partial_search(None, Some("foo".into()), PartialHashSearchType::SHA256, 100).unwrap();
893/// for hash in IterableHashSearchResult::from(search_result, &client) {
894///     println!("{hash}");
895/// }
896/// ```
897#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
898pub struct IterableHashSearchResult<'a> {
899    /// Server search result
900    pub response: SearchResponse,
901
902    /// Blocking client
903    client: &'a MdbClient,
904}
905
906impl<'a> IterableHashSearchResult<'a> {
907    /// Iterate over the hashes from a search result and blocking client
908    #[must_use]
909    pub fn from(response: SearchResponse, client: &'a MdbClient) -> Self {
910        Self { response, client }
911    }
912}
913
914impl Iterator for IterableHashSearchResult<'_> {
915    type Item = String;
916
917    fn next(&mut self) -> Option<Self::Item> {
918        if let Some(hash) = self.response.hashes.pop() {
919            Some(hash)
920        } else if let Some(uuid) = self.response.pagination {
921            let request = SearchRequest {
922                search: SearchType::Continuation(uuid),
923            };
924
925            self.response = match self.client.do_search_request(&request) {
926                Ok(response) => response,
927                Err(e) => {
928                    warn!("Failed to continue search: {e}");
929                    return None;
930                }
931            };
932
933            self.response.hashes.pop()
934        } else {
935            None
936        }
937    }
938}
939
940/// Wrapper around search results for iterating over resulting binaries with the blocking client
941#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
942pub struct IterableSampleSearchResult<'a> {
943    /// Server search result
944    pub response: SearchResponse,
945
946    /// Blocking client
947    client: &'a MdbClient,
948}
949
950impl<'a> IterableSampleSearchResult<'a> {
951    /// Iterate over the hashes from a search result and blocking client, returning the binary
952    #[must_use]
953    pub fn from(response: SearchResponse, client: &'a MdbClient) -> Self {
954        Self { response, client }
955    }
956}
957
958impl Iterator for IterableSampleSearchResult<'_> {
959    type Item = Vec<u8>;
960
961    fn next(&mut self) -> Option<Self::Item> {
962        if let Some(hash) = self.response.hashes.pop() {
963            let binary = match self.client.retrieve(&hash, false) {
964                Ok(binary) => binary,
965                Err(e) => {
966                    error!("Failed to download {hash}: {e}");
967                    return None;
968                }
969            };
970            Some(binary)
971        } else if let Some(uuid) = self.response.pagination {
972            let request = SearchRequest {
973                search: SearchType::Continuation(uuid),
974            };
975
976            self.response = match self.client.do_search_request(&request) {
977                Ok(response) => response,
978                Err(e) => {
979                    warn!("Failed to continue search: {e}");
980                    return None;
981                }
982            };
983
984            if let Some(hash) = self.response.hashes.pop() {
985                let binary = match self.client.retrieve(&hash, false) {
986                    Ok(binary) => binary,
987                    Err(e) => {
988                        error!("Failed to download {hash}: {e}");
989                        return None;
990                    }
991                };
992                Some(binary)
993            } else {
994                None
995            }
996        } else {
997            None
998        }
999    }
1000}