Skip to content
Access control Audit finding Advanced

Incorrect labelhash resolution in Portal leads to deletion of other unintended ENS subnames, and resolving hijacking of unintended

The Portal app builds the argument for deleting a subname by passing the displayed label to viem's labelhash, which decodes a bracketed 64-hex string instead of hashing it. An attacker with the registrar role can register a subname whose label is the bracketed labelhash of a real name the operator owns, so when the operator deletes the junk row the app unregisters the real subname instead.

deltabear Follow

Originally disclosed on Immunefi

Critical View original
  • Disclosed after under an hour

92411 w a critical incorrect labelhash resolution in portal leads to deletion of other unintended ens subnames and resolving hijacking of unintended

Submitted on Sep 9th 2026 at 14:54:08 UTC by @deltabear for Audit Competition | ENS

  • Report ID: #92411
  • Report Type: Websites & Apps
  • Report severity: Critical
  • Target: https://github.com/immunefi-team/audit-comp-ens/tree/audit-comp-ready/apps/portal
  • Impacts:
    • Malicious interactions with an already-connected wallet, such as: Modifying transaction arguments or parameters Substituting contract addresses Submitting malicious transactions Signing or submitting a transaction against the wrong chain (for example when the request's target chain is not validated) Inducing a blanket token approval (for example setApprovalForAll on the registry or NameWrapper) to an attacker-controlled address

Description

Brief/Intro

The Explorer's Subnames tab builds the delete transaction's argument from the row's label with viem's labelhash(), which decodes a [<64 hex>] string instead of hashing it. An attacker with ROLE_REGISTRAR registers one subname named [<labelhash of a real label the operator owns>] like vault.victim.eth. It renders as meaningless spam. When the operator deletes the junk row, the app signs unregister(labelhash("vault")) and destroys the real vault subname instead, while the junk row stays untouched and undeleted.

The same label-to-resource-id derivation feeds two further write paths in the same app. Those are under Additional risk from the same root cause below, so the fix can be scoped to all three at once. They are supplied for completeness.

Vulnerability Details

apps/portal/src/routes/$name/subnames.tsx:177-186 extracts the label shown on screen with a local getLabel, plain string slicing with no normalization step:

TS
const getLabel = useCallback((subname: string) => {
  const suffix = `.${name}`
  if (subname.endsWith(suffix)) return subname.slice(0, -suffix.length)
  return subname.split('.')[0]
}, [name])

runDelete passes that label straight through useDeleteSubname into deleteSubname (apps/portal/src/features/registry/helpers/deleteSubname.ts:50-55) and prepareDeleteSubnameTransaction (apps/portal/src/features/registry/utils/delete-subname.helpers.ts:33-39), which hands it to ENSJS unmodified:

TS
const writeParams = deleteSubnameWriteParameters(
  walletClient as Parameters<typeof deleteSubnameWriteParameters>[0],
  { registryAddress, label },
)

ENSJS computes the on-chain argument with BigInt(labelhash(label)) (@ensdomains/ensjs@e96662c dist/actions/wallet/v2/deleteSubname.js:13). viem's labelhash ([email protected] utils/ens/labelhash.js:14-19) tries encodedLabelToLabelhash() first, which reads the 64 hex characters between [ and ] straight out, and only falls back to keccak256 when that parse fails. The chain hashes the literal label string it receives at registration. A label written as [23c14fceac7676b670aa56866076586ea1ce15ddcf19208ec6346cf748dffbee] therefore has two identities: keccak256 of the literal 66 character string on chain, and labelhash("vault") in the client, because that hex is labelhash("vault").

No guard catches this, because nothing on the delete path ever checks the row's own resource. The Delete button renders on hasUnregisterRole (subnames.tsx:105-114), which is queried with label: '':

TS
const { data: hasUnregisterRole } = useQuery({
  ...getHasRolesQueryOptions({
    registryAddress: subregistryAddress as Address,
    label: '',
    roles: ['ROLE_UNREGISTER'],
    account: connectedAccount as Address,
  }),

Vulnerable source code

1. The label shown on screen, extracted with no normalization @ apps/portal/src/routes/$name/subnames.tsx:177-186

TS
const getLabel = useCallback((subname: string) => {
  const suffix = `.${name}`
  if (subname.endsWith(suffix)) return subname.slice(0, -suffix.length)
  return subname.split('.')[0]
}, [name])

2. The label reaches ENSJS unmodified @ apps/portal/src/features/registry/utils/delete-subname.helpers.ts:33-39

TS
const writeParams = deleteSubnameWriteParameters(
  walletClient as Parameters<typeof deleteSubnameWriteParameters>[0],
  { registryAddress, label },
)

3. ENSJS builds the argument by decoding, not hashing @ @ensdomains/ensjs@e96662c dist/actions/wallet/v2/deleteSubname.js:7-13

JavaScript
export const deleteSubnameWriteParameters = (client, { registryAddress, label }) => {
  return {
    address: registryAddress,
    abi: permissionedRegistryUnregisterSnippet,
    functionName: 'unregister',
    args: [BigInt(labelhash(label))],
  };
};

4. viem tries the bracket decode before it ever hashes @ [email protected] utils/ens/labelhash.js:14-19

JavaScript
export function labelhash(label) {
  const result = new Uint8Array(32).fill(0);
  if (!label) return bytesToHex(result);
  return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label));
}

5. The Delete button's gate never looks at the row — it reads the root resource once, for every row @ apps/portal/src/routes/$name/subnames.tsx:105-114,370,377

TS
const { data: hasUnregisterRole } = useQuery({
  ...getHasRolesQueryOptions({
    registryAddress: subregistryAddress as Address,
    label: '',
    roles: ['ROLE_UNREGISTER'],
    account: connectedAccount as Address,
  }),
})
...
const canDeleteSubname = Boolean(hasUnregisterRole)

6. The root grant list has six entries, and delete is not one of them @ apps/portal/src/lib/roles/permissions.ts:71-108

TS
export const registryRootPermissions: readonly RegistryRootPermission[] = [
  { key: 'ROLE_SET_SUBREGISTRY', ... },
  { key: 'ROLE_SET_RESOLVER', ... },
  { key: 'ROLE_RENEW', ... },
  { key: 'ROLE_REGISTRAR', ... },
  { key: 'ROLE_REGISTER_RESERVED', ... },
  { key: 'ROLE_SET_PARENT', ... },
] as const

7. Registrar and Unregister are separate bits @ @ensdomains/ensjs@e96662c dist/utils/v2/roles/registryRoles.js:2,11

JavaScript
const ROLE_REGISTRAR = 1n << 0n;
const ROLE_UNREGISTER = 1n << 12n;

Impact Details

An attacker can cause "Malicious interactions with an already-connected wallet, such as: Modifying transaction arguments or parameters", which is exactly the scoped impact, nowhere does the scope requires the attacker to be permissionless and from immunefi's rules on privilaged attackers: "Another exception may apply whereby impacts listed on the Impacts in Scope table can occur due to a logic error exploitable by a privileged address. Logic errors are considered valid bug reports." Here, a lower-level permissioned actor can take advantage of a logical error in the code to achieve the scoped impact exactly. Moreover, ENS registrant role isn't an admin, and can be taken advantage of, and has extremely high exploitability by bombing the name with junk subnames, and a single bulk delete will delete all real names without warning.

  • When an admin deletes a junk subname, instead, the real name will be deleted and the junk remains. Example in the screenshots.
  • Setting the resolver on a gifted subname redirects the resolver of the victim's real subname to an attacker-controlled address. tested end-to-end with screenshots
  • Configuring the subregistry on a gift ed subname modifies the subregistry of the victim's real subname, orphaning all of its child subnames. tested end-to-end

Additional risk from the same root cause

The defect above is not specific to deleting a subname. It is in how the app turns a displayed label into an on-chain resource id, and every write path that does so inherits it, including the role gate that is supposed to catch it. We reproduced two further paths against the same production build, each with its own mined transaction, and include them here so the fix is scoped to all three rather than to the Subnames tab alone.

We are not claiming a separate impact row for either. Both are reached from the page of a name the attacker gifted the victim, which is a materially weaker entry point than the Subnames tab: the victim has no pre-existing task that takes them there. They are supplied as blast radius, and as evidence that this bug does not depend on the registrar delegation at all.

(a) setResolver — an attacker holding zero roles retargets the resolver of a real name

Full bundle in extra-change-resolver/. Commit 1c9b47f, anvil fork of Sepolia, production Portal build on wrangler dev, the repo's own @ensdomains/headless-web3-provider e2e fixture, and no indexer mock anywhere in this flow.

The attacker registers an ordinary 2LD whose label is the literal 66-character string "[" + hex(labelhash(V)) + "]", where V is a real name the victim owns — an ordinary paid registration, 8.000021 USDC, no permission of any kind. They push it to the victim with safeTransferFrom (tx 0x1e3b4fc5a730cca47e5e65126aa60077e081f1fbbadb4b1d450c44f3855e710b), which needs no consent and no victim transaction.

changeResolver.ts:70-77 takes the label off the raw route string and builds the write argument with ENSJS's labelToCanonicalId, which is hexToBigInt(labelhash(label)) with the low 32 bits masked — the same viem decode. The role gate is the same function as in the delete path (hasRoles.js, BigInt(labelhash(params.label))), so it passes rather than blocking, and the app renders its own unprompted call to action on the gift's Resolver tab:

"This name does not have a resolver set." [Set resolver]

(extra-change-resolver/evidence/screenshots/03-bracket-resolver-no-resolver-set.png.) The victim clicks it, types an address, signs:

  • tx 0xd1d051f2dd2c4fae2dc7d4ad26a4c0a08bbec0810c8b93578a1d472f625827f3, block 11667082, to the shared .eth registry 0xBDC85dD5b15D7ecb354cd7cb6f2c50b4f2c4F0E2
  • calldata 0xbc7b6d62 + 1ec8b341…0000000 + the typed address; arg0 == canonicalId(V) byte for byte, not the gift's own identity (keccak256 of the bracket string, 0x588862c6…d0a4)
  • V's resolver moves 0x23f45D32…14c2 -> 0x82c6f4E3…Bb50; the gift's own resolver stays 0x0, never touched
  • the victim's real name's own Resolver tab then displays the wrong resolver under the correct label and namehash (extra-change-resolver/evidence/screenshots/06-v-resolver-after-attack.png)

Controls: the ordinary Change-resolver flow on an unrelated name of the victim's touches only that name (positive control); the attacker's own direct setResolver(canonicalId(V), attacker) reverts (negative control). Recovery is one ordinary transaction and the records survive, because setResolver moves a pointer rather than destroying data — this path is less damaging than the delete above, and is the one that shows the precondition can be nothing at all.

(b) setSubregistry — the same collision on the Registry tab

ConfigureRegistryForm.tsx:89 takes name.split('.')[0] and hands it to ENSJS setSubregistry.js, BigInt(labelhash(label)). Reproduced through the browser on the same stack: tx 0x19da10877ae687966bd14e9e051b7b24f40478c1720996bb2d0b4794c7058092, block 11654500, arg0 = 0x2e5a30f4…ab58cf5e, which the registry canonicalises onto the victim's real r42victimb2.eth rather than the bracket name on screen. The real name's subregistry moved 0x693C1f80…7D26 -> 0xb388b0FB…4E74, orphaning the subnames underneath it, while the bracket name's own subregistry slot stayed 0x0.

References

The delete path

  • apps/portal/src/routes/$name/subnames.tsx:177-186 - getLabel, no normalization
  • apps/portal/src/routes/$name/subnames.tsx:195-214 - runDelete passes getLabel(subname.name) to deleteSubnameAsync
  • apps/portal/src/features/registry/hooks/useDeleteSubname.ts:79-90 - mutation wrapper, calls the pure helper
  • apps/portal/src/features/registry/helpers/deleteSubname.ts:50-55 - calls prepareDeleteSubnameTransaction
  • apps/portal/src/features/registry/utils/delete-subname.helpers.ts:33-39 - calls ENSJS deleteSubnameWriteParameters with the raw label
  • @ensdomains/ensjs@e96662c dist/actions/wallet/v2/deleteSubname.js:7-13 - args: [BigInt(labelhash(label))]
  • [email protected] utils/ens/labelhash.js:14-19 - bracket decode tried before keccak256
  • [email protected] utils/ens/encodedLabelToLabelhash.js:1-14 - the [<64 hex>] parse

The gate that does not catch it

  • apps/portal/src/routes/$name/subnames.tsx:105-114 - hasUnregisterRole is queried with label: '', i.e. the root resource, never the row's own
  • apps/portal/src/routes/$name/subnames.tsx:370,377,388-389 - that single boolean becomes canDelete on every row in the table
  • @ensdomains/ensjs@e96662c dist/actions/public/v2/hasRoles.js:64-70 - BigInt(labelhash(params.label)); with label: '' viem returns 0x00…0, so the check resolves to ROOT_RESOURCE

ENS's documented role model, which this crosses

  • RegistryRolesLib / ENSJS dist/utils/v2/roles/registryRoles.js:1-11 - ROLE_REGISTRAR nybble 0, "authorizes registering and reserving new names. Root only."; ROLE_UNREGISTER nybble 3, "authorizes unregistering names. Root or token."
  • ENS v2 contracts documentation, Registry Roles - ROLE_REGISTRAR is root-only "because the resource (name) doesn't exist yet at registration time", with the ETH Registrar Controller as its worked example of a holder; ROLE_UNREGISTER is root-or-token with a "moderator" or "operator" as its worked examples
  • https://x.com/ensdomains/status/2093319579321999673
  • https://ens.domains/blog/post/ensv2-architecture

The role boundary

  • apps/portal/src/lib/roles/permissions.ts:71-108 - registryRootPermissions, six entries, no ROLE_UNREGISTER
  • apps/portal/src/features/registry/components/v2/RegistryAddUserSheet.tsx:122-130 - the real "Add User" grant call
  • apps/portal/src/features/registry/helpers/grantRegistryRoles.ts:45,62-70 - resource: ROOT_RESOURCE, no allowlist
  • @ensdomains/ensjs@e96662c dist/utils/v2/roles/registryRoles.js:2,11 - ROLE_REGISTRAR = 1<<0, ROLE_UNREGISTER = 1<<12

Source for the two additional write paths

  • apps/portal/src/features/resolver/helpers/changeResolver.ts:70-77 - name.split('.')[0] -> labelToCanonicalId
  • @ensdomains/ensjs dist/utils/v2/registry/labelToCanonicalId.js:3-7 - hexToBigInt(labelhash(label)), low 32 bits masked
  • apps/portal/src/features/registry/components/v2/ConfigureRegistryForm.tsx:89 - name.split('.')[0] -> ENSJS setSubregistry
  • apps/portal/src/utils/token/getLabel.ts:10-19 - the normalizing accessor that already exists and throws on [, which none of the three write paths call

Proof of Concept

Proof of Concept

impact: When an admin deletes a junk subname, instead, the real name will be deleted and the junk remains. Example in the screenshots.

shows prrof after running end-to-end.

screenshots explanations:

6 - showing all names 7 - showing deleting a real name 8 - showing deleting the junk name: it seems like the junk name is deleted and the real name remains but its not true at all 9 - after a refresh you can see the real is adctually the deleted one, and the junk name remains undeleted results: the vault name is deleted.

Loads the repo's own permissions.ts and the pinned ENSJS write-parameter builders unmodified, replays the exact grant and delete calldata against a compiled model of the registry's role gate, and checks the delete calldata byte for byte against the real mined transaction above.

Bash
node poc.mjs

poc.mjs

JavaScript
#!/usr/bin/env node
//
// ENS PoC: apps/portal's Subnames-tab Delete action builds its on-chain
// argument with viem's labelhash(), which DECODES a "[<64 hex>]" label
// instead of hashing it. A subname named "[<labelhash of "vault">]" looks
// like meaningless spam on screen, but clicking Delete on it sends
// unregister(labelhash("vault")) and destroys a different, real subname the
// operator owns.
//
//   node poc.mjs                 (ENS_REPO defaults to ../../../ens-apps)
//
// Self-contained. On first run it writes its helpers to a temp dir, installs
// pinned deps there, and re-execs itself. No wallet, no RPC, no fork needed
// to run this script.
//
// LAYER A is the repo's OWN role list (apps/portal/src/lib/roles/permissions.ts)
// and the ENSJS write-parameter builders the app calls to build both the
// grant transaction and the delete transaction
// (@ensdomains/ensjs/wallet/v2, pinned to the exact commit this repo's
// pnpm-workspace.yaml catalog names, e96662c), loaded and run unmodified.
// Nothing here reimplements labelhash or the write-parameter builders.
//
// LAYER B is a compiled Solidity model of the v2 registry's role gate and
// register/unregister state transitions (the real contracts are audited
// separately and out of scope). Every constant it uses (role bit positions,
// the ROLES_ALL bitmap a registry deployer receives) is read from this
// repo's own source, cited at each use.
//
// CORROBORATION: this exact mechanism was already run once through the real
// rendered Portal (production build, apps/portal/dist, on wrangler dev) on
// an anvil fork of live Sepolia, with a real injected-wallet click on the
// real Delete button. Mined tx
// 0xdf82d27a6bb86c80b146c767fa2aee0286f361862f8708de3249a62d0a7601aa, block
// 11665247, calldata
// 0xa02b161e23c14fceac7676b670aa56866076586ea1ce15ddcf19208ec6346cf748dffbee.
// Full detail: evidence/FORENSICS.txt, evidence/screenshots/06 through 09,
// RESULTS.md. ACT 8 below recomputes that same calldata from the real
// ENSJS write-parameter builder and checks it byte for byte.

import { spawnSync } from 'node:child_process'
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = process.env.ENS_REPO ?? path.resolve(HERE, '../../../ens-apps')
const WORK = process.env.POC_WORKDIR ?? path.join(os.tmpdir(), 'ens-poc-subname-delete-decode')

// ---------------------------------------------------------------- cast
// The real anvil default-mnemonic accounts used in the browser-driven run
// this PoC corroborates (evidence/FORENSICS.txt).
const VICTIM = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266'
const ATTACKER = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'
const VICTIM_RESOLVER = '0x0671d0CAA4d0641193b43081FDff1dBab2f7C9b9'

// ============================================================== generated files

const PKG = `{
  "name": "ens-poc-subname-delete-decode",
  "private": true,
  "type": "module",
  "dependencies": {
    "@ensdomains/ensjs": "https://pkg.pr.new/ensdomains/ensjs/@ensdomains/ensjs@e96662c",
    "@ensdomains/ensjs-abi": "https://pkg.pr.new/ensdomains/ensjs/@ensdomains/ensjs-abi@e96662c",
    "@ethereumjs/common": "^4.4.0",
    "@ethereumjs/evm": "^3.1.0",
    "@ethereumjs/statemanager": "^2.4.0",
    "@ethereumjs/util": "^9.1.0",
    "solc": "0.8.28",
    "viem": "2.52.2"
  },
  "devDependencies": { "tsx": "^4.19.2" }
}
`

// Lets the repo's own source run unmodified against these pinned deps,
// without installing the pnpm monorepo and without editing a line of target.
const LOADER = `import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'

const HERE = path.dirname(fileURLToPath(import.meta.url))
const ANCHOR = pathToFileURL(path.join(HERE, 'poc.mjs')).href
const REPO = process.env.ENS_REPO

const isBare = (s) => !s.startsWith('.') && !s.startsWith('/') && !s.includes(':')

// path.relative is WRONG across drives on Windows (G: vs C:); it returns an
// absolute path, which would make every node_modules file count as a repo file.
const REPO_PREFIX = path.resolve(REPO).toLowerCase() + path.sep
const isRepoFile = (parentURL) => {
  if (!parentURL || !parentURL.startsWith('file:')) return false
  try {
    return path.resolve(fileURLToPath(parentURL)).toLowerCase().startsWith(REPO_PREFIX)
  } catch { return false }
}

export async function resolve(specifier, context, nextResolve) {
  if (specifier.startsWith('@ens-repo/'))
    return nextResolve(pathToFileURL(path.join(REPO, specifier.slice(10))).href, context)
  // repo files resolve bare imports (viem, @ensdomains/ensjs/utils/v2 types)
  // against THIS PoC's own pinned node_modules, so both sides share one
  // module instance.
  if (isRepoFile(context.parentURL) && isBare(specifier))
    return nextResolve(specifier, { ...context, parentURL: ANCHOR })
  return nextResolve(specifier, context)
}
`

const REGISTER = `import { register } from 'node:module'
register('./_loader.mjs', import.meta.url)
`

// LAYER B. The v2 contracts are audited separately and are not in the
// in-scope repo, so this models only what the impact depends on. Every
// constant is read from this repo's own source, not invented:
//   ROLE_REGISTRAR = 1<<0, ROLE_UNREGISTER = 1<<12, admin = role<<128
//     -> node_modules/.../ensjs/dist/utils/v2/roles/registryRoles.js:2,11
//   a registry deployer holds every role at ROOT (the 0x1111...1 bitmap)
//     -> apps/portal/src/features/registry/utils/create-subname.helpers.ts:21-23
//   unregister requires ROLE_UNREGISTER on the resource or on ROOT, clears
//   owner and resolver, and leaves the subregistry and deeper subnames
//   untouched -> ensjs dist/actions/wallet/v2/deleteSubname.js docblock
const SOL = `// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract PermissionedRegistryModel {
    uint256 constant ROLE_REGISTRAR = 1 << 0;
    uint256 constant ROLE_UNREGISTER = 1 << 12;
    uint256 constant ADMIN_SHIFT = 128;

    // resource => account => bitmap. resource 0 is ROOT_RESOURCE; a ROOT role
    // authorizes the holder on every resource (EnhancedAccessControl's root
    // fallback), mirrored below.
    mapping(uint256 => mapping(address => uint256)) public roleBits;
    mapping(uint256 => address) public ownerOf;
    mapping(uint256 => address) public resolverOf;

    error Unauthorized(uint256 resource, address caller, uint256 needed);

    /// The registry deployer gets ROLES_ALL at ROOT, same as
    /// create-subname.helpers.ts's DEFAULT_ROLE_BITMAP / deploySubregistryWriteParameters.
    constructor(address deployer) {
        roleBits[0][deployer] = type(uint256).max;
    }

    function hasRoles(uint256 resource, uint256 roles, address account) public view returns (bool) {
        if (roleBits[0][account] & roles == roles) return true;
        return roleBits[resource][account] & roles == roles;
    }

    /// registryRootPermissions' grant entrypoint (RegistryAddUserSheet -> grantRegistryRoles.ts).
    function grantRootRoles(uint256 roleBitmap, address account) external {
        uint256 needed = roleBitmap << ADMIN_SHIFT;
        if (!hasRoles(0, needed, msg.sender)) revert Unauthorized(0, msg.sender, needed);
        roleBits[0][account] |= roleBitmap;
    }

    /// Setup only: seeds a name the victim already owns (e.g. "vault"),
    /// the same on-chain state "Create subname" produces.
    function seedOwned(uint256 resource, address owner_, address resolver_) external {
        ownerOf[resource] = owner_;
        resolverOf[resource] = resolver_;
    }

    /// The only thing ROLE_REGISTRAR authorizes: mint a label nobody holds yet.
    function register(uint256 resource, address owner_) external {
        if (!hasRoles(0, ROLE_REGISTRAR, msg.sender)) revert Unauthorized(0, msg.sender, ROLE_REGISTRAR);
        require(ownerOf[resource] == address(0), "already registered");
        ownerOf[resource] = owner_;
    }

    /// deleteSubname.js's on-chain target. Gated on ROLE_UNREGISTER alone.
    function unregister(uint256 anyId) external {
        if (!hasRoles(anyId, ROLE_UNREGISTER, msg.sender)) revert Unauthorized(anyId, msg.sender, ROLE_UNREGISTER);
        ownerOf[anyId] = address(0);
        resolverOf[anyId] = address(0);
    }
}
`

// ============================================================== bootstrap

if (process.env.ENS_POC_CHILD !== '1') {
  const line = '='.repeat(78)
  console.log(line)
  console.log('  ENS PoC: Subnames-tab Delete decodes a bracket label instead of')
  console.log('           hashing it, and destroys a different, real subname')
  console.log(`  repo:  ${REPO}`)
  console.log(`  build: ${WORK}`)
  console.log(line)

  if (!existsSync(path.join(REPO, 'apps', 'portal'))) {
    console.error(`\nERROR: ENS checkout not found at ${REPO}. Set ENS_REPO.`)
    process.exit(2)
  }

  mkdirSync(WORK, { recursive: true })
  writeFileSync(path.join(WORK, 'package.json'), PKG)
  writeFileSync(path.join(WORK, '_loader.mjs'), LOADER)
  writeFileSync(path.join(WORK, '_register.mjs'), REGISTER)
  writeFileSync(path.join(WORK, 'Model.sol'), SOL)
  copyFileSync(fileURLToPath(import.meta.url), path.join(WORK, 'poc.mjs'))

  if (!existsSync(path.join(WORK, 'node_modules', 'tsx', 'package.json'))) {
    console.log('\nInstalling pinned deps (viem 2.52.2, ensjs @e96662c, solc 0.8.28)...')
    const r = spawnSync('npx', ['--yes', 'pnpm@9', 'install', '--no-frozen-lockfile'],
      { cwd: WORK, stdio: 'inherit', shell: true })
    if (r.status !== 0) process.exit(r.status ?? 1)
  }

  const r = spawnSync(process.execPath,
    ['--import', 'tsx', '--import', './_register.mjs', 'poc.mjs'],
    { cwd: WORK, stdio: 'inherit',
      env: { ...process.env, ENS_POC_CHILD: '1', ENS_REPO: REPO, NODE_NO_WARNINGS: '1' } })
  process.exit(r.status ?? 1)
}

// ============================================================== layer A

const { registryRootPermissions } = await import(
  '@ens-repo/apps/portal/src/lib/roles/permissions.ts')
const { grantRolesWriteParameters, deleteSubnameWriteParameters } = await import(
  '@ensdomains/ensjs/wallet/v2')
const { decodeFunctionData, encodeFunctionData, keccak256, labelhash, stringToBytes } =
  await import('viem')

// A fake wallet client. Both write-parameter builders read only .chain/.account
// off it; neither performs an RPC call.
const client = { chain: { id: 11155111 }, account: { address: VICTIM } }

// ============================================================== EVM

const require_ = createRequire(import.meta.url)
const { Common, Hardfork } = await import('@ethereumjs/common')
const { EVM } = await import('@ethereumjs/evm')
const { DefaultStateManager } = await import('@ethereumjs/statemanager')
const { Account, Address, hexToBytes } = await import('@ethereumjs/util')

const compileModel = () => {
  const solc = require_('solc')
  const out = JSON.parse(solc.compile(JSON.stringify({
    language: 'Solidity',
    sources: { 'Model.sol': { content: readFileSync(path.join(WORK, 'Model.sol'), 'utf8') } },
    settings: { optimizer: { enabled: true, runs: 200 },
                outputSelection: { '*': { '*': ['abi', 'evm.bytecode.object'] } } },
  })))
  const fatal = (out.errors ?? []).filter((e) => e.severity === 'error')
  if (fatal.length) throw new Error(fatal.map((e) => e.formattedMessage).join('\n'))
  const c = out.contracts['Model.sol'].PermissionedRegistryModel
  return { abi: c.abi, bytecode: `0x${c.evm.bytecode.object}` }
}

const GAS = 30_000_000n
const addr = (a) => new Address(hexToBytes(a))

class RevertError extends Error {}

class Chain {
  constructor(evm, sm) { this.evm = evm; this.sm = sm }

  static async create() {
    const sm = new DefaultStateManager()
    return new Chain(await EVM.create({
      common: new Common({ chain: 1, hardfork: Hardfork.Shanghai }), stateManager: sm }), sm)
  }

  async fund(a, wei) {
    const acct = (await this.sm.getAccount(addr(a))) ?? new Account()
    acct.balance = wei
    await this.sm.putAccount(addr(a), acct)
  }

  async deploy(from, bytecode, abi, args = []) {
    const ctor = abi.find((x) => x.type === 'constructor')
    // Constructor args are ABI-encoded and appended raw (no selector) after
    // the bytecode; encodeFunctionData cannot take a constructor entry.
    const encoded = ctor && args.length
      ? bytecode + require_('viem').encodeAbiParameters(ctor.inputs, args).slice(2)
      : bytecode
    const res = await this.evm.runCall(
      { caller: addr(from), origin: addr(from), data: hexToBytes(encoded), gasLimit: GAS })
    if (res.execResult.exceptionError) throw new Error('deploy reverted')
    return res.createdAddress.toString()
  }

  /// Send PRE-ENCODED calldata, used to replay Layer A's real bytes verbatim.
  async raw({ from, to, data, abi, fn }) {
    const res = await this.evm.runCall({ caller: addr(from), origin: addr(from), to: addr(to),
      data: hexToBytes(data), gasLimit: GAS })
    const ex = res.execResult
    const ret = `0x${Buffer.from(ex.returnValue).toString('hex')}`
    if (ex.exceptionError) {
      let reason = `reverted ${ret.slice(0, 10)}`
      try {
        const d = require_('viem').decodeErrorResult({ abi, data: ret })
        reason = `${d.errorName}(${(d.args ?? []).map((a) =>
          typeof a === 'bigint' ? `0x${a.toString(16)}` : String(a)).join(', ')})`
      } catch {}
      throw new RevertError(reason)
    }
    const outs = abi?.find((x) => x.type === 'function' && x.name === fn)?.outputs
    if (!outs?.length) return undefined
    return require_('viem').decodeFunctionResult({ abi, functionName: fn, data: ret })
  }

  async send({ abi, fn, args = [], ...rest }) {
    return this.raw({ ...rest, abi, fn, data: encodeFunctionData({ abi, functionName: fn, args }) })
  }

  async call(opts) { return this.send({ ...opts, from: '0x' + '00'.repeat(19) + '01' }) }
}

// ============================================================== the run

const W = 78
const rule = (ch = '=') => console.log(ch.repeat(W))
const say = (s = '') => console.log(s)
const act = (n, t) => { say(); rule(); say(`  ${n}  ${t}`); rule() }
const kv = (k, 

The original report as published on Immunefi, by deltabear. Images and videos are our own copies; raw HTML is shown as text. View it on Immunefi.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The app derives the on-chain resource id from the displayed label using viem's labelhash, which decodes a bracketed 64-hex label rather than hashing it, and no write path normalises or validates the label first.

Impact

An operator deleting a junk subname could instead destroy a real subname they own, and the same label-to-id flaw also lets an attacker with no roles retarget a victim's resolver or subregistry via a gifted name, though the resolver path only moves a pointer and is recoverable.

What the attacker needed

Attacker holds ROLE_REGISTRAR; operator deletes the junk row; for resolver path: victim clicks Set resolver

The fix

The write paths should derive the resource id from a normalised label accessor that rejects bracketed hex labels, and the delete gate should check roles on the row's own resource rather than the root.

How it was found

  1. An attacker holding the registrar role registers a subname whose label is the bracketed labelhash of a real subname the operator owns.
  2. The junk subname appears in the Subnames tab as meaningless spam.
  3. The operator clicks Delete on the junk row.
  4. The app builds the unregister argument from the decoded labelhash and signs a transaction that targets the real subname.
  5. After a refresh the real subname is gone and the junk row remains.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

Every name on this registry is identified on-chain by a number derived from its text label. Normally that number is a hash of the label, but the library used here also accepts a label written as a bracketed hex string and treats the hex inside as the number directly. So a junk-looking name can carry the identity of a real name, and any action the app takes on the junk name actually hits the real one.

What is Access control?

A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.

More by deltabear

View all

30 more disclosed reports, best first.

More from ENS

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Broken access control

The lesson behind this report.

A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.