From 42aa8e176cebc2181c2ac9f25d90ceecfc95e8ed Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 3 Sep 2025 22:56:30 +0200 Subject: [PATCH] Adds output path validation for enhanced security Enhances security by validating output paths and executable paths. This prevents path traversal attacks and command injection vulnerabilities by ensuring that users can only specify valid relative paths within the vault and safe executable paths. It also displays notices when the path is deemed unsafe. --- main.ts | 34 +++++- src/core/SecurityUtils.ts | 131 ++++++++++++++++++++++++ src/ui/modal/sections/GeneralSection.ts | 7 +- 3 files changed, 167 insertions(+), 5 deletions(-) create mode 100644 src/core/SecurityUtils.ts diff --git a/main.ts b/main.ts index b29e30b..b46c279 100644 --- a/main.ts +++ b/main.ts @@ -22,6 +22,7 @@ import { import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS, ExportFormat } from './src/core/settings'; import { FALLBACK_FONTS, PLUGIN_DIRS } from './src/core/constants'; import { DependencyChecker } from './src/core/DependencyChecker'; +import { SecurityUtils } from './src/core/SecurityUtils'; import { ModalSettingsHelper } from './src/core/ModalSettingsHelper'; import { ExportErrorHandler } from './src/core/ExportErrorHandler'; import { TempDirectoryManager } from './src/core/TempDirectoryManager'; @@ -937,6 +938,11 @@ ${dependencyResult.allAvailable * Prepare the output path for a file */ private prepareOutputPath(file: TFile, outputFolder: string): string { + // Validate output folder for security + if (!SecurityUtils.validateOutputPath(outputFolder)) { + throw new Error(`Invalid output folder path: ${outputFolder}. Path contains invalid characters or traversal attempts.`); + } + const vaultPath = (this.app.vault.adapter as any).basePath; const outputDir = path.join(vaultPath, outputFolder); @@ -1045,6 +1051,10 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setPlaceholder('pandoc') .setValue(this.plugin.settings.pandocPath) .onChange(async (value) => { + if (!SecurityUtils.validateExecutablePath(value)) { + new Notice(`Invalid Pandoc path: ${SecurityUtils.getExecutablePathValidationError(value)}`); + return; + } this.plugin.settings.pandocPath = value; await this.plugin.saveSettings(); })); @@ -1056,6 +1066,10 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setPlaceholder('typst') .setValue(this.plugin.settings.typstPath) .onChange(async (value) => { + if (!SecurityUtils.validateExecutablePath(value)) { + new Notice(`Invalid Typst path: ${SecurityUtils.getExecutablePathValidationError(value)}`); + return; + } this.plugin.settings.typstPath = value; await this.plugin.saveSettings(); })); @@ -1067,6 +1081,10 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setPlaceholder('convert') .setValue(this.plugin.settings.executablePaths.imagemagickPath) .onChange(async (value) => { + if (!SecurityUtils.validateExecutablePath(value)) { + new Notice(`Invalid ImageMagick path: ${SecurityUtils.getExecutablePathValidationError(value)}`); + return; + } this.plugin.settings.executablePaths.imagemagickPath = value; await this.plugin.saveSettings(); })); @@ -1078,10 +1096,20 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setPlaceholder('/opt/homebrew/bin, /usr/local/bin') .setValue(this.plugin.settings.executablePaths.additionalPaths.join(', ')) .onChange(async (value) => { - this.plugin.settings.executablePaths.additionalPaths = value + const paths = value .split(',') .map(p => p.trim()) .filter(p => p.length > 0); + + // Validate each path + for (const pathItem of paths) { + if (!SecurityUtils.validateExecutablePath(pathItem)) { + new Notice(`Invalid system path: ${SecurityUtils.getExecutablePathValidationError(pathItem)}`); + return; + } + } + + this.plugin.settings.executablePaths.additionalPaths = paths; await this.plugin.saveSettings(); })); } @@ -1138,6 +1166,10 @@ class ObsidianTypstPDFExportSettingTab extends PluginSettingTab { .setPlaceholder('exports') .setValue(this.plugin.settings.outputFolder) .onChange(async (value) => { + if (!SecurityUtils.validateOutputPath(value)) { + new Notice(`Invalid output folder: ${SecurityUtils.getPathValidationError(value)}`); + return; + } this.plugin.settings.outputFolder = value; await this.plugin.saveSettings(); }); diff --git a/src/core/SecurityUtils.ts b/src/core/SecurityUtils.ts new file mode 100644 index 0000000..9816134 --- /dev/null +++ b/src/core/SecurityUtils.ts @@ -0,0 +1,131 @@ +/** + * Security utilities for path validation and sanitization + */ + +import * as path from 'path'; + +export class SecurityUtils { + /** + * Validates that an output folder path is safe and doesn't contain traversal attempts + * @param outputFolder The folder path to validate + * @returns true if the path is safe, false otherwise + */ + static validateOutputPath(outputFolder: string): boolean { + if (!outputFolder || typeof outputFolder !== 'string') { + return false; + } + + // Normalize and resolve the path to detect traversal attempts + const normalizedPath = path.normalize(outputFolder.trim()); + + // Check for path traversal attempts + if (normalizedPath.includes('..') || + normalizedPath.startsWith('/') || + normalizedPath.startsWith('\\') || + normalizedPath.includes('\x00')) { + return false; + } + + // Additional checks for suspicious patterns + const suspiciousPatterns = [ + /\.\./, // Directory traversal + /\/\//, // Double slashes + /[<>:"|?*]/, // Invalid filename characters + /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i // Windows reserved names + ]; + + return !suspiciousPatterns.some(pattern => pattern.test(normalizedPath)); + } + + /** + * Validates that an executable path is safe for use in shell commands + * @param executablePath The executable path to validate + * @returns true if the path is safe, false otherwise + */ + static validateExecutablePath(executablePath: string): boolean { + // Allow empty paths (will use system PATH) + if (!executablePath || executablePath.trim() === '') { + return true; + } + + const normalizedPath = path.normalize(executablePath.trim()); + + // Check for command injection attempts + const dangerousPatterns = [ + /[;&|`$(){}[\]]/, // Shell metacharacters + /\x00/, // Null bytes + /\n|\r/, // Newlines + /\s*[;&|]\s*/, // Command separators with whitespace + /\$\{.*\}/, // Variable substitution + /`.*`/, // Command substitution + /\$\(.*\)/ // Command substitution + ]; + + return !dangerousPatterns.some(pattern => pattern.test(normalizedPath)); + } + + /** + * Gets a human-readable error message for invalid paths + * @param outputFolder The invalid path + * @returns Description of why the path is invalid + */ + static getPathValidationError(outputFolder: string): string { + if (!outputFolder || typeof outputFolder !== 'string') { + return 'Output folder is required'; + } + + const normalizedPath = path.normalize(outputFolder.trim()); + + if (normalizedPath.includes('..')) { + return 'Path traversal attempts (..) are not allowed'; + } + if (normalizedPath.startsWith('/') || normalizedPath.startsWith('\\')) { + return 'Absolute paths are not allowed - use relative paths from vault root'; + } + if (normalizedPath.includes('\x00')) { + return 'Null bytes are not allowed in paths'; + } + if (/\/\//.test(normalizedPath)) { + return 'Double slashes are not allowed in paths'; + } + if (/[<>:"|?*]/.test(normalizedPath)) { + return 'Invalid characters found in path'; + } + if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(normalizedPath)) { + return 'Reserved system names are not allowed as folder names'; + } + + return 'Invalid path format'; + } + + /** + * Gets a human-readable error message for invalid executable paths + * @param executablePath The invalid executable path + * @returns Description of why the path is invalid + */ + static getExecutablePathValidationError(executablePath: string): string { + if (!executablePath || typeof executablePath !== 'string') { + return 'Executable path is required'; + } + + const normalizedPath = path.normalize(executablePath.trim()); + + if (/[;&|`$(){}[\]]/.test(normalizedPath)) { + return 'Shell metacharacters are not allowed in executable paths'; + } + if (/\x00/.test(normalizedPath)) { + return 'Null bytes are not allowed in paths'; + } + if (/\n|\r/.test(normalizedPath)) { + return 'Newlines are not allowed in paths'; + } + if (/\s*[;&|]\s*/.test(normalizedPath)) { + return 'Command separators are not allowed in executable paths'; + } + if (/\$\{.*\}/.test(normalizedPath) || /`.*`/.test(normalizedPath) || /\$\(.*\)/.test(normalizedPath)) { + return 'Command or variable substitution patterns are not allowed'; + } + + return 'Invalid executable path format'; + } +} \ No newline at end of file diff --git a/src/ui/modal/sections/GeneralSection.ts b/src/ui/modal/sections/GeneralSection.ts index e896214..ab73072 100644 --- a/src/ui/modal/sections/GeneralSection.ts +++ b/src/ui/modal/sections/GeneralSection.ts @@ -7,6 +7,7 @@ import { Setting, App } from 'obsidian'; import { ModalSection, ModalState, ValidationResult } from '../modalTypes'; import { ExportFormat } from '../../../core/settings'; import { FolderSuggest } from '../../components/FolderSuggest'; +import { SecurityUtils } from '../../../core/SecurityUtils'; export class GeneralSection implements ModalSection { private container: HTMLElement | null = null; @@ -101,10 +102,8 @@ export class GeneralSection implements ModalSection { // Validate output folder if (this.outputFolderInput) { const value = this.outputFolderInput.value.trim(); - if (!value) { - errors.push('Output folder is required'); - } else if (value.startsWith('/') || value.startsWith('\\')) { - warnings.push('Output folder should be relative to vault root'); + if (!SecurityUtils.validateOutputPath(value)) { + errors.push(SecurityUtils.getPathValidationError(value)); } }