Skip to content

Models as Code: Measuring Malicious Code Poisoning Attacks on Pretrained Model HubsModels Are Codes: Towards Measuring Malicious Code Poisoning Attacks on Pre-trained Model Hubs

arXiv· arXiv:2409.09368· ASE 2024· Jian Zhao, Shenao Wang, Yanjie Zhao, Xinyi Hou, Kailong Wang, Peiming Gao, Yuanchao Zhang, Chen Wei, Haoyu WangHuazhong University of Science and Technology; MYbank, Ant GroupIndexed by this site · 23 days ago· Originally publishedSelected DefensesSelectedAttention43

Quick read

Defenses

Based on the paper PDF (AI-generated); refer to the original

The authors systematically study malicious code poisoning on Hugging Face and build the detection pipeline MalHug, discovering 91 malicious models and 9 malicious dataset loading scripts over three months on the Ant Group mirror.

Threat modelAttackers can access the model hub's public interface and upload malicious datasets and models; they can hijack trusted accounts via leaked authentication tokens or use AI Jacking to register abandoned names to gain trust; the victim systems are users who load datasets (load_dataset executes loading scripts by default) or deserialize models (pickle variants, Keras Lambda layers).

Questions
Pretrained model hubs such as Hugging Face face malicious code poisoning: attackers can embed code in dataset loading scripts or serialized model files such as pickle, which executes when users load them. Existing tools struggle to perform semantic-level analysis, and there is a lack of systematic understanding of the PTM supply chain attack surface.
Methods
The authors first conduct threat modeling, classification of 15 model formats, and root-cause analysis of vulnerabilities, then propose the MalHug pipeline: extracting dataset loading scripts, decompiling model files, and combining Scalpel-based taint analysis with YARA-based heuristic pattern matching to identify malicious behavior.
Experiments and results
MalHug was deployed on Ant Group's Hugging Face mirror and ran for over three months, analyzing 705,991 models and 176,386 datasets, and detected 91 malicious models (76 Pickle variants, 15 Keras Lambda layers) and 9 malicious loading scripts, involving remote control, credential theft, and system reconnaissance.
Limitations and future work
The authors note: access restrictions meant not all models and datasets on the platform could be covered; the list of unsafe libraries/APIs may not exhaust in-the-wild exploitation methods; anti-static-analysis techniques such as obfuscation cannot be ruled out; and merely flagging unsafe TensorFlow operators may produce false positives (Discussion section).
Experimental setupHugging Face 镜像(705,991 个模型、176,386 个数据集) · 恶意模型与恶意数据集加载脚本数量、不安全 API/库出现次数 et al.
Benchmarks
Hugging Face 镜像(705,991 个模型、176,386 个数据集)
Metrics
恶意模型与恶意数据集加载脚本数量不安全 API/库出现次数模型格式分布占比
AI summaryand selection rationaleResearchers from Huazhong University of Science and Technology and Ant Group proposed a detection pipeline, MalHug, which ran for more than three months on a Hugging Face mirror instance within Ant Group's infrastructure, scanning more than 705K models and 176K datasets and finding 91 malicious models and 9 malicious dataset loading scripts. The authors say this is the first systematic study of malicious code poisoning attacks on pretrained model hubs; MalHug combines dataset loading script extraction, model deserialization, taint analysis, and heuristic pattern matching, filling the gap in semantic-level analysis of tools such as Fickling and ModelScan. The malicious behaviors found include reverse shells, browser credential theft, and system reconnaissance; the paper also provides a code injection risk classification for 15 model formats, noting that more than 55% of models use Pickle-based serialization, and the related malicious samples have been released on GitHub (security-pride/MalHug).

Researchers from Huazhong University of Science and Technology and Ant Group proposed a detection pipeline, MalHug, which ran for more than three months on a Hugging Face mirror instance within Ant Group's infrastructure, scanning more than 705K models and 176K datasets and finding 91 malicious models and 9 malicious dataset loading scripts. The authors say this is the first systematic study of malicious code poisoning attacks on pretrained model hubs; MalHug combines dataset loading script extraction, model deserialization, taint analysis, and heuristic pattern matching, filling the gap in semantic-level analysis of tools such as Fickling and ModelScan. The malicious behaviors found include reverse shells, browser credential theft, and system reconnaissance; the paper also provides a code injection risk classification for 15 model formats, noting that more than 55% of models use Pickle-based serialization, and the related malicious samples have been released on GitHub (security-pride/MalHug).

Why it was selectedMalHug ran for three months on Ant Group's mirror site, scanning 705K models and 176K datasets and finding 91 malicious models, providing a supply chain risk reference for teams that depend on pretrained models.

Related events and news

0 events · 1 news mentions

News that mentions this paper

Paper analysis

6 questions; open one to read the full answer

  1. What problem does this paper attempt to solve?

    Studies malicious code poisoning attacks on Hugging Face and proposes the detection pipeline MalHug to fill the semantic analysis gap of existing tools.

    Core problem: malicious code poisoning attacks on pretrained model hubs (mainly Hugging Face) lack systematic study, and existing detection tools struggle to perform semantic-level analysis.

    • Problem setting: As of July 12, 2024, Hugging Face hosts over 761K models and 176K datasets; the authors state that recent security reports have disclosed vulnerabilities and malicious attack instances on the platform, such as executing malicious code at model load time via pickle serialization, which can achieve goals such as backdoor installation, sensitive information theft, and ransomware deployment.
    • Inadequacy of existing tools: The authors state that Fickling, ModelScan, Pickle Scanning, etc. mainly rely on detecting specific library and function calls rather than analyzing the code actually executed, making semantic-level analysis of malicious behavior difficult, and may produce false positives and false negatives against complex or obfuscated attacks; moreover, there is a lack of comprehensive understanding of PTM supply chain abuse and attack techniques.
    • Core work of the paper: The authors state this is the first systematic study on malicious code poisoning attacks against pretrained model hubs, including threat modeling, classification of 15 model formats, and root-cause analysis of vulnerabilities, and proposes MalHug, an end-to-end detection pipeline for Hugging Face.
    • Threat model (§2.2):
      • Attacker goal: Execute malicious code when a user loads a model or dataset through code poisoning.
      • Attacker capability: Can access the model hub's public interface, create and upload malicious datasets and models.
      • Trust acquisition means: Use leaked authentication tokens to hijack trusted accounts, or use AI Jacking to register abandoned names of well-known models/datasets.
      • Victim systems and assumptions: Users generally trust well-known model hubs and popular contributors; when loading datasets, load_dataset executes the same-named loading script by default, and deserializing pickle-type models executes embedded code.
  2. What related research exists?

    Related work is divided into three groups: model-centric malicious code poisoning research, model-centric security research, and existing detection tools; the authors state that this paper is the first systematic study centered on PTMs.

    Malicious Code Poisoning Attack Research

    • Ladisa et al. (2023)—proposed a taxonomy of open-source software supply chain attacks, covering 107 unique attack vectors and 94 real-world incidents.
    • Hua et al. (2024, MalModel)—demonstrated how to hide malicious payloads in mobile deep learning models using black-box backdoor attacks.
    • Duan et al. (2021), Ohm et al. (2020), etc.—studied supply chain attacks on interpreted-language package managers; the authors state this paper extends the understanding to code poisoning specifically targeting pretrained model hubs.

    Model Hub Security Research

    • Zhou (2024)—examined unsafe deserialization in pretrained large model hubs, disclosing the risks of unsafe pickle.loads operations.
    • Walker and Wood (2024)—analyzed machine learning supply chain attacks, pointing out the dangers of maliciously crafted model files.
    • Jiang et al. (2022)—studied artifacts and security features of multiple model hubs, exposing insufficient protection for PTMs; Jiang et al. (2023) separately studied PTM naming practices on Hugging Face and proposed DARA to detect naming anomalies.

    Existing Detection Tools (Comparison Targets)

    • Pickle Scanning (Hugging Face), PickleScan (mmaitre314), Fickling (Trail of Bits)—detect unsafe library and API calls in pickle files, support only Pickle, and do not support datasets (Table 6).
    • Bhakti (Dropbox)—extends to unsafe Lambda layer detection in TensorFlow and Keras models, but is still library/API-level analysis and does not analyze dataset loading scripts.
    • ModelScan (ProtectAI)—supports Pickle variants and TensorFlow/Keras formats, but is likewise at Unsafe Lib & API granularity and does not support datasets (Table 6).

    Positioning of This Paper: The authors state that this paper is the first systematic study specifically on malicious code injection attacks against pretrained model hubs, analyzing not only vulnerabilities and attack vectors but also implementing a detection pipeline deployed in a real industrial environment; compared with the above tools, MalHug performs semantic-level analysis and covers dataset loading scripts (Table 6).

  3. How does the paper address this problem?

    First conduct threat modeling and root cause analysis of 15 model formats, then build the four-component pipeline MalHug: script extraction, model deserialization, taint analysis, and heuristic pattern matching.

    The overall approach is to first understand the attack surface through pilot studies (threat modeling, format classification, root cause analysis), then build an end-to-end detection pipeline MalHug, comprising four components: dataset loading script extraction, model deserialization, deep taint analysis, and heuristic pattern matching (Figure 1).

    Format Classification and Root Cause Analysis

    • Classification: Table 2 divides 15 popular model formats into "architecture + weights" and "weights only" categories by storage capability, and marks code injection vulnerability: pickle, marshal, joblib, dill, and cloudpickle are vulnerable; SavedModel, Checkpoint, TFLite, and HDF5 are partially vulnerable; GGUF, ONNX, JSON, MsgPack, Safetensors, and NPY/NPZ are not vulnerable (according to current understanding).
    • Root cause: The authors believe the vulnerability stems from the tension between flexibility and security in serialization design—arbitrary object instantiation in pickle variants blurs the boundary between data and code; HDF5 (Keras) Lambda layers introduce indirect risk by depending on the marshal module; SavedModel/TFLite custom operators have a smaller attack surface but still carry risk.

    Dataset Loading Script Analysis (§4.1)

    • Process: Extract the loading script for each dataset, scan import statements and function calls, and compare against a list of unsafe libraries/APIs.
    • List sources: Compiled by combining static analysis rules from Pyre and Semgrep, covering categories such as built-in functions, command execution, network, file system, system information, and cryptography (Table 3); identified using regular expressions and AST parsing.

    Model File Analysis (§4.2)

    • PyTorch/Pickle variants: Extract data.pkl from the model archive, disassemble it into opcodes with pickletools, and scan for unsafe opcodes summarized from manual auditing (Table 4, such as REDUCE, GLOBAL, OBJ, INST, NEWOBJ, NEWOBJ_EX); upon discovery, use Fickling to decompile into an AST and extract suspicious code snippets from function call arguments (Figure 2).
    • TensorFlow/Keras: Algorithm 1 parses SavedModel and HDF5 structures, detecting Lambda layers and unsafe operators (such as tf.io.read_file, tf.io.write_file); for Lambda layers, prepend a Python version header to the marshal-serialized bytecode and then use a .pyc decompiler to recover the source code; for unsafe operators, only flag them without further analysis, with the authors' stated reason being that these operators cannot directly inject system commands.

    Deep Taint Analysis (§4.3)

    • Foundation: Build control flow graphs and data flow graphs based on the open-source static analysis framework Scalpel.
    • Configuration: Define source-sink API combinations by malicious behavior category (hidden authentication, backdoor, cryptojacking, embedded shell, remote control, sensitive information leakage, suspicious execution patterns), with sources and sinks taken from the unsafe APIs in Table 3.

    Heuristic Pattern Matching (§4.4)

    • Motivation: The authors believe that taint sources such as malicious shell commands or obfuscated code patterns cannot be flagged solely through Python APIs.
    • Approach: Use YARA rules for pattern matching, complementing taint analysis to cover both API-based and pattern-based threats.
  4. What experiments did the paper conduct?

    MalHug was deployed on Ant Group's Hugging Face mirror for over three months, analyzing 705,991 models and 176,386 datasets, and detected 91 malicious models and 9 malicious loading scripts.

    Experimental Setup

    • Deployment environment: The MalHug prototype was deployed on Ant Group's internal Hugging Face mirror instance and ran for over three months; the server was Ubuntu 22.04, dual AMD EPYC Milan 7713 CPUs, 512 GB memory, two NVIDIA A100 80 GB GPUs.
    • Analysis targets: Metadata for 760,999 models and 176,849 datasets was collected using the huggingface-hub library (as of July 12, 2024); after excluding restricted-access ones, 705,991 models and 176,386 datasets were actually analyzed, totaling 179.4 TB.
    • Implementation basis: The model decompilation module uses open-source Fickling and ModelScan for preliminary filtering, taint analysis is based on Scalpel, plus custom YARA rules.
    • Evaluation method: The paper states that because of the lack of a high-quality malicious-sample ground truth dataset, it instead evaluated MalHug's performance in the real world and conducted a measurement study; malicious behavior classification relied on static analysis and manual review by experienced researchers, distinguishing proof-of-concept from actual malicious behavior.
    • Comparison method: Qualitative comparison with SOTA tools (Table 6), with no quantitative detection-rate comparison experiment.

    Main Results

    MetricValueSource
    Model repositories analyzed705,991§5.1
    Datasets analyzed176,386§5.1
    Datasets containing loading scripts6,578 (3.73%)§5.2
    Malicious models detected91 (76 Pickle variants + 15 Keras Lambda layers)§5.2
    Malicious dataset loading scripts detected9§5.2
    Publication time range of malicious artifactsMarch 2022 to June 2024§5.2
    • The authors state that malicious behavior categories mainly include remote control, sensitive information theft, and proof-of-concept (Figure 4).
    • The authors state that during the observation period the number of malicious behaviors fluctuated but generally trended upward, with the highest proportions in Q1 and Q2 of 2024, which they suggest implies that the complexity and frequency of recent malicious activity are increasing.

    Model Format Distribution Measurement

    • What was measured: Statistics on the distribution of model file formats on Hugging Face (Figure 3).
    • Results: PyTorch format (.pt/.pth/.bin) 335,893 (51.0%), explicit Pickle variants (.pkl/.pickle/.joblib/.dill) 26,696 (4.1%), together more than 55% of models use Pickle-based serialization; Keras (.keras/.h5/.pb) 17,739 (2.7%), TensorFlow (.pb/.tflite/.ckpt) 16,395 (2.49%).
    • Authors' interpretation: The authors believe Pickle-based serialization is widely used, raising security concerns and highlighting the need for security measures for various serialization methods.

    Unsafe API Filtering Results

    • What was measured: Statistics on occurrences of suspicious APIs in model files and dataset loading scripts (Table 5).
    • Results: In model files, __builtin__.exec appeared 27 times, __builtin__.eval 23 times, os.system/posix.system 18 times; in loading scripts, __builtin__.compile 56 times, __builtin__.eval 74 times; additionally 72 Keras Lambda layers and 35 unsafe TensorFlow operator instances await further inspection.
    • Exception: getattr accounted for 91.2% of dangerous API usage (3,775 times in models, 456 times in scripts), but after checking its arguments the authors found no actual malicious exploitation instances and believe it is basically used for legitimate programming purposes in these contexts.

    Case Studies

    • Case#1 Remote control: Malicious code in the PyTorch model repository "baller10" establishes a reverse shell when the model is loaded, executing different commands depending on the operating system; the authors state its payload is similar to the previously disclosed "baller423/goober2" by JFrog, and that the reverse shells of 10 malicious models in "star23" point to different geographic locations such as Sri Lanka, Germany, and Poland, which the authors believe may indicate attackers using proxy servers to hide their real locations.
    • Case#2 Chrome credential theft: The dataset loading script of the "Besthpz/best" repository steals Chrome passwords and cookies and sends them to a remote server, packaged as a password-protected ZIP (Figure 6).
    • Case#3 System reconnaissance: The loading script of the "Yash2998db/stan_small" dataset executes a subprocess in its initialization method to collect system information and exfiltrate it to a remote server (Figure 7).

    Other Ablations and Analyses

    • Qualitative comparison with SOTA tools (Table 6): MalHug is at semantic-level granularity and supports datasets, while other tools are all at Unsafe Lib & API granularity and do not support datasets; in terms of model format support, MalHug is the same as ModelScan (Pickle variants + TensorFlow & Keras).
    • The paper does not report MalHug's precision/recall, false positive rate, or quantitative detection comparison with baseline tools.
  5. What are some points that can be further explored?

    In the Discussion section, the authors list four limitations: limited coverage, the API list may not be exhaustive, obfuscation-based countermeasures cannot be ruled out, and the TensorFlow flagging approach may produce false positives.

    Limitations and Future Directions Noted by the Authors

    • Incomplete coverage (§6 Limitations): Due to access restrictions, the analysis could not cover all models and datasets on the platform, and malicious instances may exist that were not detected.
    • List may not be exhaustive (§6 Limitations): Although the collection of unsafe libraries and APIs referenced existing work such as Pysa, it may not exhaust all potential in-the-wild exploitation methods.
    • Obfuscation countermeasures unknown (§6 Limitations): Although no instances of obfuscation techniques used to evade static analysis have yet been encountered in models, the possibility of such anti-analysis methods cannot be ruled out; the authors cite package manager poisoning research as an analogy.
    • TensorFlow flagging approach is coarse (§6 Limitations): TensorFlow models using unsafe operators are only flagged, which may produce false positives; the authors state these limitations highlight the need for continuous improvement of detection methods.
    • Platform-side mitigation (§6 Mitigation): The authors mention that Hugging Face plans to disable automatic execution of dataset loading scripts by default in its next major version, requiring users to explicitly set trust_remote_code=True; Keras has fixed the Lambda layer-related vulnerability in version 2.13.

    Experimental Coverage

    • The analysis targets the Hugging Face instance of Ant Group's mirror: 705,991 model repositories and 176,386 datasets (§5.1); the paper does not report actually running MalHug on other model hubs such as ModelScope.
    • The model formats covered by detection are Pickle variants, Keras (Lambda layers), and TensorFlow (unsafe operators only flagged) (§4.2, Table 6).
    • Malicious behavior classification relies on static analysis plus manual review (§5.2); the paper does not report the number of reviewing researchers, consistency metrics, or misjudgment rate.
    • The comparison with existing tools is qualitative (Table 6); the paper does not report a quantitative comparison of MalHug with Fickling, ModelScan, etc. on the same dataset.
    • The paper does not report MalHug's precision, recall, or false positive rate, nor the time taken to analyze a single model or the full mirror.
  6. Summarize the main content of the paper

    The authors systematically study malicious code poisoning on Hugging Face and build MalHug, detecting 91 malicious models and 9 malicious loading scripts over three months on the Ant Group mirror.

    This is a defense and measurement paper on the supply chain security of pretrained model hubs; the authors state it is the first systematic study of malicious code poisoning attacks against PTM hubs.

    • Problem: Hugging Face hosts over 761K models and 176K datasets; attackers can upload models containing malicious code (pickle deserialization execution) or datasets (loading scripts execute by default); the authors state that existing tools remain at library/API-level detection and lack semantic-level analysis.
    • Method: First conduct threat modeling and classification and root cause analysis of 15 model formats (Table 2), then propose the MalHug pipeline: extracting dataset loading scripts, deserializing model files (pickletools + Fickling + .pyc decompilation), Scalpel-based taint analysis, and YARA-based heuristic pattern matching.
    • Deployment scale: MalHug ran on the Ant Group Hugging Face mirror for over three months, analyzing 705,991 models and 176,386 datasets (179.4 TB).
    • Main findings: Detected 91 malicious models (76 Pickle variants, 15 Keras Lambda layers) and 9 malicious dataset loading scripts, with publication times spanning March 2022 to June 2024, and behavior types including remote control, sensitive information theft, and proof of concept.
    • Ecosystem measurement: Over 55% of models use Pickle-based serialization (PyTorch format accounts for 51.0%, explicit Pickle variants account for 4.1%, Figure 3); getattr accounts for 91.2% of dangerous API usage, but the authors found no actual malicious exploitation after checking the arguments.
    • Authors' conclusion: The authors believe these findings reveal security threats in the PTM supply chain, and that MalHug provides a practical solution tested in an industrial environment; the authors also acknowledge limitations in coverage, completeness of the API list, resistance to obfuscation, and the TensorFlow flagging approach, requiring continuous improvement of detection methods.
Read originalASE 2024