SDKs overview

MalShare offers Software Development Kits (SDKs) and libraries designed to facilitate interaction with its malware sample database and API. These tools enable developers to integrate MalShare's threat intelligence capabilities directly into their applications, scripts, and security solutions. The primary goal of these SDKs is to simplify common tasks such as searching for samples, retrieving file hashes, and downloading malware binaries for further analysis. By abstracting the underlying HTTP requests and API authentication, SDKs reduce development time and potential errors.

The MalShare API is designed around a RESTful architecture, allowing for straightforward integration using standard web technologies. While official SDKs focus on popular scripting languages, the open nature of the API encourages community contributions in other programming environments. Developers can access an extensive collection of malware samples and associated metadata, which is crucial for tasks like incident response, threat hunting, and security research. The official MalShare documentation provides comprehensive details on the API endpoints and expected request/response formats, ensuring developers can build custom integrations even without a dedicated SDK.

MalShare's approach to providing SDKs and API access aligns with general industry practices for security intelligence platforms, where programmatic access is key for automation and integration into larger security ecosystems. For example, similar programmatic access models are employed by services like VirusTotal, which also offers APIs for submitting and retrieving malware analysis reports, demonstrating a common need for flexible integration options in the cybersecurity domain.

Official SDKs by language

MalShare provides official SDKs or detailed examples primarily for scripting languages commonly used in security research and automation. These resources help developers quickly get started with the MalShare API without needing to re-implement API client logic. The official documentation includes code snippets and examples that serve as de facto SDKs for these languages.

The core functionality supported by these official resources includes:

  • Search: Querying the database for malware samples based on various criteria (e.g., hash, filename, tags).
  • Download: Retrieving specific malware samples for local analysis.
  • Metadata Retrieval: Accessing information such as file type, size, and submission date associated with samples.
  • Hash Lookups: Checking if a specific file hash exists in the MalShare database.

While formal, installable packages might be less prevalent compared to some commercial APIs, the provided examples are directly usable and well-documented. The MalShare documentation specifically highlights examples for Python, PHP, and Bash scripts, which are frequently used by security analysts for automation tasks. This focus reflects the practical needs of the target developer audience, emphasizing ease of use and rapid deployment.

Table of Official SDKs/Examples

Language Package/Approach Installation/Setup Maturity
Python Direct API calls with requests library (example scripts) pip install requests Production-ready (examples maintained)
PHP Direct API calls with curl or file_get_contents (example scripts) No specific package beyond PHP core extensions Production-ready (examples maintained)
Bash Direct API calls with curl (example scripts) No specific package beyond standard Unix utilities Production-ready (examples maintained)

Installation

Installation for MalShare's official SDKs primarily involves ensuring the necessary language runtime and standard HTTP client libraries are available. Since MalShare emphasizes direct API interaction through examples rather than distributing formal package manager-installable SDKs for every language, the installation process is often simplified to setting up the environment.

Python

For Python, the primary requirement is the requests library, which simplifies making HTTP requests. If you don't have it installed, you can add it using pip, Python's package installer:

pip install requests

After installation, you can directly use the provided Python examples from the MalShare API documentation by copying them into your project and replacing placeholder values with your MalShare API key.

PHP

PHP examples typically rely on built-in functions like file_get_contents or the cURL extension for HTTP requests. Most PHP installations include cURL by default or it can be easily enabled:

; On Debian/Ubuntu
sudo apt-get install php-curl
sudo service apache2 restart  # or php-fpm restart

; On RHEL/CentOS
sudo yum install php-curl
sudo systemctl restart httpd  # or php-fpm restart

Once cURL is enabled, the MalShare PHP examples can be used without further package installations.

Bash

Bash scripts leverage the curl command-line tool, which is commonly available on most Unix-like operating systems. If curl is not installed, it can be added via your system's package manager:

# On Debian/Ubuntu
sudo apt-get install curl

# On RHEL/CentOS
sudo yum install curl

With curl available, the MalShare Bash examples can be executed directly from the terminal.

Developers should always refer to the specific language's official documentation for detailed installation instructions for these core tools, for instance, the official Python downloads page or the PHP installation guide.

Quickstart example

This Python quickstart demonstrates how to search for a malware sample by hash and download it using the MalShare API. You will need a MalShare API key, which can be obtained by registering on the MalShare website.

Prerequisites:

  • Python 3 installed
  • requests library installed (pip install requests)
  • Your MalShare API key

Replace YOUR_API_KEY with your actual MalShare API key and TARGET_HASH with the specific SHA256 hash of the malware sample you wish to retrieve.


import requests
import os

API_KEY = "YOUR_API_KEY"  # Replace with your MalShare API key
BASE_URL = "https://malshare.com/api.php"
TARGET_HASH = "a3b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1" # Example SHA256 hash

def search_and_download_sample(api_key, base_url, target_hash):
    print(f"Searching for hash: {target_hash}")
    # First, check if the hash exists and get download link
    search_params = {
        "api_key": api_key,
        "action": "details",
        "hash": target_hash
    }
    try:
        search_response = requests.get(base_url, params=search_params)
        search_response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
        details = search_response.json()

        if details and details.get("STATUS") == "OK" and "link" in details:
            download_link = details["link"]
            filename = f"malware_sample_{target_hash}.zip"
            print(f"Found sample, downloading from: {download_link}")

            # Download the sample
            download_response = requests.get(download_link, stream=True)
            download_response.raise_for_status()

            with open(filename, "wb") as f:
                for chunk in download_response.iter_content(chunk_size=8192):
                    f.write(chunk)
            print(f"Sample downloaded to {os.path.abspath(filename)}")
        elif details and details.get("STATUS") == "ERROR":
            print(f"Error searching for hash: {details.get('MESSAGE', 'Unknown error')}")
        else:
            print("Sample not found or unexpected response structure.")

    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Connection error occurred: {conn_err}")
    except requests.exceptions.Timeout as timeout_err:
        print(f"Timeout error occurred: {timeout_err}")
    except requests.exceptions.RequestException as req_err:
        print(f"An error occurred during the request: {req_err}")
    except ValueError:
        print("Error decoding JSON response.")

if __name__ == "__main__":
    # This is an example hash. Always use a known hash from MalShare or your research.
    # MalShare provides a free tier with 500 API requests per day.
    # See https://malshare.com/pricing.html for more details.
    search_and_download_sample(API_KEY, BASE_URL, TARGET_HASH)

This script first queries the MalShare API for details about a specific hash. If the sample is found and a download link is provided, it then proceeds to download the sample and save it as a ZIP file. Malware samples from MalShare are typically password-protected with infected when downloaded as ZIP files to prevent accidental execution. It is crucial to handle downloaded samples within a secure, isolated environment such as a virtual machine or sandbox for analysis to prevent system compromise.

Community libraries

Beyond the official examples, the MalShare API's straightforward nature has led to the development of various community-contributed libraries and scripts. These libraries often wrap the API in more object-oriented ways or provide specialized functionality for specific use cases, such as integration with incident response platforms or automated sandbox analysis tools.

Community contributions can be found on platforms like GitHub, where developers share their projects. While these libraries may not carry the same official support as MalShare's own documentation examples, they can offer additional features, different language support, or more user-friendly interfaces for specific programming paradigms. When using community libraries, it is always recommended to:

  • Review the source code: Ensure the library's implementation aligns with security best practices and correctly interacts with the MalShare API.
  • Check for active maintenance: Libraries that are actively maintained are more likely to be compatible with future API changes and receive bug fixes.
  • Verify licensing: Understand the licensing terms of the community library before incorporating it into your projects.

Examples of community-driven development around threat intelligence APIs can be seen with other platforms as well, where users create custom scripts and integrations to fit their unique security operational needs. For instance, the broader open-source community provides numerous tools for working with various threat intelligence feeds, demonstrating the value of flexible APIs that allow for such extensions.

Developers interested in contributing to the MalShare ecosystem or finding existing community tools should search public code repositories. The MalShare API's clear documentation makes it accessible for third-party developers to build and share their own clients and tools, further expanding the utility of the platform for the cybersecurity community.