01 //Introduction
Reverse tabnabbing is a client-side phishing vector that lets a page opened from your site silently navigate the original tab to an attacker-controlled URL. The carrier is almost always an outbound target="_blank" link, a window.open() call, or a form submission that opens a new tab. The attack is over a decade old, was originally described by Mathias Bynens in 2014, and still ships in fresh reports every quarter because the vulnerable pattern, an anchor with target="_blank" and no rel="noopener", is the most natural way to write the markup.
The bug class sits in a quiet seam of the web platform. Your application is correct, the browser is correct, and the same-origin policy is enforced. The vulnerability lives in the moment a new tab is opened with a back-reference to the opener. The new tab cannot read the opener's DOM (that would be a cross-origin read), but it can assign window.opener.location, which performs a top-level navigation. Once the attacker page swaps the original tab to a pixel-perfect phishing clone of your login screen, the user has no obvious cue that anything has changed. CWE-1022 (Use of Web Link to Untrusted Target with window.opener Access) is the canonical reference.
rel="noopener" for anchors with target="_blank" (since Chrome 88, Firefox 79, Safari 12.1). That fixed the default for fresh HTML, but did not retroactively fix four other paths: window.open() (still needs an explicit noopener in the features string), <form target="_blank"> submissions, server-rendered HTML cached or rendered in older engines, and embedded surfaces (PDFs, SVG, WebViews, email clients, Electron shells) that do not always follow the modern default. Code review still has to enforce noopener everywhere because the implicit default cannot be relied on across every consumer of your markup.OWASP catalogues the issue in its Reverse Tabnabbing page and in the HTML5 Security Cheat Sheet. The defensive recipe is identical across frameworks: every anchor with target="_blank" carries rel="noopener noreferrer", every window.open passes noopener in the features string, every Markdown or rich-text renderer is configured to emit the rel attribute, and the application sets Cross-Origin-Opener-Policy: same-origin as a backstop. This module walks through the attack surface, the canonical payloads, and the per-framework fix that closes the bug class properly.
A page renders <a href="https://partner.tld" target="_blank">Partner</a> without a rel attribute. The partner site is compromised and serves window.opener.location = 'https://login-app.tld/signin'. What does the victim see?
02 //The Attack Flow
Every reverse tabnabbing attack follows the same four-stage flow: the victim clicks an outbound link from your site that opens a new tab, the browser preserves a window.opener reference in the new tab, the attacker page runs a one-line script that assigns window.opener.location to a phishing URL, and the original tab silently navigates to the attacker's clone while the victim is reading the new tab. By the time the victim returns to what they think is your site, it is not your site anymore.
target="_blank" link to an attacker-controlled URLwindow.openerwindow.opener.location = 'https://evil.tld/login'Cross-origin script access is blocked by the same-origin policy, but cross-origin navigation via window.opener.location is allowed. The attacker cannot read your DOM, but they can replace the page the user thinks they came from. By the time the victim flips back, the original tab no longer shows your site, it shows whatever the attacker chose, and the user has no obvious cue that the tab was hijacked.
The shape of a realistic exploit depends on what the new tab's origin is willing to do. Most reverse-tabnabbing reports involve a third-party site that the application links to: a partner page, an outbound advertiser, a user-submitted URL in a comment or profile, a Markdown-rendered link in a forum post. The attacker does not need to compromise your site to weaponise the bug, they only need a page that your users will click through to. That is why user-submitted content with outbound links is the highest-value sink: the attacker controls the destination directly.
Common Sink Surfaces in Real Applications
| Where outbound links live | Typical attacker payload |
|---|---|
| User profile bios, social links | Self-submitted attacker URL that triggers on click |
| Comment / post bodies (Markdown rendered) | Inline link to an attacker page |
| Forum signatures, custom statuses | Long-lived link that targets every visitor of every thread |
| Outbound advertising / affiliate links | Compromised ad network or partner content |
| Help-centre articles linking to vendor docs | Compromised vendor doc page |
| Email templates opened in webmail | Tracking link from a marketing platform |
| Documentation iframes, embedded sandboxes | Third-party docs widget with target=_blank links |
| Single sign-on / OAuth callbacks rendering "Continue to | Compromised IdP page or look-alike |
| File preview viewers that render hyperlinks (PDF, DOCX, SVG) | Crafted document with a malicious annotation link |
[label](https://attacker.tld) compiles to an <a href>. Many renderers add target="_blank" by default for outbound URLs, and many forget to add rel="noopener noreferrer". Almost every reverse-tabnabbing CVE you will read started life in a Markdown renderer, a forum post, or a profile bio.1// VULNERABLE, the link opens a new tab and leaves window.opener
2// populated for the destination origin.
3export function OutboundLink({ href, children }: { href: string; children: React.ReactNode }) {
4 return (
5 // BAD, target="_blank" without rel="noopener noreferrer".
6 // Implicit noopener only applies to <a target="_blank"> in the latest browser
7 // engines. WebViews, Electron shells, older Safari builds, PDF viewers,
8 // and many embedded engines still leak window.opener.
9 <a href={href} target="_blank">
10 {children}
11 </a>
12 );
13}
14
15// An attacker submitting a profile URL https://attacker.tld/landing produces an
16// anchor whose destination can navigate the original tab via
17// window.opener.location = 'https://evil-clone.tld/login'.
18// Every visitor who clicks the attacker's profile link is one navigation away
19// from a phishing page that looks identical to your login.The team patches every <a target="_blank"> to add rel="noopener noreferrer". A pentester reports window.open(url) calls in three files still leak the opener. Why is that a separate fix, and what does it tell you about the original review?
03 //Payload Anatomy & Trigger Patterns
A new tab becomes a reverse-tabnabbing sink the moment it carries a non-null window.opener for a cross-origin destination. The HTML spec preserves that reference by default for any new browsing context created with a target name, which includes target="_blank", named targets like target="popup", and window.open without explicit noopener. The defensive bytes are rel="noopener" on the markup side and "noopener" in the window.open features string on the JS side. rel="noreferrer" is the legacy cross-browser equivalent and also strips the Referer header, which is usually a good thing.
<a target="_blank" href=...>withoutrel="noopener"<form target="_blank" action=...>submissionswindow.open(url)withoutnoopenerin the features string<area target="_blank">in image maps<base target="_blank">applied document-wide- Server-rendered HTML pulled from user-submitted Markdown or rich-text editors
- Comment bodies, profile bios, and any user-supplied HTML
- Email templates rendered inside a webmail iframe with
target="_blank" dangerouslySetInnerHTMLin React with sanitised but unattributed<a>tags- Markdown renderers that emit external links with no rel attribute
- PDF and SVG viewers that follow
<a target>annotations - Browser-extension content scripts that
window.openpage URLs
The full trigger set is { target="_blank", target="_new", target="<named>" } plus any window.open() call whose features string lacks noopener. If any of these reach the DOM without rel="noopener noreferrer" and the destination is not under your first-party control, you have a tabnabbing sink. Markdown-rendered links and rich-text editors are by far the most common forgotten path.
Payload Catalogue, What an Attacker Actually Writes
1// 1) The original Bynens 2014 payload, still works in any engine
2// that does not enforce the implicit noopener default.
3if (window.opener) {
4 window.opener.location = 'https://login-app.tld/signin';
5}
6
7// 2) Delayed, defeats users who notice the immediate redirect.
8// Fires after the victim has switched away and back.
9setTimeout(() => {
10 if (window.opener) window.opener.location = 'https://login-app.tld/signin';
11}, 15_000);
12
13// 3) Combined with postMessage abuse, the opener may listen for messages
14// on a permissive origin check and trust attacker-supplied data.
15if (window.opener) {
16 window.opener.postMessage({ type: 'login', token: 'fake' }, '*');
17}rel="noopener" and call it done. noopener nulls window.opener, which closes the tabnabbing path, but the request to the destination still carries a full Referer header (the URL of your page, including query strings that may leak session tokens, search queries, or internal route IDs). Adding noreferrer strips the Referer as well, and as a bonus also nulls the opener on older engines that implemented noreferrer before noopener existed. The defensible rule is to ship both attributes together: rel="noopener noreferrer".A reviewer suggests adding rel="noopener" to every outbound anchor. A teammate replies 'that still leaks the Referer, and on a few older WebViews the opener is preserved when only noopener is set without noreferrer'. Who is right and what is the minimal correct rule?
04 //Mitigation Patterns
There are three correct mitigations, in rough order of preference. Render every outbound anchor with rel="noopener noreferrer" via a shared component (so the attribute can never be forgotten); wrap window.open in a helper that always passes noopener; and set Cross-Origin-Opener-Policy: same-origin on every document so the browsing-context group is isolated from any popup that does slip through. Each one is a few lines of code; the discipline is to apply them at every sink, not just the homepage.
Mitigation Options at a Glance
| Strategy | How | When to use |
|---|---|---|
| Shared outbound-link component | One | Always. This is the primary control; banning bare in lint is the durable enforcement. |
| safeOpen() wrapper for window.open | A helper that calls window.open(url, "_blank", "noopener,noreferrer") and asserts the result | Every programmatic popup, OAuth handoff, print-preview, share-sheet, or download trigger. |
| Cross-Origin-Opener-Policy: same-origin | Server-set HTTP response header that isolates the browsing-context group | Every authenticated document. Closes the residual gap when a single anchor slips through review. |
| Configure Markdown / rich-text renderers | Tell the renderer to add target="_blank" and rel="noopener noreferrer" on outbound links | Anywhere user-submitted text becomes HTML: comments, profiles, knowledge-base articles, tickets. |
| Block data: and javascript: in href | Allow-list http(s): and mailto: protocols on user-supplied URLs before rendering | Belt-and-braces for tabnabbing combined with XSS; trim the protocol surface to what you actually need. |
| Drop target="_blank" entirely | Open outbound links in the same tab; let the user middle-click if they want a new tab | High-trust paths where you can afford the UX change; removes the sink class outright. |
1// components/OutboundLink.tsx, one canonical component used at every outbound link.
2//
3// Strategy: render <a target="_blank" rel="noopener noreferrer"> by default,
4// and let callers opt out only for first-party links (same origin).
5// A lint rule bans bare <a target="_blank"> elsewhere in the codebase.
6
7import { AnchorHTMLAttributes } from 'react';
8
9const SAFE_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);
10
11function isFirstParty(href: string): boolean {
12 try {
13 const u = new URL(href, window.location.origin);
14 return u.origin === window.location.origin;
15 } catch {
16 return false;
17 }
18}
19
20function assertSafeHref(href: string): void {
21 try {
22 const u = new URL(href, 'https://app.tld');
23 if (!SAFE_PROTOCOLS.has(u.protocol)) {
24 throw new Error(`unsafe protocol: ${u.protocol}`);
25 }
26 } catch {
27 throw new Error('invalid href');
28 }
29}
30
31type Props = AnchorHTMLAttributes<HTMLAnchorElement> & { href: string };
32
33export function OutboundLink({ href, children, ...rest }: Props) {
34 assertSafeHref(href);
35 const sameOrigin = typeof window !== 'undefined' && isFirstParty(href);
36 return (
37 <a
38 href={href}
39 target={sameOrigin ? undefined : '_blank'}
40 rel={sameOrigin ? undefined : 'noopener noreferrer'}
41 {...rest}
42 >
43 {children}
44 </a>
45 );
46}
47
48// Use the component at EVERY outbound link. Do not render bare <a> elsewhere.
49// <OutboundLink href={partnerUrl}>Partner site</OutboundLink>window.open(url, target) calls without an explicit noopener in the features string still hand back a window object whose opener points at the caller. The defensive form is window.open(url, "_blank", "noopener,noreferrer"), which returns null. If you need the window reference (printing, focusing back later), set win.opener = null on the returned object before assigning anything to it, but prefer the noopener form because it also prevents the new tab from running in the same process as your document.1// lib/safe-open.ts, the only allowed wrapper for window.open.
2//
3// Lint bans direct window.open calls. Every popup, OAuth handoff, share-sheet,
4// or print-preview goes through this helper, which guarantees noopener and
5// noreferrer in the features string.
6
7const SAFE_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);
8
9export function safeOpen(rawUrl: string, target: string = '_blank'): Window | null {
10 let parsed: URL;
11 try {
12 parsed = new URL(rawUrl, window.location.origin);
13 } catch {
14 throw new Error('safeOpen: invalid URL');
15 }
16 if (!SAFE_PROTOCOLS.has(parsed.protocol)) {
17 throw new Error(`safeOpen: refusing protocol ${parsed.protocol}`);
18 }
19 // The features string is the load-bearing argument. Without "noopener",
20 // the returned window keeps a back-reference to the opener, which is the
21 // exact channel the attack uses.
22 const win = window.open(parsed.toString(), target, 'noopener,noreferrer');
23 // Belt-and-braces: even with noopener in the features string, defensively
24 // null the opener on the returned reference if the browser hands one back.
25 if (win) win.opener = null;
26 return win;
27}1<!-- components/OutboundLink.vue -->
2<template>
3 <a
4 :href="href"
5 :target="external ? '_blank' : undefined"
6 :rel="external ? 'noopener noreferrer' : undefined"
7 >
8 <slot />
9 </a>
10</template>
11
12<script setup lang="ts">
13const props = defineProps<{ href: string }>();
14
15const SAFE = new Set(['http:', 'https:', 'mailto:']);
16const url = new URL(props.href, window.location.origin);
17if (!SAFE.has(url.protocol)) {
18 throw new Error('OutboundLink: unsafe protocol');
19}
20const external = url.origin !== window.location.origin;
21</script>
22
23<!-- Global directive that prevents raw <a target="_blank"> in templates -->
24<!-- plugins/eslint-no-bare-blank-target.ts enforces the rule at build time. -->1// outbound-link.directive.ts, applied wherever an anchor has target="_blank".
2import { Directive, ElementRef, HostBinding, Input, OnInit } from '@angular/core';
3
4@Directive({ selector: 'a[target="_blank"]', standalone: true })
5export class OutboundLinkDirective implements OnInit {
6 @Input() href = '';
7
8 @HostBinding('attr.rel') rel = 'noopener noreferrer';
9
10 constructor(private host: ElementRef<HTMLAnchorElement>) {}
11
12 ngOnInit(): void {
13 const SAFE = new Set(['http:', 'https:', 'mailto:']);
14 let u: URL;
15 try {
16 u = new URL(this.href, window.location.origin);
17 } catch {
18 throw new Error('OutboundLinkDirective: invalid href');
19 }
20 if (!SAFE.has(u.protocol)) {
21 throw new Error(`OutboundLinkDirective: refusing protocol ${u.protocol}`);
22 }
23 }
24}1// lib/markdown-safe.js, the post-processor every Markdown renderer
2// must run before HTML reaches the response body.
3//
4// Strategy: tell the renderer to emit target="_blank" with the right rel,
5// and post-process anything user-supplied (HTML pasted into a rich-text
6// editor, imported docs, raw HTML blocks) to enforce the same default.
7
8import sanitizeHtml from 'sanitize-html';
9
10export function renderUserMarkdown(html) {
11 return sanitizeHtml(html, {
12 allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
13 allowedAttributes: {
14 ...sanitizeHtml.defaults.allowedAttributes,
15 a: ['href', 'name', 'target', 'rel'],
16 },
17 // Strip dangerous protocols outright; tabnabbing combines badly with
18 // javascript: and data: URLs in the same href.
19 allowedSchemes: ['http', 'https', 'mailto'],
20 transformTags: {
21 a: (tagName, attribs) => {
22 const href = attribs.href || '';
23 let isExternal = true;
24 try {
25 isExternal = new URL(href, 'https://app.tld').origin !== 'https://app.tld';
26 } catch {
27 /* keep external default */
28 }
29 if (isExternal) {
30 attribs.target = '_blank';
31 attribs.rel = 'noopener noreferrer';
32 } else {
33 delete attribs.target;
34 delete attribs.rel;
35 }
36 return { tagName: 'a', attribs };
37 },
38 },
39 });
40}A developer says 'modern Chrome and Firefox already null window.opener for target="_blank" anchors, so we do not need rel=noopener'. Why is that not enough?
05 //Format-Specific Concerns: Markdown, Frameworks, and Embeds
Adding rel="noopener noreferrer" in your own JSX is necessary but not sufficient. Reverse tabnabbing has several format-specific subtleties that produce real, exploitable bypasses: Markdown renderers that emit anchors without rel, framework routers that bypass the shared component, embedded surfaces (PDFs, SVG, WebViews) that ignore modern defaults, and OAuth popup flows that need a window reference and therefore tempt developers into removing the safeguard. Each one has produced disclosures in mainstream apps. A reviewer looking only at JSX will miss them.
Per-Surface Behaviour and Required Defense
| Surface | Bypass pattern | Correct defense |
|---|---|---|
| Markdown / CommonMark renderers | Default output emits with no rel; outbound links in user content are tabnabbing-prone | Configure the renderer (remark-external-links, markdown-it-link-attributes, marked.use({ renderer })) to add target and rel on every outbound link |
| Rich-text WYSIWYG output (TinyMCE, CKEditor, Quill) | Pasted HTML preserves user-supplied target and href; rel may be stripped by sanitiser | Allow target and rel in the sanitiser allowlist, then force rel="noopener noreferrer" via a transformTags hook |
| Next.js / Remix / Nuxt link components | for internal routes is fine; raw for outbound bypasses the framework | Wrap framework Link in a shared OutboundLink component; lint bans bare |
| OAuth popup callbacks | window.open(authUrl, "_blank") is opened without noopener so the parent can postMessage the resulting tokens | Use noopener and a server round-trip with a state nonce instead of a direct window reference; or open same-tab and redirect back |
| Electron / Tauri / WebView shells | Embedded Chromium may not enforce the implicit noopener default, especially on older builds or custom configurations | Set webPreferences.nativeWindowOpen and explicit rel attributes; configure the will-navigate / new-window handler to enforce noopener |
| PDF, SVG, and DOCX preview viewers | annotations in user-supplied documents may open external URLs with full window.opener access | Strip or normalise annotations during preview generation; render previews in a sandboxed iframe with COOP same-origin |
| Email templates rendered in webmail | Outbound links in transactional mail rendered inside Gmail / Outlook / a webmail iframe can tabnab the surrounding webmail tab | Render template anchors with rel="noopener noreferrer" server-side; treat outbound mail HTML as untrusted by the webmail client |
1// lib/markdown.js, configure the renderer once, render everywhere.
2import { Marked } from 'marked';
3
4const marked = new Marked({
5 renderer: {
6 link(href, title, text) {
7 let isExternal = false;
8 try {
9 const u = new URL(href, 'https://app.tld');
10 isExternal = u.origin !== 'https://app.tld';
11 } catch {
12 return text; // refuse to render an unparseable href
13 }
14 const attrs = isExternal
15 ? ` target="_blank" rel="noopener noreferrer nofollow ugc"`
16 : '';
17 const t = title ? ` title="${escapeAttr(title)}"` : '';
18 return `<a href="${escapeAttr(href)}"${t}${attrs}>${text}</a>`;
19 },
20 },
21});
22
23// For markdown-it the equivalent is markdown-it-link-attributes:
24// md.use(require('markdown-it-link-attributes'), {
25// matcher(href) { return /^https?:/.test(href) && !href.startsWith('https://app.tld'); },
26// attrs: { target: '_blank', rel: 'noopener noreferrer nofollow ugc' },
27// });rel="noopener noreferrer nofollow ugc". nofollow tells search engines not to transfer link equity to attacker-controlled URLs, which both deflates SEO spam and reduces the value of compromising your comments section. ugc (user-generated content) is the modern successor and signals the same intent more precisely. Together with noopener and noreferrer, they form the recommended four-attribute baseline for outbound user links.1// auth/oauth-popup.ts, opens an OAuth popup without leaking window.opener.
2//
3// The naive pattern (window.open(authUrl, "_blank")) opens the popup with
4// the opener reference intact so the parent can listen for postMessage from
5// the callback. That preserves the tabnabbing channel for the entire OAuth
6// session and gives the IdP (or anything the IdP redirects to) a free shot
7// at navigating the parent.
8//
9// Safer pattern: open with noopener, generate a state nonce, and poll a
10// short-lived server endpoint for the result instead of cross-window postMessage.
11
12import { safeOpen } from '../lib/safe-open';
13
14export async function startOAuth(provider: 'google' | 'github'): Promise<{ token: string }> {
15 const state = crypto.randomUUID();
16 const url = `/auth/start/${provider}?state=${state}`;
17 // safeOpen passes noopener,noreferrer; the popup cannot reach window.opener.
18 safeOpen(url);
19 // Poll a server endpoint that the callback writes to when the user finishes.
20 return pollForResult(state, { intervalMs: 1500, timeoutMs: 60_000 });
21}
22
23// Trade-off: a single server round-trip per poll is more chatty than a
24// cross-window postMessage, but the channel is auditable, observable, and
25// not load-bearing on browser-context references that change with every
26// browser release.A pentester reports that a Markdown comment with [evil](https://attacker.tld) renders to <a href="https://attacker.tld" target="_blank">evil</a> without any rel attribute. Your validator runs on the Markdown source, so the check passes and the rendered HTML leaks window.opener. What is the correct fix?
06 //Detection in Code Review
Reverse tabnabbing has a narrow, well-known surface: anywhere an outbound link or popup is opened from your application. Grep gets you most of the way; the rest is reading the call site to confirm the attribute is structured (passed via a shared component) rather than hand-written. SAST tools have uneven coverage; the better tooling flags target="_blank" without rel="noopener" as a static finding and treats window.open calls without a features string as tainted-flow sinks.
1# Find every anchor that opens a new tab. Each one is a place to verify
2# rel="noopener noreferrer" is present, ideally via a shared component.
3
4# JSX / TSX / Vue / Svelte / plain HTML
5rg -n 'target=["\'\\`]_blank' --type-add 'web:*.{html,jsx,tsx,vue,svelte,htm}' -t web
6
7# Anchors WITHOUT rel, the smell to look for
8rg -nP 'target=["\'][_]blank["\'](?![^<>]*\brel=)'
9
10# Programmatic popups, every window.open needs noopener in the features string
11rg -n 'window\.open\s*\('
12
13# window.open WITHOUT noopener, the smell
14rg -nP "window\.open\([^)]*\)" | rg -v 'noopener'
15
16# <form target="_blank">, the forgotten sink
17rg -nE '<form[^>]*target=["\'][_]blank'
18
19# <base target=...>, a global multiplier of the sink surface
20rg -nE '<base[^>]*target='
21
22# Markdown renderers, each one needs to be configured for outbound rel attrs
23rg -n 'marked|remark|markdown-it|commonmark|markdown-it-link-attributes|rehype-external-links'
24
25# The right pattern, a shared component
26rg -n 'OutboundLink|ExternalLink|safeOpen|secureOpen'SAST / Linter Coverage
| Tool | Rule | Catches |
|---|---|---|
| eslint-plugin-react | react/jsx-no-target-blank | JSX without rel="noopener noreferrer" (enabled in recommended preset) |
| eslint-plugin-vue | vue/no-target-blank | Vue templates with target="_blank" and missing rel attributes |
| @angular-eslint | @angular-eslint/template/no-positive-tabindex (related; no dedicated rule) | Use a custom directive selector to enforce rel at compile time |
| Semgrep | javascript.lang.security.audit.window-opener-tabnabbing | JS/TS bare and window.open without noopener in the features string |
| CodeQL | js/dom-based-xss family includes window.open with tainted URL; no dedicated tabnabbing rule | Indirect coverage via tainted-flow into window.open; add a custom query for missing noopener |
| Snyk Code | CWE-1022 rule family | Multi-language detection of target="_blank" without rel and unsafe window.open patterns |
| htmlhint | rel-noopener / rel-no-unsafe-target | Static HTML scan for missing rel on target="_blank" anchors |
1# semgrep-rules/reverse-tabnabbing.yaml
2rules:
3 - id: anchor-blank-without-noopener
4 languages: [javascript, typescript]
5 severity: ERROR
6 message: >-
7 <a target="_blank"> without rel="noopener noreferrer" leaks
8 window.opener to the destination origin, enabling reverse tabnabbing.
9 Render outbound links via the shared OutboundLink component.
10 patterns:
11 - pattern-either:
12 - pattern: <a target="_blank" ...>...</a>
13 - pattern: <a $...PROPS target={"_blank"} ...>...</a>
14 - pattern-not-inside: |
15 <a target="_blank" rel="noopener noreferrer" ...>...</a>
16 - pattern-not-inside: |
17 <a target="_blank" rel="noopener noreferrer nofollow ugc" ...>...</a>
18 - pattern-not-inside: |
19 <OutboundLink ...>...</OutboundLink>
20 metadata:
21 cwe: 'CWE-1022'
22 owasp: 'A05:2021 - Security Misconfiguration'
23
24 - id: window-open-without-noopener
25 languages: [javascript, typescript]
26 severity: ERROR
27 message: >-
28 window.open(...) without "noopener" in the features string leaves
29 window.opener populated and lets the destination navigate the opener.
30 Use safeOpen(url) from lib/safe-open.ts.
31 patterns:
32 - pattern-either:
33 - pattern: window.open($URL)
34 - pattern: window.open($URL, $TARGET)
35 - pattern-not: window.open($URL, $TARGET, "...noopener...")
36 - pattern-not-inside: |
37 function safeOpen(...) { ... }
38 metadata:
39 cwe: 'CWE-1022'rel="noopener noreferrer" (plus nofollow ugc for user content)? (3) Does window.open pass noopener,noreferrer in the features string? (4) Are user-submitted Markdown and rich-text renderers configured to add the rel attribute on outbound links? (5) Is Cross-Origin-Opener-Policy: same-origin set on authenticated documents as a backstop? (6) For embedded surfaces (PDF, SVG, WebView, Electron), are external links normalised or sandboxed before display? Any "no" is a finding.1// __tests__/outbound-link.spec.tsx, characterisation test that catches
2// regressions every time someone touches
3// the OutboundLink component.
4import { render } from '@testing-library/react';
5import { OutboundLink } from '../components/OutboundLink';
6import { safeOpen } from '../lib/safe-open';
7
8describe('OutboundLink', () => {
9 it('renders rel="noopener noreferrer" and target="_blank" for external URLs', () => {
10 const { container } = render(<OutboundLink href="https://partner.tld">x</OutboundLink>);
11 const a = container.querySelector('a')!;
12 expect(a.getAttribute('target')).toBe('_blank');
13 expect(a.getAttribute('rel')).toBe('noopener noreferrer');
14 });
15
16 it('does NOT set target or rel for same-origin URLs', () => {
17 const { container } = render(<OutboundLink href="/internal/page">x</OutboundLink>);
18 const a = container.querySelector('a')!;
19 expect(a.getAttribute('target')).toBeNull();
20 expect(a.getAttribute('rel')).toBeNull();
21 });
22
23 it.each([
24 ['javascript:', 'javascript:alert(1)'],
25 ['data:', 'data:text/html,<script>alert(1)</script>'],
26 ['vbscript:', 'vbscript:msgbox(1)'],
27 ['file:', 'file:///etc/passwd'],
28 ])('refuses %s protocol', (_label, href) => {
29 expect(() => render(<OutboundLink href={href}>x</OutboundLink>)).toThrow();
30 });
31});
32
33describe('safeOpen', () => {
34 it('passes noopener,noreferrer in the features string', () => {
35 const spy = jest.spyOn(window, 'open').mockReturnValue(null);
36 safeOpen('https://partner.tld');
37 expect(spy).toHaveBeenCalledWith(
38 'https://partner.tld/',
39 '_blank',
40 'noopener,noreferrer',
41 );
42 });
43});A code review finds 23 anchor sinks across the codebase. The team lead suggests banning bare <a target="_blank"> in lint and forcing them through the OutboundLink component. Is that a good control?
07 //Real-World Case Studies
Reverse tabnabbing has a long and embarrassingly repetitive disclosure history. The pattern is monotonous: a major site renders user-controlled outbound links with target="_blank" and no rel="noopener", a researcher publishes a window.opener.location proof-of-concept, the vendor ships a one-line attribute change, and a year later a different surface in the same product makes the same mistake. The interesting part is how often the bug appears in user-content-heavy products: social networks, code-hosting platforms, knowledge bases, anywhere people submit links.
- Mathias Bynens 2014 disclosure, the original write-up that put the bug class on the map. Demonstrated against Twitter, Facebook, LinkedIn, and many others, all of which rendered user-submitted outbound links with bare
target="_blank". Most major platforms shippedrel="noopener noreferrer"defaults within months, but the long tail of smaller products kept the issue alive for the next decade. - Google search-result links (multiple disclosures, 2017-2019), Google's search results historically rendered outbound result links with
target="_blank"and no rel. Google addednoopenerin 2017, but several adjacent surfaces (image search, news vertical, knowledge panel cards) needed separate fixes over the following two years. Each one was the same one-line change. - GitHub README, Issues, and Pages (long tail), GitHub's Markdown pipeline renders user content as HTML. Outbound links in READMEs, issue comments, and Pages-hosted sites historically reached the DOM without consistent
rel="noopener". GitHub now defaults tonofollow noopener noreferrer ugcfor outbound user links, but the migration touched a dozen rendering paths. - WordPress (Gutenberg block editor, 2018), the block editor exposed a toggle for "Open in new tab" on link blocks. Early Gutenberg betas added
target="_blank"without settingrel, producing tabnabbing across every WordPress site using the new editor until a point release patched the default. - Microsoft Teams "Stay-in-Teams" handler (2020), a deep-link handler that opened external URLs inside the Teams Electron shell did not enforce
noopenerin itswindow.opencalls. Compromised links shared in chat could navigate the Teams window itself. Fixed by adding awill-navigateguard and explicitnoopenerin the new-window handler. - Slack message link unfurls (multiple, 2019-2022), anchor rendering inside Slack desktop builds occasionally regressed on
rel="noopener"when Electron'snativeWindowOpenwas toggled. Slack added an internal proxy that runs every outbound click through a server-side redirect so a downstream attacker page cannot reach back to the client. - Notion and Linear public-share pages (2021-2023), public Notion documents and Linear shared issues rendered Markdown-style outbound links. Both products shipped
rel="noopener noreferrer nofollow"defaults after disclosure, with the additionalugchint added in a later iteration. - VS Code Markdown preview (CVE-2023-36730), the Markdown preview pane in VS Code rendered outbound links inside a webview without the rel attribute. Combined with the embedded Electron context, a malicious preview could navigate the editor window. Patched by adding the rel attribute in the preview renderer and tightening the webview's allow-list.
Across the case studies, what is the recurring root cause?
08 //Beyond the Code: COOP, CSP, and Outbound Posture
The HTML-attribute fix closes the immediate sink. The HTTP-header fix limits the blast radius when a future regression slips through. Cross-Origin-Opener-Policy: same-origin on every authenticated document means that a popup or new tab whose origin is not same-origin to the opener gets a fresh browsing-context group, with window.opener already null on arrival. Treat outbound posture as part of the defense, not a separate ops concern.
Outbound Hardening Recommendations
| Control | What it does | Why it limits reverse-tabnabbing impact |
|---|---|---|
| Cross-Origin-Opener-Policy: same-origin | Forces a new browsing-context group for cross-origin popups; window.opener is null on the destination | A missed rel attribute on a single anchor no longer leaks the opener reference to a cross-origin destination. |
| Cross-Origin-Embedder-Policy: require-corp | Pairs with COOP to enable cross-origin isolation; tightens the boundary further | Required for some advanced isolation guarantees; nice-to-have alongside COOP for hardened apps. |
| Content-Security-Policy frame-ancestors / form-action | Restricts where forms can submit and where the page can be embedded | Reduces adjacent abuse channels (clickjacking, form hijacking) that combine with tabnabbing. |
| Outbound-link interstitial / proxy | Outbound clicks go through /redirect?url=... that warns or scrubs the destination | Gives the application a chance to strip referrer, log clicks, and warn the user about leaving the site. |
| Strict outbound URL allow-list for redirector endpoints | Open-redirect prevention on any server-side endpoint that takes a destination URL | Prevents attackers from chaining open-redirect into a tabnabbing-style phish that looks first-party. |
| Sandboxed iframes for embedded user content | Embedded content cannot escape the iframe to open opener-leaking popups in the parent. |
1# Set on every authenticated HTML response. These three headers are the
2# server-side backstop for reverse tabnabbing and adjacent UI-redress bugs.
3
4Cross-Origin-Opener-Policy: same-origin
5Cross-Origin-Resource-Policy: same-origin
6Content-Security-Policy:
7 default-src 'self';
8 script-src 'self';
9 frame-ancestors 'none';
10 form-action 'self';
11 base-uri 'none';
12Referrer-Policy: strict-origin-when-cross-origin
13
14# COOP same-origin gives every authenticated document its own browsing-context
15# group. Any popup or new tab whose origin is not same-origin starts with a
16# null window.opener, regardless of whether the anchor remembered rel.
17#
18# CSP base-uri 'none' prevents an injected <base target="_blank"> from
19# multiplying the tabnabbing sink surface across every anchor on the page.
20#
21# Referrer-Policy strict-origin-when-cross-origin removes path / query data
22# from the Referer header on outbound clicks, complementing rel="noreferrer".<base target> from amplifying the sink surface, and keep the Referer header lean. Pair the HTML fix (shared component, lint rule, configured Markdown renderer) with strong server-side posture so the worst-case incident is contained.1// lib/outbound.tsx, the one and only allowed outbound-link entry point.
2//
3// Everything goes through this module. Direct <a target="_blank"> and
4// window.open usage is banned by lint. The module guarantees:
5// * target="_blank" only for cross-origin destinations
6// * rel="noopener noreferrer" always, plus "nofollow ugc" for user content
7// * Allow-list of http(s) and mailto: protocols
8// * Optional interstitial redirect for outbound clicks in high-trust paths
9
10import { AnchorHTMLAttributes, MouseEvent } from 'react';
11
12const SAFE = new Set(['http:', 'https:', 'mailto:']);
13
14interface Props extends AnchorHTMLAttributes<HTMLAnchorElement> {
15 href: string;
16 userContent?: boolean;
17 interstitial?: boolean;
18}
19
20function classify(href: string): { external: boolean; canonical: string } {
21 const u = new URL(href, 'https://app.tld');
22 if (!SAFE.has(u.protocol)) throw new Error(`refusing protocol ${u.protocol}`);
23 return { external: u.origin !== 'https://app.tld', canonical: u.toString() };
24}
25
26export function OutboundLink({ href, userContent, interstitial, children, onClick, ...rest }: Props) {
27 const { external, canonical } = classify(href);
28 const rel = external
29 ? userContent
30 ? 'noopener noreferrer nofollow ugc'
31 : 'noopener noreferrer'
32 : undefined;
33 const finalHref = external && interstitial
34 ? `/r?u=${encodeURIComponent(canonical)}`
35 : canonical;
36 const handle = (e: MouseEvent<HTMLAnchorElement>) => {
37 if (onClick) onClick(e);
38 };
39 return (
40 <a
41 href={finalHref}
42 target={external ? '_blank' : undefined}
43 rel={rel}
44 onClick={handle}
45 {...rest}
46 >
47 {children}
48 </a>
49 );
50}
51
52// Use it everywhere outbound links appear:
53// <OutboundLink href={partnerUrl}>Partner</OutboundLink>
54// <OutboundLink href={userSubmittedUrl} userContent>{label}</OutboundLink>
55// <OutboundLink href={trackedUrl} interstitial>Tracked</OutboundLink>09 //Conclusion
Reverse tabnabbing is a textbook case of trust transferred across a navigation seam. The application is correct; the browser is correct; the same-origin policy is enforced. The vulnerability lives in the moment a new browsing context is opened with a back-reference the destination did not need. Fix it the same way every adjacent bug class is fixed: a single component, applied at every sink, paired with a structured popup helper and an HTTP posture (COOP, CSP, Referrer-Policy) that limits the damage when something does slip through.
rel="noopener noreferrer" (add nofollow ugc for user-submitted content) · Wrap every window.open in a safeOpen helper that passes noopener,noreferrer in the features string · Configure Markdown and rich-text renderers to add target and rel on outbound links · Block javascript:, data:, and other unsafe protocols in href · Ban bare <a target="_blank"> via react/jsx-no-target-blank or equivalent · Add a Semgrep / CodeQL rule that flags window.open without noopener · Set Cross-Origin-Opener-Policy: same-origin, Referrer-Policy: strict-origin-when-cross-origin, and a tight CSP on every authenticated document.When you see a new outbound link in a diff, the first question is not "does it open the right URL", it is "what reference does the destination get back to my tab, and how?" If the answer involves a raw anchor or a bare window.open, every byte in the destination URL is potentially a phishing primitive. The fix is one component and one helper away. Pair this module with the Open Redirect, Clickjacking, and postMessage Attacks guides for the adjacent classes where the bug is "an output sink hands the attacker a navigation or messaging channel back into your application."