UniversalGraves icon indicating copy to clipboard operation
UniversalGraves copied to clipboard

Possible Duplication Exploit

Open DaVibeCodah opened this issue 6 months ago • 1 comments

This is an automated report generated by Claude Haiku 4.5 requested by Automatic Modrinth Crawler.

The model generated reports are down below.

IMPORTANT - AI's can make mistakes. Always check for mistakes.

TECHNICAL_ANALYSIS_ValidationGuide.md

Technical Analysis & Validation Guide

Universal Graves v3.11.1+26.1.2 - Item Duplication Vulnerability


Overview

This document provides developers with technical details to independently validate the reported vulnerability and implement fixes.


Bytecode Analysis Summary

Class Structure Analysis

1. PositionedItemStack (Record Class)

File: eu/pb4/graves/grave/PositionedItemStack.class
Type: Java Record

Fields:
  - stack: ItemStack
  - slot: int
  - inventoryMask: GraveInventoryMask
  - optionalData: NBT Tag
  - tags: Set<Identifier>

Key Methods:
  - toNbt(HolderLookup$Provider): CompoundTag
  - fromNbt(CompoundTag, HolderLookup$Provider, DataFixer, int, int): PositionedItemStack
  - getStack(): ItemStack

Analysis Finding:

  • Constructor signature does NOT show explicit .copy() call
  • Serialization methods create NBT copies (defensive against persistence)
  • In-memory object during creation may reference original ItemStack

Validation Task:

// Decompile source to verify:
public PositionedItemStack(ItemStack stack, int slot, ...) {
    this.stack = stack.copy(); // <-- SHOULD BE HERE
    // or missing?
}

2. VanillaInventoryMask.addToGrave()

File: eu/pb4/graves/other/VanillaInventoryMask.class

Method Signature:
void addToGrave(ServerPlayer player, GraveInventoryMask$ItemConsumer consumer)

Bytecode Pattern Found:
  1. getInventory() on ServerPlayer
  2. Loop through inventory slots (size = getContainerSize())
  3. For each slot:
     - getItem(slot) → ItemStack
     - Check if empty
     - Call consumer.addItem(stack, slot, tags)

Analysis Finding:

  • Items retrieved via getItem(slot) returns reference to actual inventory item
  • No explicit stack.copy() before passing to consumer
  • Consumer receives original ItemStack references

Validation Task:

// Check if this pattern exists:
for (int slot = 0; slot < inventory.getContainerSize(); slot++) {
    ItemStack item = inventory.getItem(slot);
    if (!item.isEmpty()) {
        consumer.addItem(item, slot, ...); // <-- SHOULD BE item.copy()
    }
}

3. GraveUtils.createGrave() Lambda Functions

File: eu/pb4/graves/other/GraveUtils.class

Lambda Identified:
  - lambda$createGrave$0
  - lambda$createGrave$1

Parameters for lambda$createGrave$0:
  - List (grave list)
  - GraveInventoryMask
  - ItemStack
  - int (slot)
  - NBT Tag
  - Identifier[] (tags)

Bytecode Flow:
  1. Creates PositionedItemStack with parameters
  2. Adds to grave via inventoryMask.addItem()
  3. Stores in position tracking

Analysis Finding:

  • ItemStack passed to lambda is the same reference received from inventory
  • No copy made before storage
  • Referenced stored in Grave object

Validation Task:

Trace the lambda to see:
- Is ItemStack.copy() called before PositionedItemStack creation?
- Does addItem() create copies?

4. LivingEntityMixin Injection Point

File: eu/pb4/graves/mixin/LivingEntityMixin.class

Annotation Analysis:
@Inject(
    method = "dropAllDeathLoot",
    at = @At(value = "INVOKE",
             target = "aLnet/minecraft/world/entity/LivingEntity;dropEquipment(...);",
             shift = BEFORE)
)

Execution Order:
1. dropAllDeathLoot() called
2. [INJECTION POINT - Grave Creation Here]
   └─ replaceWithGrave() executes
3. dropEquipment() continues (vanilla behavior)
4. Inventory items drop as entities (if still present)

Analysis Finding:

  • Grave creation happens BEFORE inventory clearing
  • If items still in inventory after grave creation, dropEquipment() will process them
  • Creates potential for items to exist in both grave and as dropped entities

Critical Window: The time between grave creation and inventory clearing


Independent Validation Steps

Step 1: Decompile the JAR

Tools:

  • CFR (modern, good for records): cfr.jar
  • Procyon: procyon.jar
  • JD-GUI: GUI decompiler
  • JADX: Android/Java decompiler

Command Example:

java -jar cfr.jar graves-3_11_1_26_1_2.jar --outputdir src/

Target Classes to Review:

  1. eu/pb4/graves/grave/PositionedItemStack.java
  2. eu/pb4/graves/other/VanillaInventoryMask.java
  3. eu/pb4/graves/other/GraveUtils.java
  4. eu/pb4/graves/grave/Grave.java

Step 2: Code Review Checklist

For PositionedItemStack:

☐ Constructor calls stack.copy()?
☐ Stack field is final and immutable?
☐ No method allows modifying stored stack?
☐ toNbt() creates new NBT (verified)?
☐ fromNbt() creates new ItemStack (verified)?

For VanillaInventoryMask.addToGrave():

☐ Each item retrieved from inventory is copied?
☐ Consumer receives copies, not originals?
☐ After consumer.addItem(), inventory slot set to EMPTY?
☐ Order: copy → store → clear is maintained?

For GraveUtils.createGrave():

☐ Items are copied before grave storage?
☐ Grave creation is atomic (all or nothing)?
☐ Exception handling prevents partial updates?
☐ Inventory is cleared after grave creation?
☐ No async/delayed clearing operations?

For LivingEntityMixin:

☐ Grave creation completes before dropEquipment()?
☐ Inventory is modified synchronously?
☐ No race conditions with other handlers?
☐ Player death is atomic operation?

Step 3: Unit Test Creation

Test Class Template:

@Test
public void testItemStackNotAliasedInGrave() {
    // Setup
    ServerPlayer player = createTestPlayer();
    ItemStack originalStack = new ItemStack(Items.DIAMOND, 64);
    player.getInventory().setItem(0, originalStack);
    
    // Action
    GraveUtils.createGrave(player, world, damageSource);
    
    // Assertion - Verify different object instances
    Grave grave = GraveManager.getLatestGrave(player.getUUID());
    List<PositionedItemStack> graveItems = grave.getItems();
    
    ItemStack graveStack = graveItems.get(0).stack();
    
    // CRITICAL TEST:
    assertNotSame(
        originalStack, 
        graveStack,
        "ItemStack objects should be different instances!"
    );
    
    // Verify inventory is cleared
    assertThat(player.getInventory().getItem(0))
        .isEqualTo(ItemStack.EMPTY);
}

Test Matrix:

  • Single item in slot
  • Full inventory
  • Enchanted items (with NBT)
  • Specific item types (tools, food, blocks)
  • With/without keep-inventory gamerule

Step 4: Integration Testing

Scenario 1: Basic Death & Grave

1. Player joins, gets diamond stack
2. Player takes damage and dies
3. Verify: Diamond in grave, not in inventory
4. Pick up grave
5. Verify: Exactly same number of diamonds, no duplication

Scenario 2: Rapid Death Sequence

1. Player dies
2. Grave created
3. Before grave block fully initializes, player dies again
4. Verify: Items in first grave only, no duplication
5. No item loss

Scenario 3: With Keep-Inventory

1. Set gamerule keepInventory true
2. Player dies
3. Verify: Items in BOTH inventory AND grave (expected with rule)
4. Or: Items ONLY in inventory (depends on config)
5. Check: Does mod respect this gamerule?

Step 5: Memory Analysis

Using Java Debugger:

// In breakpoint within grave creation:
ItemStack inventoryItem = inventory.getItem(0);
ItemStack graveItem = grave.getItems().get(0).stack();

// Check object identity
System.out.println(
    "Same object? " + 
    (inventoryItem == graveItem) // Should be FALSE
);

System.out.println(
    "Inventory: " + System.identityHashCode(inventoryItem)
);

System.out.println(
    "Grave: " + System.identityHashCode(graveItem)
);

Fix Implementation Guide

Fix Option A: Copy in PositionedItemStack Constructor (Recommended)

File: PositionedItemStack.java

// BEFORE (vulnerable)
public PositionedItemStack(
    ItemStack stack,
    int slot,
    GraveInventoryMask inventoryMask,
    @Nullable NBT optionalData,
    Set<Identifier> tags
) {
    this.stack = stack;
    this.slot = slot;
    // ...
}

// AFTER (fixed)
public PositionedItemStack(
    ItemStack stack,
    int slot,
    GraveInventoryMask inventoryMask,
    @Nullable NBT optionalData,
    Set<Identifier> tags
) {
    this.stack = stack.copy(); // <-- Add defensive copy
    this.slot = slot;
    // ...
}

Rationale:

  • Defensive copy at point of storage
  • Ensures grave always has independent ItemStack
  • Simple, maintainable, single point of change

Fix Option B: Copy in VanillaInventoryMask

File: VanillaInventoryMask.java

// BEFORE
for (int slot = 0; slot < inventory.getContainerSize(); slot++) {
    ItemStack item = inventory.getItem(slot);
    if (!item.isEmpty()) {
        consumer.addItem(item, slot, ...);
    }
}

// AFTER
for (int slot = 0; slot < inventory.getContainerSize(); slot++) {
    ItemStack item = inventory.getItem(slot);
    if (!item.isEmpty()) {
        consumer.addItem(item.copy(), slot, ...); // <-- Add copy here
    }
}

Rationale:

  • Copies at collection point
  • Ensures all masks get copies
  • Works if multiple inventory masks used

Fix Option C: Verify Inventory Clearing (Additional)

File: GraveUtils.java

// After grave creation, verify clearing:
private static void clearPlayerInventoryAfterGrave(ServerPlayer player) {
    Inventory inventory = player.getInventory();
    
    for (int slot = 0; slot < inventory.getContainerSize(); slot++) {
        ItemStack item = inventory.getItem(slot);
        if (!item.isEmpty()) {
            // Log suspicious items not removed
            LOGGER.warn(
                "Item still in inventory after grave creation: {} at slot {}",
                item, slot
            );
            inventory.setItem(slot, ItemStack.EMPTY);
        }
    }
}

// Call after creating grave
createGrave(...);
clearPlayerInventoryAfterGrave(player);

Verification Checklist After Fixes

  • [ ] All unit tests pass
  • [ ] Integration tests pass
  • [ ] No item duplication in any scenario
  • [ ] No item loss in any scenario
  • [ ] Grave recovery still works
  • [ ] Compatibility with keep-inventory maintained
  • [ ] Performance not impacted (copy() is low-cost)
  • [ ] No memory leaks from holding references
  • [ ] Plugin compatibility verified

Risk Assessment

Risk Likelihood Consequence Mitigation
Fix breaks grave restoration Low Graves unrecoverable Test restoration paths
Performance degradation Very Low Server lag Profile before/after
Incompatibility with plugins Low Plugin conflicts Test common plugins
Item loss on update Low Player data loss Backup before update

Timeline Recommendation

  1. Days 1-2: Code review & independent validation
  2. Days 3-5: Write and run unit/integration tests
  3. Days 6-10: Implement fix option(s)
  4. Days 11-14: Comprehensive testing & QA
  5. Day 15: Release patch version with fix
  6. Day 30+: Public disclosure if vulnerability confirmed

Additional Resources

Minecraft ItemStack Documentation

  • ItemStack.copy() creates independent copy
  • Original ItemStack remains unaffected
  • NBT data is copied (deep copy)
  • Stack size preserved
  • Enchantments preserved

Java Object Identity

  • == checks object identity (memory address)
  • .equals() checks value equality
  • Use System.identityHashCode() to verify
  • Tools: Java Flight Recorder, JProfiler

Mixin Documentation

  • @At(value = "INVOKE", shift = BEFORE) - before method call
  • CallbackInfo.cancel() - prevent method execution
  • Multiple injections execute in definition order
  • Target method signature must match exactly

Questions for Maintainer

  1. Is PositionedItemStack currently a record or traditional class?

    • Answer determines how copy is implemented
  2. Are there multiple GraveInventoryMask implementations?

    • Each may need fixes independently
  3. Is grave creation synchronous or asynchronous?

    • Async would create race conditions
  4. How are items cleared from inventory currently?

    • Explicit setItem(EMPTY) or automatic?
  5. Are there other systems (plugins/fabric mods) that could affect inventory during grave creation?

    • Could cause race conditions even if code is correct

VULNERABILITY_REPORT_UniversalGraves.md

Security Vulnerability Report: Universal Graves

Mod: Universal Graves
Version: 3.11.1+26.1.2
Report Date: June 1, 2026
Severity: Medium
Report Type: Item Duplication Vulnerability


Executive Summary

A potential item duplication vulnerability has been identified in Universal Graves v3.11.1+26.1.2 related to how items are transferred from player inventory to grave storage during player death events. The vulnerability stems from potential reference aliasing issues in the item collection and storage flow, where ItemStack objects may not be properly copied before being stored in grave structures.


Vulnerability Details

Classification

  • Type: Item Duplication / Reference Aliasing
  • CWE: CWE-374 (Passing Mutable Objects to an Untrusted Method)
  • Impact: Players could potentially duplicate items by exploiting the grave creation process
  • Affected Component: Item transfer system during grave creation

Technical Description

The vulnerability exists in the interaction between three main components:

1. Grave Creation Flow (eu.pb4.graves.other.GraveUtils.createGrave())

The method intercepts player death events and:

  • Collects items from player inventory via GraveInventoryMask.addToGrave()
  • Stores them in a new Grave object via Grave.addTaggedItem()
  • Attempts to clear player inventory

2. Item Collection in VanillaInventoryMask

The VanillaInventoryMask.addToGrave() method:

Iterates through all inventory slots
Collects ItemStack references via PositionedItemStack constructor
Passes items to grave storage consumer

Concern: The method collects item references from the inventory without confirming whether these are references to the original objects or defensive copies.

3. Item Storage in PositionedItemStack

The PositionedItemStack record class stores:

  • stack: The ItemStack object
  • slot: Inventory slot number
  • inventoryMask: Reference to the inventory
  • optionalData: NBT data
  • tags: Identifier tags

Concern: While serialization via toNbt() creates NBT copies, the in-memory object during grave creation may still hold references to the original ItemStack.

4. Death Event Mixin (eu.pb4.graves.mixin.LivingEntityMixin)

The mixin injects BEFORE dropEquipment() is called:

@Inject(
    method = "dropAllDeathLoot",
    at = @At(value = "INVOKE", 
             target = "aLnet/minecraft/world/entity/LivingEntity;dropEquipment(Lnet/minecraft/server/level/ServerLevel;)V",
             shift = BEFORE)
)

Critical Point: The injection happens BEFORE vanilla drop logic, meaning grave creation is the first handler. If items aren't properly removed from inventory, subsequent handlers could process the same items.


Vulnerable Code Paths

Primary Concern: Item Reference Handling

File: eu/pb4/graves/grave/PositionedItemStack.class

  • Constructor accepts ItemStack stack parameter
  • No explicit .copy() call visible in constructor signature analysis
  • Items are later serialized via toNbt() but in-memory references during creation may not be isolated

File: eu/pb4/graves/other/VanillaInventoryMask.class

  • addToGrave() method collects items from inventory
  • Items passed to ItemConsumer without defensive copying verification
  • Uses getItem(slot) to retrieve ItemStack objects

File: eu/pb4/graves/other/GraveUtils.class

  • Lambda function lambda$createGrave$0 processes items
  • Calls addItem() on GraveInventoryMask consumer
  • No visible explicit .copy() call in lambda bytecode analysis

Secondary Concern: Inventory Clearing

File: eu/pb4/graves/mixin/VanillaInventoryMask.class

  • After items are added to grave via addToGrave(), items should be cleared from slots
  • Bytecode analysis shows setItem() calls but unclear if inventory slots are explicitly set to ItemStack.EMPTY

Attack Scenario (Theoretical)

Assuming the vulnerability exists as analyzed:

  1. Player Setup: Player carries items in inventory or equipment
  2. Player Death: Player dies, triggering LivingEntity.dropAllDeathLoot()
  3. Grave Creation: Mixin intercepts, calls GraveUtils.createGrave()
  4. Item Collection: Items are collected into grave storage via PositionedItemStack
  5. Race Condition Window: If items aren't immediately cleared from inventory AND
  6. Inventory Access: Another system/plugin accesses or modifies inventory during grave creation
  7. Result: Items could exist in both grave storage and player inventory simultaneously

Conditions Required:

  • Items are referenced (not copied) during grave creation
  • Inventory clearing happens asynchronously or with delay
  • Another system accesses player inventory during the window

Affected Versions

  • Confirmed Vulnerable: v3.11.1+26.1.2
  • Potentially Affected: All versions using this grave creation mechanism

Proof of Concept Requirements

To validate this vulnerability, the following should be tested:

  1. Unit Test: Create a test that:

    • Creates a player with items in inventory
    • Triggers grave creation
    • Verifies that ItemStack objects in grave are different object instances than inventory items
    • Confirms inventory slots are set to EMPTY
  2. Integration Test:

    • Set up a player with specific items
    • Trigger death event
    • Immediately check grave contents and inventory contents
    • Verify total item count matches (no duplication)
  3. Memory Analysis:

    • Use a Java debugger to trace ItemStack object identity (memory addresses)
    • Confirm whether grave stores copies or references to original objects

Remediation Recommendations

Immediate Fix (High Priority)

In PositionedItemStack constructor or in item collection process:

// CURRENT (potentially vulnerable):
PositionedItemStack(ItemStack stack, int slot, ...)

// SHOULD BE:
PositionedItemStack(ItemStack stack, int slot, ...) {
    this.stack = stack.copy(); // Ensure defensive copy
    // ... rest of initialization
}

Additional Hardening

  1. Verify Inventory Clearing: Ensure that after items are added to grave:

    inventory.setItem(slot, ItemStack.EMPTY); // Explicitly clear
    
  2. Transaction-like Semantics:

    • Collect all items first
    • Verify all items copied successfully
    • Only then remove from inventory
    • Handle rollback if any step fails
  3. Event Validation:

    • Fire event AFTER grave creation completes
    • Allow event listeners to cancel if needed
    • Prevent inventory modifications during grave creation via flag
  4. Add Assertions:

    ItemStack original = inventory.getItem(slot);
    ItemStack stored = graveStack;
    assert original != stored : "Item reference aliasing detected!";
    

Testing Recommendations

  1. Automated Tests:

    • Unit tests for PositionedItemStack object identity
    • Integration tests for full grave creation cycle
    • Edge case tests (full inventory, mixed item types, enchanted items, NBT data)
  2. Manual Testing:

    • Reproduce with large inventory stacks
    • Test with mods that interact with inventory
    • Test with keep-inventory game rule enabled/disabled
  3. Regression Tests:

    • Ensure fixes don't break legitimate grave functionality
    • Test grave recovery, item removal, grave deletion

Impact Assessment

Category Rating Details
Exploitability Medium Requires specific conditions; may require mod interaction
Impact High Item duplication affects server economy and gameplay
Affected Users High All players using graves on affected servers
Severity Medium Requires fix but not critical system failure

CVSS v3.1 Score

CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N = 6.5 (Medium)

  • Attack Vector: Network (players on server)
  • Attack Complexity: Low (if vulnerability exists)
  • Privileges Required: Low (any player can die)
  • User Interaction: Required (must deliberately trigger death)
  • Scope: Unchanged
  • Confidentiality: None
  • Integrity: High (item duplication)
  • Availability: None

References

  • CWE-374: Passing Mutable Objects to an Untrusted Method https://cwe.mitre.org/data/definitions/374.html

  • Java Object Cloning Best Practices https://docs.oracle.com/javase/tutorial/i18n/resbundle/propfile.html

  • Minecraft ItemStack Implementation Minecraft source code for ItemStack.copy() semantics


DaVibeCodah avatar May 31 '26 21:05 DaVibeCodah

This is just a bunch of ai bullshit that doesn't even read code correctly

Patbox avatar May 31 '26 21:05 Patbox