External resources are content a document references instead of carrying: images, stylesheets, linked pictures and similar files. GroupDocs.Merger treats any resource that a document tries to load from a URL or from a file outside the document as external.
Security considerations
Loading external resources from untrusted documents can pose security risks:
Server-Side Request Forgery (SSRF): a malicious document can reference internal network addresses, such as cloud metadata endpoints or localhost services, and make your server request them.
NTLM credential leaks: a reference to a UNC path (for example \\server\share) can trigger automatic NTLM authentication and leak credentials.
Data exfiltration and tracking: a request to an attacker’s server reveals that, when and where a document was opened.
Local file disclosure: a reference to a local file, such as file:///etc/passwd, can pull content from the machine into the output.
To mitigate these risks, GroupDocs.Merger is secure by default: every LoadOptions sets skip_external_resources to True, and a Merger created without load options uses the same default, so nothing external is loaded unless you allow it.
What loads by default
With skip_external_resources set to True (the default), a document still loads:
content it carries: data: URIs, cid: references, MHTML parts and packaged media, such as the images inside a DOCX, PPTX or EPUB file;
resources that match an entry of whitelisted_resources.
Everything else is skipped and the operation continues: http, https, ftp and every other scheme, UNC paths, local files, including files in the document’s own folder, and relative references that point outside the document.
The options are read when the Merger is created. Changing them afterwards does not affect that Merger. Documents you join to a Merger follow the options of that Merger.
Note
Since version 26.12, external resources are denied by default, and LoadOptions has the skip_external_resources, whitelisted_resources and external_resource_handler properties. Earlier versions loaded the external resources a document referenced and had no option to stop it. If your documents rely on remote images or stylesheets, allow their locations with whitelisted_resources, or set skip_external_resources to False for documents you trust.
Supported document types
The options take effect for these documents:
Documents
External resources they can reference
Word processing: DOC, DOCX, DOCM, DOT, DOTX, DOTM, RTF, ODT, OTT
Images, stylesheets and other resources from outside the book
Other formats:
Raster images and audio have no way to reference an external resource.
For PDF, Visio diagrams, OneNote, plain text, CSV, and ZIP and TAR archives, the product’s tests process a probe document full of external references with every operation that applies to it and observe no request.
XPS, PostScript and TeX documents and the other archive formats are not covered by that measurement.
Allowing trusted resources
To load particular resources from trusted locations while everything else stays denied, add their absolute URI prefixes to whitelisted_resources. The whitelist takes effect only while skip_external_resources is True.
A resource matches an entry when:
its scheme and host equal the entry’s, ignoring case, with no subdomain matching;
its port equals the entry’s once the scheme’s default port is filled in;
its path starts with the entry’s path at a / boundary, case-sensitively, so /assets does not match /assetsX.
Local and UNC paths are compared as file: URIs, so C:\assets\logo.png is compared as file:///C:/assets/logo.png. Dot segments are removed, and the query and fragment are ignored. A resource holding an encoded /, \ or . never matches, and a relative or protocol-relative (//host/...) reference never matches an http or https entry.
The following example merges two web pages that reference a stylesheet and three pictures on docs.groupdocs.com. It loads the stylesheet and the pictures of one folder, assets/, and denies everything else, so the photo under photos/ is not loaded:
fromgroupdocs.mergerimportMergerfromgroupdocs.merger.domainimportFileTypefromgroupdocs.merger.domain.optionsimportLoadOptionsdefallow_trusted_resources():load_options=LoadOptions(FileType.HTML)# Load what is under this folder; every other external resource stays deniedload_options.whitelisted_resources=["https://docs.groupdocs.com/merger/net/_sample_files/developer-guide/loading/skip-external-resources/assets/"]withMerger("./input.html",load_options)asmerger:merger.join("./input2.html")merger.save("./output.html")if__name__=="__main__":allow_trusted_resources()
input.html is a sample file used in this example. Click here to download it.
input2.html is a sample file used in this example. Click here to download it.
The two pages link four files on docs.groupdocs.com, in the folder /merger/net/_sample_files/developer-guide/loading/skip-external-resources/: assets/portal.css, assets/logo.png, photos/north-pier-dock.jpg and assets/holiday-hours.jpg.
An entry that is empty, not an absolute URI, carries a query or fragment, or contains %2F, %5C or %2E makes creating the Merger raise ValueError, whatever skip_external_resources is set to:
Whitelisted resource '<entry>' must be an absolute URI without a query, fragment or encoded '/', '\' or '.'. (Parameter 'WhitelistedResources')
Keep in mind:
the document follows redirects: a whitelisted URL that redirects loads the redirect target, even when the target is not whitelisted;
the list is copied when the Merger is created, and None counts as an empty list.
To decide per resource in code, for example by file type, use a handler.
Deciding per resource with a handler
When a list of prefixes is not enough — to allow resources by file type, to record every resource a document references, or to supply a resource’s content yourself — set the external_resource_handler property of LoadOptions to a handler: an object with an on_loading(args) method, or a function that takes args. The property is None by default.
For each external resource a document is about to load:
skip_external_resources and whitelisted_resources decide first, as described above.
The handler is called with an ExternalResourceLoadingArgs. Its uri property holds the reference, and skipped holds the decision from step 1.
The handler can keep that decision, set skipped to False to load the resource, set it to True to skip it, or set data to supply the resource’s content as bytes. When data is set and skipped is False, the document uses those bytes and no request is made for the resource; empty bytes supply empty content.
Allowing images by file type
The following handler loads JPEG images from one trusted host in addition to what the defaults allow. Everything else keeps the decision of step 1, so content the document carries still loads. On the two web pages of the previous example it loads the two JPEG pictures, the photo of the dock and the holiday opening hours, and leaves out the stylesheet and the logo, a PNG image:
fromurllib.parseimporturlsplitfromgroupdocs.mergerimportMergerfromgroupdocs.merger.domainimportFileTypefromgroupdocs.merger.domain.optionsimportLoadOptionsclassTrustedJpegHandler:defon_loading(self,args):try:uri=urlsplit(args.uri)exceptValueError:return# not a URL: keep the decision made so farif(uri.scheme=="https"and(uri.hostnameor"")=="docs.groupdocs.com"anduri.path.lower().endswith((".jpg",".jpeg"))):args.skipped=Falsedefallow_jpeg_images_by_handler():load_options=LoadOptions(FileType.HTML)load_options.external_resource_handler=TrustedJpegHandler()withMerger("./input.html",load_options)asmerger:merger.join("./input2.html")merger.save("./output.html")if__name__=="__main__":allow_jpeg_images_by_handler()
input.html is a sample file used in this example. Click here to download it.
input2.html is a sample file used in this example. Click here to download it.
The two pages link four files on docs.groupdocs.com, in the folder /merger/net/_sample_files/developer-guide/loading/skip-external-resources/: assets/portal.css, assets/logo.png, photos/north-pier-dock.jpg and assets/holiday-hours.jpg.
Check the location as well as the file type. A URL that ends in .jpg can point at any server, including http://169.254.169.254/image.jpg, and says nothing about the content it returns.
Supplying content and recording resources
The following handler supplies resources from content you have already downloaded and verified, and records the decision for every resource. The example gives it local copies of the stylesheet and the two pictures under assets/, so they load without a request, and the photo, which it does not have, stays denied:
fromgroupdocs.mergerimportMergerfromgroupdocs.merger.domainimportFileTypefromgroupdocs.merger.domain.optionsimportLoadOptions# The folder on docs.groupdocs.com that the two pages linkSITE="https://docs.groupdocs.com/merger/net/_sample_files/developer-guide/loading/skip-external-resources/"classPrefetchedResourceHandler:def__init__(self,prefetched):self._prefetched=prefetcheddefon_loading(self,args):content=self._prefetched.get(args.uri)ifcontentisnotNone:args.data=contentargs.skipped=Falseprint("{}: {}".format("skipped"ifargs.skippedelse"loaded",args.uri))defsupply_prefetched_resources():# The resources, downloaded and verified beforehand, by the URL the pages referenceprefetched={}fornamein("assets/portal.css","assets/logo.png","assets/holiday-hours.jpg"):withopen("./"+name,"rb")asf:prefetched[SITE+name]=f.read()load_options=LoadOptions(FileType.HTML)load_options.external_resource_handler=PrefetchedResourceHandler(prefetched)withMerger("./input.html",load_options)asmerger:merger.join("./input2.html")merger.save("./output.html")if__name__=="__main__":supply_prefetched_resources()
input.html is a sample file used in this example. Click here to download it.
input2.html is a sample file used in this example. Click here to download it.
For word processing, HTML and MHTML documents, uri is resolved against the document’s base, so it is the URL that would be requested. For other formats it can be the reference as the document carries it, so it can be relative.
The handler is also called for content the document carries, such as data: URIs and cid: parts, with skipped set to False. Skipping such a resource removes it from the output.
If the handler raises an exception, that resource is skipped, and the operation raises your exception.
The handler can be called from several threads at once, so it must be thread-safe.
A handler that allows everything reopens every request the defaults deny. Decide from the URI, never from content of the document being processed.
Loading all external resources
If you process only documents you trust, you can allow every external resource by setting skip_external_resources to False. Local files and UNC paths then load as well, the whitelist has no effect, and the document follows redirects. A handler, when set, is still called and can skip resources.
fromgroupdocs.mergerimportMergerfromgroupdocs.merger.domainimportFileTypefromgroupdocs.merger.domain.optionsimportLoadOptionsdefload_all_external_resources():# Only for documents you trust: every external resource loadsload_options=LoadOptions(FileType.DOCX)load_options.skip_external_resources=FalsewithMerger("./trusted-document.docx",load_options)asmerger:merger.join("./trusted-document2.docx")merger.save("./output.docx")if__name__=="__main__":load_all_external_resources()
trusted-document.docx is a sample file used in this example. Click here to download it.
trusted-document2.docx is a sample file used in this example. Click here to download it.
The two documents link three files on docs.groupdocs.com, in the folder /merger/net/_sample_files/developer-guide/loading/skip-external-resources/: assets/logo.png, photos/north-pier-dock.jpg and assets/holiday-hours.jpg.
Format-specific behaviour
EPUB, SVG and SVGZ documents
For EPUB documents, and for SVG and SVGZ documents in some operations, GroupDocs.Merger reads the document’s markup to find its external references before the document is processed. That markup must be well-formed XML. If it cannot be read, the operation raises GroupDocsMergerException (from groupdocs.merger.exceptions) with this message, which gives the .NET names of the options:
The document's markup could not be read to check it for external resources, so it was not loaded. Set SkipExternalResources to false without an ExternalResourceHandler to load it without the check.
To process such a document, set skip_external_resources to False and leave external_resource_handler unset; the markup is then not checked.
Embedded objects
The constructors of OleDiagramOptions, OleSpreadsheetOptions and OleWordProcessingOptions that take only a file path and a page number render the image of the embedded object when they are called, before any Merger exists. That image never shows the external resources the embedded document references, whatever the LoadOptions of the target document allow. See Import documents.