From 7b7adef0161f9ef55c1049ac64b940397ea4b64f Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Sat, 27 Jun 2026 18:30:19 +0200 Subject: [PATCH] fix(xslt): bound template recursion so it fails gracefully, not with a crash (#357) * fix(xslt): bound template recursion so it fails gracefully, not with a crash A recursive named template whose depth is driven by source data (e.g. ``) could recurse without bound and overflow the native stack (SIGBUS) on attacker-controllable input. Every XSLT processor guards this (libxslt's xsltMaxDepth); PureXML did not. Measurement first: source *nesting* depth is not the exposure. `transform` parses the source at the default maxDepth (256) and there is no XSLT API that accepts a pre-built tree, so the engine never sees a source deeper than ~255; an identity transform of a 254-deep source completes normally on a normal stack. The reachable crash is data-driven template recursion, which overflows an 8 MB stack between ~400 and 600 levels. Template-instantiation nesting (instantiateTemplate and builtInRule) is now counted and capped at maxTemplateDepth; past it the guard latches, the instantiation loops unwind, and `transform` throws XSLTError.recursionLimitExceeded instead of crashing. The default (300, exposed as PureXML.XSLT.defaultMaxTemplateDepth, overridable via a new maxTemplateDepth parameter on transform) clears the parser's max source depth so a deep-source identity transform still runs, while staying within an 8 MB main-thread stack with margin. A stylesheet with deeper legitimate recursion raises the limit on a correspondingly larger stack. copyOf moved to XSLTSorting.swift to keep XSLTTransformer.swift within the file length limit; it is unchanged (a whole-subtree copy that does not recurse on depth). Guarded by XSLTRecursionLimitTests (run on a large-stack thread, since the limit is above what swift-testing's Task stack holds). Full suite 1802 pass. Part of #356; making the engine fully iterative (deep recursion succeeds, and is safe on a small Task stack) remains tracked there. * test(xslt): exclude the large-stack recursion tests on WASI WASI is single-threaded and has no Foundation Thread/DispatchSemaphore, which the recursion-limit tests need to exercise the guard on a stack large enough for the limit (300) to fire before the stack overflows. Guard the file with #if !os(WASI); the recursion guard itself is platform-independent pure Swift, covered by the macOS and Linux runs. --- CHANGELOG.md | 2 + Sources/XSLT/XSLTParser.swift | 6 ++ Sources/XSLT/XSLTRuntime.swift | 19 ++++++ Sources/XSLT/XSLTSorting.swift | 32 +++++++++- Sources/XSLT/XSLTTransform.swift | 3 + Sources/XSLT/XSLTTransformer.swift | 33 +++++----- Tests/XSLTRecursionLimitTests.swift | 96 +++++++++++++++++++++++++++++ 7 files changed, 174 insertions(+), 17 deletions(-) create mode 100644 Tests/XSLTRecursionLimitTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c78544..751ac3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- An XSLT transform with unbounded template recursion no longer overflows the stack; it fails gracefully with `XSLTError.recursionLimitExceeded` instead (#356). A recursive named template whose depth is driven by source data (for example ``) could recurse without bound and crash the process (SIGBUS) on an attacker-controllable input, the way every XSLT processor guards against (libxslt's `xsltMaxDepth`). Template-instantiation nesting is now counted and capped at `maxTemplateDepth` (default 300, exposed as `PureXML.XSLT.defaultMaxTemplateDepth`), a new optional parameter on `PureXML.XSLT.transform`. The default clears the parser's maximum source nesting depth (256) so an identity transform of the deepest permitted source still runs, while staying within an 8 MB main-thread stack with margin; a stylesheet with deeper legitimate recursion can raise the limit (on a correspondingly larger stack). Measurement note: source *nesting* depth was never the exposure here, since the engine only ever sees a source parsed at the default `maxDepth` and an identity transform of a 254-deep source completes normally; the reachable crash was data-driven template recursion. The full XSLT/XPath conformance suite is unchanged (no corpus transform recurses past the default). Making the engine fully iterative (so deep recursion succeeds rather than failing gracefully, and is safe on a small Swift-concurrency Task stack) remains tracked in #356. + - Serializing a tree as HTML (`PureXML.HTML.serialize`, the html output method's serializer) no longer recurses on the tree's depth, so it no longer overflows the stack on a deeply-nested tree (as shallow as a couple of thousand deep on a Swift Task stack). The serializer now drives a deferred-close work stack (the same shape as the XML serializer and `Canonicalizer`): an element pushes a close step then its children reversed, and a raw-text element (`script`, `style`) flags its direct text children to emit verbatim. The output is byte-identical: the void-element, raw-text, comment, and escaping semantics are unchanged, with the HTML conformance corpus passing. A 50000-deep tree now serializes without crashing. (#350) - Processing `xi:include` elements (`PureXML.XInclude.process`) no longer recurses on the tree's depth, so it no longer overflows the stack on a deeply-nested document, even one with no includes (as shallow as a couple of thousand deep on a Swift Task stack). The pass now drives an explicit work stack: each branch gathers its processed children into a reference accumulator, then a deferred build step assembles the node, while the `xml:base`, inclusion-chain depth, and cycle-detection visited set thread down exactly as before. An include splices its (or its fallback's) content in place by pushing the loaded nodes back onto the stack. Behavior is unchanged: the XInclude/XPointer conformance corpus and the fallback, xpointer, cycle, and `xml:base` cases pass. A 50000-deep document, with or without an include at its base, now processes without crashing. (#350) diff --git a/Sources/XSLT/XSLTParser.swift b/Sources/XSLT/XSLTParser.swift index 152c11a..3599599 100644 --- a/Sources/XSLT/XSLTParser.swift +++ b/Sources/XSLT/XSLTParser.swift @@ -35,11 +35,17 @@ public extension PureXML.XSLT { case notAStylesheet /// An `xsl:message terminate="yes"` ended the transformation with this text. case terminated(String) + /// Template instantiation nested deeper than the configured limit (the + /// associated value), so the transform was stopped before it could + /// overflow the stack. Reached by unbounded template recursion, e.g. a + /// recursive named template whose depth is driven by source data. + case recursionLimitExceeded(Int) public var description: String { switch self { case .notAStylesheet: "the document is not an xsl:stylesheet" case let .terminated(message): "transformation terminated: \(message)" + case let .recursionLimitExceeded(limit): "template recursion exceeded the limit of \(limit)" } } } diff --git a/Sources/XSLT/XSLTRuntime.swift b/Sources/XSLT/XSLTRuntime.swift index 1674e96..1dfbff4 100644 --- a/Sources/XSLT/XSLTRuntime.swift +++ b/Sources/XSLT/XSLTRuntime.swift @@ -1,4 +1,12 @@ extension PureXML.XSLT { + /// The default ceiling on template-instantiation nesting (see + /// ``RecursionGuard``). Chosen to clear the parser's max source depth (256), + /// so an identity transform of the deepest permitted source still runs, while + /// staying within an 8 MB stack with margin; unbounded template recursion + /// (which can overflow the stack) trips it well before that. Configurable per + /// transform for stylesheets with deeper legitimate recursion. + public static let defaultMaxTemplateDepth = 300 + /// One produced item: a node for the result tree, or an attribute to attach to /// the enclosing element. enum ResultItem { @@ -64,4 +72,15 @@ extension PureXML.XSLT { final class Termination { var message: String? } + + /// Shared, mutable guard against unbounded template-instantiation recursion + /// (a recursive template whose depth is driven by source data would otherwise + /// overflow the native stack). `depth` tracks the current nesting of template + /// applications; `exceeded` latches once it passes the configured limit, so the + /// instantiation loops unwind and the transform fails gracefully. A reference + /// type so the value-semantics transformer can update it. + final class RecursionGuard { + var depth = 0 + var exceeded = false + } } diff --git a/Sources/XSLT/XSLTSorting.swift b/Sources/XSLT/XSLTSorting.swift index 4f31fd4..40e3110 100644 --- a/Sources/XSLT/XSLTSorting.swift +++ b/Sources/XSLT/XSLTSorting.swift @@ -122,7 +122,13 @@ extension PureXML.XSLT.Transformer { } func builtInRule(_ xnode: PureXML.XPath.Node, mode: String?, _ context: XSLTContext) -> [ResultItem] { - switch xnode { + recursionGuard.depth += 1 + defer { recursionGuard.depth -= 1 } + guard recursionGuard.depth <= maxTemplateDepth else { + recursionGuard.exceeded = true + return [] + } + return switch xnode { case let .tree(node): switch node.kind { case .element, .document: @@ -139,6 +145,24 @@ extension PureXML.XSLT.Transformer { } } + /// Copies the nodes selected by `select` into the result tree (`xsl:copy-of`); + /// a non-node-set result copies as its string value. Whole subtrees are taken + /// as-is, so this does not recurse on their depth. + func copyOf(_ select: String, _ context: XSLTContext) -> [ResultItem] { + guard let nodes = value(select, context)?.nodes else { + // A non-node-set result copies as its string value. + return value(select, context).map { [.node(.text($0.string))] } ?? [] + } + return nodes.map { xnode in + switch xnode { + case let .tree(tree): .node(Self.withInScopeNamespaces(tree)) + case let .attribute(_, attribute): .attribute(attribute) + case let .namespace(_, prefix, uri): + .attribute(.init(prefix.isEmpty ? "xmlns" : "xmlns:\(prefix)", uri)) + } + } + } + func message(_ terminate: Bool, _ body: [PureXML.XSLT.Instruction], _ context: XSLTContext) -> [ResultItem] { if terminate, termination.message == nil { termination.message = Self.text(of: instantiate(body, context)) @@ -154,6 +178,12 @@ extension PureXML.XSLT.Transformer { passing parameters: [PureXML.XSLT.Binding], from caller: XSLTContext, ) -> [ResultItem] { + recursionGuard.depth += 1 + defer { recursionGuard.depth -= 1 } + guard recursionGuard.depth <= maxTemplateDepth else { + recursionGuard.exceeded = true + return [] + } var context = context context.importPrecedence = template.importPrecedence context.importRangeLow = template.importRangeLow diff --git a/Sources/XSLT/XSLTTransform.swift b/Sources/XSLT/XSLTTransform.swift index f8c9677..2c6955c 100644 --- a/Sources/XSLT/XSLTTransform.swift +++ b/Sources/XSLT/XSLTTransform.swift @@ -11,6 +11,7 @@ public extension PureXML.XSLT { documentLoader: @escaping (String) -> String? = { _ in nil }, baseURI: String = "", parameters: [String: String] = [:], + maxTemplateDepth: Int = PureXML.XSLT.defaultMaxTemplateDepth, ) throws -> String { let documentLoader = resolvingLoader(documentLoader, baseURI: baseURI) let sheet = try XSLTParser.parse(stylesheet, loader: documentLoader) @@ -34,8 +35,10 @@ public extension PureXML.XSLT { // The source DTD's unparsed entities, by name to system URI (12.4). unparsedEntityURIs: parsed.documentType.unparsedEntities.mapValues(\.id.resolvedSystemID), baseURI: baseURI, + maxTemplateDepth: maxTemplateDepth, ) let result = transformer.run() + if transformer.recursionLimitExceeded { throw XSLTError.recursionLimitExceeded(maxTemplateDepth) } if let message = transformer.terminationMessage { throw XSLTError.terminated(message) } let method = sheet.output.method ?? defaultMethod(for: result) if method == "text" { diff --git a/Sources/XSLT/XSLTTransformer.swift b/Sources/XSLT/XSLTTransformer.swift index 17a7c28..fec9e95 100644 --- a/Sources/XSLT/XSLTTransformer.swift +++ b/Sources/XSLT/XSLTTransformer.swift @@ -16,6 +16,13 @@ extension PureXML.XSLT { let documentLoader: (String) -> String? private let keyIndexes = PureXML.XSLT.KeyIndexCache() let termination = Termination() + let recursionGuard = PureXML.XSLT.RecursionGuard() + /// The deepest template-instantiation nesting allowed before the transform + /// fails gracefully rather than overflowing the stack. The default clears + /// the parser's max source depth (so an identity transform of the deepest + /// permitted source still runs) while staying within an 8 MB stack; raise + /// it (with a correspondingly larger stack) for deeper legitimate recursion. + let maxTemplateDepth: Int private let matchCache = MatchCache() private let documentCache = PureXML.XSLT.DocumentCache() let numberingCache = XSLTNumbering.SiblingPositionCache() @@ -25,6 +32,12 @@ extension PureXML.XSLT { termination.message } + /// Whether template recursion hit `maxTemplateDepth` during `run()`, so the + /// transform was stopped before it could overflow the stack. + var recursionLimitExceeded: Bool { + recursionGuard.exceeded + } + /// Caller-supplied top-level parameter values, overriding xsl:param defaults. let parameters: [String: String] /// The stylesheet's own parsed document, returned by `document('')` (12.1). @@ -41,8 +54,10 @@ extension PureXML.XSLT { stylesheetDocument: PureXML.Model.Node? = nil, unparsedEntityURIs: [String: String] = [:], baseURI: String = "", + maxTemplateDepth: Int = PureXML.XSLT.defaultMaxTemplateDepth, ) { self.parameters = parameters + self.maxTemplateDepth = maxTemplateDepth self.stylesheet = stylesheet self.root = root self.documentLoader = documentLoader @@ -137,6 +152,7 @@ extension PureXML.XSLT { ) -> [ResultItem] { var items: [ResultItem] = [] for (offset, xnode) in nodes.enumerated() { + if termination.message != nil || recursionGuard.exceeded { break } guard let owner = Self.ownerNode(xnode) else { continue } let nodeContext = XSLTContext( node: owner, @@ -159,7 +175,7 @@ extension PureXML.XSLT { var items: [ResultItem] = [] var context = context for instruction in body { - if termination.message != nil { break } + if termination.message != nil || recursionGuard.exceeded { break } switch instruction { case let .variable(name, select, varBody): context.variables[name] = variableValue(select, varBody, context) @@ -328,21 +344,6 @@ extension PureXML.XSLT.Transformer { return instantiateTemplate(template, context, passing: parameters, from: context) } - private func copyOf(_ select: String, _ context: XSLTContext) -> [ResultItem] { - guard let nodes = value(select, context)?.nodes else { - // A non-node-set result copies as its string value. - return value(select, context).map { [.node(.text($0.string))] } ?? [] - } - return nodes.map { xnode in - switch xnode { - case let .tree(tree): .node(Self.withInScopeNamespaces(tree)) - case let .attribute(_, attribute): .attribute(attribute) - case let .namespace(_, prefix, uri): - .attribute(.init(prefix.isEmpty ? "xmlns" : "xmlns:\(prefix)", uri)) - } - } - } - // MARK: Building elements func buildElement( diff --git a/Tests/XSLTRecursionLimitTests.swift b/Tests/XSLTRecursionLimitTests.swift new file mode 100644 index 0000000..d94feb7 --- /dev/null +++ b/Tests/XSLTRecursionLimitTests.swift @@ -0,0 +1,96 @@ +// The recursion guard must be exercised on a large stack (the limit is above +// what a small stack holds), which needs Foundation's Thread. WASI is +// single-threaded and has no Thread/Dispatch, so these tests are excluded +// there; the guard itself is platform-independent pure Swift, covered by the +// macOS and Linux runs. +#if !os(WASI) + import Foundation + import Testing + @testable import PureXML + + /// XSLT template recursion is bounded so an unbounded recursive template (whose + /// depth can be driven by source data) fails gracefully instead of overflowing + /// the stack (#356). Source *nesting* depth is already bounded by the parser's + /// `maxDepth`, so it is not the exposure; a recursive named template is. + /// + /// These run on a dedicated large-stack thread: the recursion limit (300) is + /// above what swift-testing's small Task stack holds, so the guard must be given + /// a production-sized stack to fire on rather than the test harness overflowing + /// first. That is exactly the gap the limit closes on a normal 8 MB main thread. + @Suite("XSLT template recursion limit") + struct XSLTRecursionLimitTests { + private let xsl = "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"" + + /// Runs `body` on a thread with a large stack and returns its result, so the + /// recursion guard is exercised on a production-sized stack. + private func onLargeStack(_ body: @escaping @Sendable () -> T) -> T { + let box = Box() + let done = DispatchSemaphore(value: 0) + let thread = Thread { + box.value = body() + done.signal() + } + thread.stackSize = 64 * 1024 * 1024 + thread.start() + done.wait() + guard let value = box.value else { preconditionFailure("the worker thread produced no result") } + return value + } + + private final class Box: @unchecked Sendable { var value: T? } + + /// A stylesheet whose named template recurses `count` times, driving the + /// recursion from the passed parameter (a stand-in for `count(//x)`). + private func recursiveStylesheet(_ count: Int) -> String { + "" + + "" + + "" + + "" + + "" + + "" + + "" + } + + @Test("recursion past the default limit throws rather than crashing") + func test_deepRecursionFailsGracefully() { + let error: (any Error)? = onLargeStack { + do { + _ = try PureXML.XSLT.transform(stylesheet: recursiveStylesheet(5000), source: "") + return nil + } catch { + return error + } + } + #expect(error as? PureXML.XSLT.XSLTError == .recursionLimitExceeded(PureXML.XSLT.defaultMaxTemplateDepth)) + } + + @Test("recursion within the limit transforms normally") + func test_shallowRecursionSucceeds() { + let out = onLargeStack { (try? PureXML.XSLT.transform(stylesheet: recursiveStylesheet(100), source: "")) ?? "" } + #expect(out.contains("")) + } + + @Test("a raised maxTemplateDepth allows deeper legitimate recursion") + func test_configurableLimit() { + let out = onLargeStack { + (try? PureXML.XSLT.transform(stylesheet: recursiveStylesheet(1000), source: "", maxTemplateDepth: 4000)) ?? "" + } + // Recursion went far past the default limit of 300 (it would otherwise have + // thrown), producing ~1000 nested elements. + #expect(out.components(separatedBy: "").count - 1 > 900) + } + + @Test("an identity transform of the deepest permitted source still runs") + func test_identityOfMaxDepthSource() { + let depth = 254 // the parser permits up to maxDepth (256) nesting. + let src = String(repeating: "", count: depth) + "leaf" + String(repeating: "", count: depth) + let sheet = "" + + "" + + "" + let out = onLargeStack { (try? PureXML.XSLT.transform(stylesheet: sheet, source: src)) ?? "" } + #expect(out.contains("leaf")) + #expect(out.contains(String(repeating: "", count: depth))) + } + } + +#endif