Safer Document Processing
- 10 minutes to read
Workbooks from untrusted sources can contain content that requires excessive memory or processing time to load (for example, many cells or deeply nested XML elements). Workbooks can also contain unsafe content (for example, macros and links to external data) or hidden data that you do not want to share.
The Spreadsheet Document API allows you to process these workbooks in the following ways:
Limit Resources of a Load Operation
Use the LoadOptions.SecurityLoadingLimits property to specify security limits for a workbook load operation. The WorkbookSecurityLoadingLimits class contains the following limits:
| Property | Description |
|---|---|
| MaxFileSize | Gets or sets the maximum size of a loaded file in bytes. |
| MaxXmlElementDepth | Gets or sets the maximum nesting depth of XML elements in each XML file of a loaded document. |
| MaxXmlElementCount | Gets or sets the maximum number of XML elements in each XML file of a loaded document. |
| MaxWorksheetCount | Gets or sets the maximum number of worksheets in a loaded workbook. |
| MaxChartCount | Gets or sets the maximum number of charts in a loaded workbook. |
| MaxSheetCellCount | Gets or sets the maximum number of cells in each worksheet of a loaded workbook. |
| MaxSheetRowCount | Gets or sets the maximum number of rows in each worksheet of a loaded workbook. |
| MaxSheetColumnCount | Gets or sets the maximum number of column definitions in each worksheet of a loaded workbook. |
If a property is set to null, the corresponding limit does not apply.
If a loaded document exceeds a limit specified by a WorkbookSecurityLoadingLimits property, Workbook(stream, options) and Workbook(buffer, options) constructors throw a SecurityLoadingLimitExceededException. To log the violation and continue loading, set the LoadOptions.SecurityLoadingHandler property to a ISecurityLoadingHandler.
Remove Unsafe Content When You Load a Workbook
Use the LoadOptions.SecurityLoadingOptions property to specify content that the API removes when it loads a workbook. The WorkbookSecurityLoadingOptions class contains the following settings:
| Property | Description |
|---|---|
| RemoveMacros | Gets or sets whether to remove macros from a loaded document. |
| RemoveActiveXContent | Gets or sets whether to remove ActiveX controls from a loaded document. |
| RemoveOleObjects | Gets or sets whether to remove embedded OLE objects from a loaded document. |
| RemoveCustomXMLParts | Gets or sets whether to remove custom XML parts from a loaded document. |
| RemoveExternalImages | Gets or sets whether to remove references to external images from a loaded document. |
| RestrictedHyperlinkRemovalMode | Gets or sets how the API processes restricted hyperlinks in a loaded document. |
| RemovePivotCaches | Gets or sets whether to remove pivot caches from a loaded workbook. |
| RemoveRestrictedFormulas | Gets or sets whether to remove formulas that contain restricted functions from a loaded workbook. |
| RemoveExternalWorkbooks | Gets or sets whether to remove links to external workbooks from a loaded workbook. |
| RemoveExternalConnections | Gets or sets whether to remove external data connections from a loaded workbook. |
The following code snippet limits the file size and the number of worksheets, removes macros, external links, and restricted formulas when the API loads a workbook, and displays an error message in the console if the document exceeds a limit:
using System;
using System.IO;
using DevExpress.Docs;
using DevExpress.Docs.Spreadsheet;
LoadOptions loadOptions = new LoadOptions() {
SecurityLoadingLimits = new WorkbookSecurityLoadingLimits() {
MaxFileSize = 10 * 1024 * 1024,
MaxWorksheetCount = 50
},
SecurityLoadingOptions = new WorkbookSecurityLoadingOptions() {
RemoveMacros = true,
RemoveExternalWorkbooks = true,
RemoveExternalConnections = true,
RemoveRestrictedFormulas = true
}
};
try {
using FileStream stream = File.OpenRead("Document.xlsx");
using Workbook workbook = new Workbook(stream, loadOptions);
Console.WriteLine($"Loaded sheets: {workbook.Sheets.Count}");
}
catch (SecurityLoadingLimitExceededException e) {
Console.WriteLine(e.Message);
}
Handle Security Violations
To log security violations, load documents that exceed a limit, or keep content that a security loading option detects, implement the ISecurityLoadingHandler interface. Assign the implementation to the LoadOptions.SecurityLoadingHandler property.
The API calls the following methods of the ISecurityLoadingHandler implementation:
| Method | Call Condition | Return Value |
|---|---|---|
| HandleLimitExceeded | The document exceeds a limit specified by the SecurityLoadingLimits property. | SecurityLimitAction.Continue loads the entire document. SecurityLimitAction.Throw stops the load operation and throws a SecurityLoadingLimitExceededException. |
| HandleOptionsViolation | The document contains content that the SecurityLoadingOptions property specifies. | SecurityViolationAction.Remove removes the content. SecurityViolationAction.Keep keeps the content. |
The API calls the HandleLimitExceeded method once for each exceeded workbook limit (for example, MaxWorksheetCount or MaxChartCount). For a worksheet limit (MaxSheetCellCount, MaxSheetRowCount, or MaxSheetColumnCount), the API calls the HandleLimitExceeded method once for each worksheet that exceeds the limit.
The API calls the HandleOptionsViolation method once for each option that detects content. The PropertyName property of the parameters argument gets the name of the limit or option (for example, MaxSheetRowCount or RemoveMacros).
The following code snippet logs security violations to the console, loads the entire document if the document exceeds a limit, and removes detected macros:
using System;
using System.IO;
using DevExpress.Docs.Office;
using DevExpress.Docs.Spreadsheet;
LoadOptions loadOptions = new LoadOptions() {
SecurityLoadingLimits = new WorkbookSecurityLoadingLimits() { MaxWorksheetCount = 10 },
SecurityLoadingOptions = new WorkbookSecurityLoadingOptions() { RemoveMacros = true },
SecurityLoadingHandler = new SecurityViolationLogger()
};
using FileStream stream = File.OpenRead("Document.xlsx");
using Workbook workbook = new Workbook(stream, loadOptions);
class SecurityViolationLogger : ISecurityLoadingHandler {
public SecurityLimitAction HandleLimitExceeded(SecurityLimitExceededParams parameters) {
Console.WriteLine($"Limit exceeded: {parameters.PropertyName}");
return SecurityLimitAction.Continue;
}
public SecurityViolationAction HandleOptionsViolation(SecurityOptionsViolationParams parameters) {
Console.WriteLine($"Content removed: {parameters.PropertyName}");
return SecurityViolationAction.Remove;
}
}
Inspect a Workbook
Before you share or archive a workbook, call the Workbook.Inspect method to detect content that can pose security or privacy risks. The WorkbookInspectResult.ContentTypes property gets detected content types (WorkbookContentType).
The parameterless Inspect method detects all supported content types. To inspect specific content types, pass a combination of WorkbookInspectOptions flags to the Workbook.Inspect(options) method.
Note
The Inspect method does not modify the workbook. To remove detected content, pass the result of the WorkbookInspectResult.CreateSanitizeOptions() method to the Workbook.Sanitize(options) method.
A new workbook stores creation and modification dates. The Inspect method reports the dates as WorkbookContentType.DocumentHistory.
The following code snippet inspects a workbook, displays detected content types in the console, removes the detected content, and saves the workbook:
using System;
using System.IO;
using DevExpress.Docs.Spreadsheet;
Directory.CreateDirectory("output");
using FileStream inputStream = File.OpenRead("Document.xlsx");
using Workbook workbook = new Workbook(inputStream);
WorkbookInspectResult inspectResult = workbook.Inspect();
foreach (WorkbookContentType contentType in inspectResult.ContentTypes)
Console.WriteLine($"Detected: {contentType}");
// Remove the detected content.
WorkbookSanitizeOptions sanitizeOptions = inspectResult.CreateSanitizeOptions();
foreach (WorkbookSanitizeResult result in workbook.Sanitize(sanitizeOptions))
Console.WriteLine($"{result.Type}: {result.Action}");
using FileStream outputStream = File.Create(Path.Combine("output", "Document.xlsx"));
workbook.Save(outputStream);
Sanitize a Workbook
Call the Workbook.Sanitize method to remove unsafe and sensitive content from a loaded workbook.
The parameterless Sanitize method removes the following content:
- Document properties (metadata) and custom XML parts
- Comments and threaded comments
- Macros, ActiveX controls, and embedded OLE objects
- Hidden sheets, rows, and columns
- Invisible cell text (text that has the same color as the cell fill)
To keep specific content or make hidden content visible, pass a WorkbookSanitizeOptions object to the Workbook.Sanitize(options) method:
| Property | Description |
|---|---|
| Metadata | Gets or sets metadata categories that the API removes when it sanitizes a document. |
| RemoveComments | Gets or sets whether to remove comments when the API sanitizes a document. |
| RemoveThreadedComments | Gets or sets whether to remove threaded comments when the API sanitizes a workbook. |
| RemoveCustomXmlParts | Gets or sets whether to remove custom XML parts when the API sanitizes a document. |
| RemoveActiveXContent | Gets or sets whether to remove ActiveX controls when the API sanitizes a document. |
| RemoveMacros | Gets or sets whether to remove macros when the API sanitizes a document. |
| RemoveOleObjects | Gets or sets whether to remove embedded OLE objects when the API sanitizes a document. |
| HiddenSheets | Gets or sets how the API processes hidden sheets when it sanitizes a workbook. |
| HiddenRows | Gets or sets how the API processes hidden rows when it sanitizes a workbook. |
| HiddenColumns | Gets or sets how the API processes hidden columns when it sanitizes a workbook. |
| InvisibleCellText | Gets or sets how the API processes cell text that has the same color as the cell background. |
The Metadata property does not remove custom XML parts. To remove custom XML parts, use the RemoveCustomXmlParts property.
The Sanitize method returns a list that contains one WorkbookSanitizeResult item for each processed content type, regardless of the number of processed objects. If the workbook does not contain content of a specific type, the list does not contain an item for the type.
If the Sanitize method removes hidden rows or columns, the API deletes the rows or columns and shifts the remaining cells. Formulas that refer to removed sheets return #REF! errors.
Note
The Sanitize method does not check worksheet protection and removes hidden rows and columns from protected worksheets.
The following code snippet removes metadata, comments, macros, and embedded objects from a workbook, makes hidden sheets, rows, columns, and invisible cell text visible, displays sanitization results in the console, and saves the workbook:
using System;
using System.IO;
using DevExpress.Docs.Office;
using DevExpress.Docs.Spreadsheet;
Directory.CreateDirectory("output");
using FileStream inputStream = File.OpenRead("Document.xlsx");
using Workbook workbook = new Workbook(inputStream);
WorkbookSanitizeOptions options = new WorkbookSanitizeOptions() {
HiddenSheets = HiddenContentSanitizeMode.MakeVisible,
HiddenRows = HiddenContentSanitizeMode.MakeVisible,
HiddenColumns = HiddenContentSanitizeMode.MakeVisible,
InvisibleCellText = InvisibleContentSanitizeMode.MakeVisible
};
foreach (WorkbookSanitizeResult result in workbook.Sanitize(options))
Console.WriteLine($"{result.Type}: {result.Action}");
using FileStream outputStream = File.Create(Path.Combine("output", "Document.xlsx"));
workbook.Save(outputStream);