spotube icon indicating copy to clipboard operation
spotube copied to clipboard

some security flaws

Open s-b-repo opened this issue 2 weeks ago • 11 comments

Is there an existing issue for this? (Please read the description)

  • [x] I have searched the existing issues

Current Behavior

Windows Security Vulnerabilities Report

Critical Vulnerabilities

  1. Protocol Handler Command Injection (CRITICAL - CWE-78) Location: lib/collections/initializers.dart:6-26

Description: The registerWindowsScheme function registers a Windows protocol handler with unsanitized user input. The %1 parameter is directly inserted into the registry command string without validation or escaping.

Vulnerable Code: dart RegistryValue protocolCmdRegValue = RegistryValue( '', RegistryValueType.string, '"$appPath" "%1"', );

Exploitation:

  • An attacker could craft a malicious URL like spotify://test" & calc.exe & "
  • When Windows executes the protocol handler, it would run: "C:\path\to\spotube.exe" "test" & calc.exe & ""
  • The & operator in Windows command line allows command chaining, leading to arbitrary command execution

Impact: Remote Code Execution (RCE) when a user clicks a malicious protocol URL

Fix:

  • Validate and sanitize the %1 parameter before registration
  • Use proper escaping for Windows command line arguments
  • Consider using a safer protocol handler implementation that validates input
  1. Chocolatey Uninstall Script Command Injection (HIGH - CWE-78) Location: choco-struct/tools/chocolateyuninstall.ps1:14

Description: The uninstall script directly uses the UninstallString from the registry without validation, which could contain malicious commands.

Vulnerable Code:

$packageArgs['file'] = "$($_.UninstallString)"

Exploitation:

  • If an attacker can modify the registry entry for Spotube's uninstall string (requires admin or registry manipulation)
  • They could inject commands like: C:\path\to\uninstall.exe" & calc.exe & "
  • When Chocolatey runs the uninstall, it would execute the injected commands

Impact: Local Privilege Escalation or arbitrary command execution during uninstall

Fix:

  • Validate the UninstallString before using it
  • Use proper PowerShell escaping
  • Consider using Start-Process with proper argument handling

Medium Severity Vulnerabilities

  1. Command Injection in Build Script (MEDIUM - CWE-78) Location: cli/commands/build/windows.dart:18-19

Description: The build script uses shell.run with a path that could potentially be manipulated, though this is less critical as it's only used during build time.

Vulnerable Code: dart await shell.run( "git clone https://github.com/DomGries/InnoDependencyInstaller.git $innoDependencyPath", );

Exploitation:

  • If cwd.path is controlled by an attacker (unlikely but possible in CI/CD environments)
  • They could inject commands via path manipulation

Impact: Build-time command injection (limited impact)

Fix:

  • Validate cwd.path before using it
  • Use proper path sanitization
  • Consider using absolute paths or validating the path structure
  1. Unvalidated Command Line Arguments (MEDIUM - CWE-20) Location: windows/runner/utils.cpp:24-42 and lib/main.dart:58-65

Description: Command line arguments are passed directly to the Dart application without validation or sanitization.

Vulnerable Code: std::vectorstd::string GetCommandLineArguments() { // ... for (int i = 1; i < argc; i++) { command_line_arguments.push_back(Utf8FromUtf16(argv[i])); } return command_line_arguments; }

Exploitation:

  • Malicious arguments could be passed to the application
  • While the current CLI parser only handles --verbose, --version, and --help, future additions could be vulnerable
  • Protocol handler arguments are passed directly without validation

Impact: Potential for argument injection if new features are added that process arguments unsafely

Fix:

  • Implement strict validation of command line arguments
  • Whitelist allowed argument patterns
  • Sanitize protocol handler arguments before processing
  1. Path Traversal in File Operations (MEDIUM - CWE-22) Location: Multiple locations using file paths

Description: While ServiceUtils.sanitizeFilename exists, it's not consistently used everywhere, and some file operations may be vulnerable to path traversal.

Potential Vulnerable Areas:

  • lib/extensions/dio.dart:26 - Uses targetFile.uri.pathSegments.last without validation
  • lib/provider/local_tracks/local_tracks_provider.dart:78-81 - Recursive directory listing without path validation
  • File operations that use user-provided paths

Exploitation:

  • If user-controlled paths are used in file operations without proper sanitization
  • Paths like ../../../etc/passwd could access files outside intended directories

Impact: Unauthorized file access, potential information disclosure

Fix:

  • Always use ServiceUtils.sanitizeFilename or equivalent for user-provided paths
  • Validate paths are within allowed directories
  • Use path.resolve() or equivalent to normalize paths before use

Low Severity / Informational

  1. Missing Input Validation in Protocol Handler Registration Location: lib/collections/initializers.dart:6

Description: The scheme parameter is not validated before being used in registry key creation.

Vulnerable Code: String protocolRegKey = 'Software\Classes\$scheme';

Exploitation:

  • Malicious scheme names could potentially manipulate registry structure
  • However, this requires code execution to call the function

Impact: Low - requires code execution to exploit

Fix:

  • Validate scheme names against a whitelist
  • Sanitize scheme names to prevent registry manipulation
  1. Unsafe String Replacement in Build Scripts Location: cli/commands/build/windows.dart:35-36, 48-60

Description: String replacements use replaceAll without validation, which could be exploited if version strings contain special characters.

Vulnerable Code: final newContent = content.replaceAll(versionVarRegExp, versionWithoutBuildNumber);

Impact: Low: version strings are typically controlled, but could be exploited in CI/CD

Fix:

  • Validate version strings before replacement
  • Use more specific regex patterns

Recommendations

  1. Immediate Actions:

    • Fix the protocol handler command injection (Vulnerability 1) - this is the most critical
    • Fix the Chocolatey uninstall script (Vulnerability 2)
    • Implement input validation for all user-controlled data
  2. Security Best Practices:

    • Implement a security review process for all Windows-specific code
    • Add automated security testing for protocol handlers
    • Use parameterized commands instead of string concatenation
    • Implement proper input validation and sanitization throughout
  3. Code Review Focus Areas:

    • All protocol handler implementations
    • All command execution points (shell.run, Process.run, etc.)
    • All file path operations
    • All registry operations
  4. Testing:

    • Test protocol handler with malicious URLs
    • Test uninstall scripts with manipulated registry entries
    • Test file operations with path traversal attempts
    • Test command line argument processing with malicious input

References

  • CWE-78: OS Command Injection
  • CWE-20: Improper Input Validation
  • CWE-22: Path Traversal
  • OWASP Top 10: A03:2021 – Injection

Expected Behavior

N/A

Steps to reproduce

N/A

Logs

N/A

Operating System

windows

Spotube version

latest

Installation source

GitHub Releases (Binary)

Additional information

No response

Self grab

  • [ ] I'm ready to work on this issue!

s-b-repo avatar Dec 08 '25 07:12 s-b-repo

Runner Files Security Audit Report Comprehensive Multi-Step Security Analysis

Audit Methodology

This audit follows a systematic approach examining each runner file for:

  1. Command injection vulnerabilities
  2. Buffer overflow risks
  3. Path traversal issues
  4. Input validation problems
  5. Unsafe API usage
  6. Memory safety issues
  7. Privilege escalation risks
  8. DLL hijacking vulnerabilities
  9. String handling security
  10. Window message handling security

WINDOWS RUNNER FILES

  1. windows/runner/main.cpp

File Analysis: Entry point for Windows application

Vulnerabilities Found:

VULN-001: Unvalidated Command Line Arguments (MEDIUM)

  • Location: Lines 22-24
  • Code:

std::vectorstd::string command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments));

  • Issue: Command line arguments are passed directly to Dart without validation
  • Impact: Potential argument injection if Dart code processes arguments unsafely
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Implement argument validation/whitelisting before passing to Dart

VULN-002: COM Initialization Without Security Context (LOW)

  • Location: Line 18
  • Code: ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  • Issue: COM initialized without explicit security context
  • Impact: Low - standard practice, but could be more secure
  • CWE: CWE-276 (Incorrect Default Permissions)
  • Recommendation: Consider using COINIT_DISABLE_OLE1DDE flag for additional security

VULN-003: Hardcoded Window Title (INFORMATIONAL)

  • Location: Line 29
  • Code: window.CreateAndShow(L"spotube", origin, size);
  • Issue: Window title is hardcoded, but used in SendAppLinkToInstance for window finding
  • Impact: Low - could be exploited for window spoofing if title matching is used for security
  • Recommendation: Ensure window title matching doesn't have security implications
  1. windows/runner/utils.cpp and utils.h

File Analysis: Utility functions for console and command line handling

Vulnerabilities Found:

VULN-004: Unsafe freopen_s Error Handling (MEDIUM)

  • Location: Lines 13-17
  • Code:

if (freopen_s(&unused, "CONOUT$", "w", stdout)) { _dup2(_fileno(stdout), 1); } if (freopen_s(&unused, "CONOUT$", "w", stderr)) { _dup2(_fileno(stdout), 2); }

  • Issue: Error from freopen_s is checked but _dup2 is called unconditionally, potentially duplicating invalid file descriptors
  • Impact: Medium - could lead to console redirection failures
  • CWE: CWE-252 (Unchecked Return Value)
  • Recommendation: Only call _dup2 if freopen_s succeeds

VULN-005: Command Line Argument Injection Risk (HIGH)

  • Location: Lines 24-42
  • Code:

std::vectorstd::string GetCommandLineArguments() { int argc; wchar_t argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); // ... for (int i = 1; i < argc; i++) { command_line_arguments.push_back(Utf8FromUtf16(argv[i])); } return command_line_arguments; }

  • Issue: Arguments are converted but not validated or sanitized
  • Impact: High - malicious arguments could be passed to Dart code
  • CWE: CWE-20 (Improper Input Validation), CWE-78 (OS Command Injection)
  • Exploitation: An attacker could craft malicious command line arguments that, when processed by Dart code, could lead to command injection
  • Recommendation:
    • Validate argument length limits
    • Sanitize special characters
    • Implement argument whitelisting
    • Add bounds checking

VULN-006: Potential Buffer Overflow in UTF-16 to UTF-8 Conversion (MEDIUM)

  • Location: Lines 44-64
  • Code:

std::string Utf8FromUtf16(const wchar_t* utf16_string) { // ... utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, utf8_string.data(), target_length, nullptr, nullptr);

  • Issue: While resize is used, there's no validation of target_length before allocation
  • Impact: Medium - extremely large strings could cause memory exhaustion
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation: Add maximum length validation before allocation

VULN-007: Memory Leak Risk (LOW)

  • Location: Line 39
  • Code: ::LocalFree(argv);
  • Issue: LocalFree is called, but if an exception occurs before this point, memory could leak
  • Impact: Low - modern C++ exception handling should prevent this
  • CWE: CWE-401 (Missing Release of Resource)
  • Recommendation: Use RAII wrapper or smart pointer for argv
  1. windows/runner/flutter_window.cpp and flutter_window.h

File Analysis: Flutter window wrapper implementation

Vulnerabilities Found:

VULN-008: Unvalidated Window Message Handling (MEDIUM)

  • Location: Lines 40-61
  • Code:

LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (flutter_controller_) { std::optional<LRESULT> result = flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, lparam); if (result) { return *result; } } // ... }

  • Issue: Window messages are passed to Flutter without validation
  • Impact: Medium - malicious window messages could potentially exploit Flutter engine vulnerabilities
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate message types and parameters before passing to Flutter

VULN-009: Missing Window Handle Validation (LOW)

  • Location: Multiple locations
  • Issue: Window handles are used without null checks in some paths
  • Impact: Low - would cause crashes rather than security issues
  • CWE: CWE-476 (NULL Pointer Dereference)
  • Recommendation: Add null checks where appropriate
  1. windows/runner/win32_window.cpp and win32_window.h

File Analysis: Core Win32 window management

Vulnerabilities Found:

VULN-010: DLL Hijacking Risk (HIGH)

  • Location: Line 26
  • Code:

HMODULE user32_module = LoadLibraryA("User32.dll");

  • Issue: LoadLibraryA without full path could be vulnerable to DLL hijacking if current directory is in PATH
  • Impact: High - attacker could place malicious DLL in current directory
  • CWE: CWE-427 (Uncontrolled Search Path Element)
  • Exploitation: If an attacker can control the current working directory or place a malicious User32.dll in a directory searched before system32, code execution could occur
  • Recommendation:
    • Use LoadLibraryEx with LOAD_LIBRARY_SEARCH_SYSTEM32 flag
    • Or use full path to system DLL
    • Or use GetSystemDirectory to get system path

VULN-011: Unsafe Window Handle Casting (MEDIUM)

  • Location: Lines 143-147
  • Code:

auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam); SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams)); auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);

  • Issue: lpCreateParams is cast without validation
  • Impact: Medium - if lpCreateParams is malicious, could lead to use-after-free or type confusion
  • CWE: CWE-704 (Incorrect Type Conversion)
  • Recommendation: Validate pointer before casting

VULN-012: Window Title Injection in SendAppLinkToInstance (MEDIUM)

  • Location: Lines 253-286
  • Code:

bool Win32Window::SendAppLinkToInstance(const std::wstring& title) { HWND hwnd = ::FindWindow(kWindowClassName, title.c_str()); // ... SendAppLink(hwnd); // ... }

  • Issue: Window title is used to find window, but SendAppLink is called with the found window handle without additional validation
  • Impact: Medium - if window title matching is bypassed or if multiple windows exist, wrong window could receive link
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation:
    • Validate window handle belongs to current process
    • Add additional checks before sending link
    • Consider using window property or atom instead of title matching

VULN-013: Privilege Escalation via SetForegroundWindow (LOW)

  • Location: Line 278
  • Code: SetForegroundWindow(hwnd);
  • Issue: SetForegroundWindow can be used to steal focus from other applications
  • Impact: Low - annoyance/UX issue, not a security vulnerability per se
  • CWE: N/A
  • Recommendation: Consider using AllowSetForegroundWindow with proper process ID

VULN-014: Unvalidated Window Placement Structure (LOW)

  • Location: Lines 262-275
  • Code:

WINDOWPLACEMENT place = { sizeof(WINDOWPLACEMENT) }; GetWindowPlacement(hwnd, &place); switch(place.showCmd) { // ... }

  • Issue: GetWindowPlacement return value not checked
  • Impact: Low - could use uninitialized data if call fails
  • CWE: CWE-252 (Unchecked Return Value)
  • Recommendation: Check return value before using structure

VULN-015: Potential Integer Overflow in Scale Function (LOW)

  • Location: Lines 19-21
  • Code:

int Scale(int source, double scale_factor) { return static_cast(source * scale_factor); }

  • Issue: Multiplication could overflow before cast to int
  • Impact: Low - would cause incorrect window sizing, not security issue
  • CWE: CWE-190 (Integer Overflow)
  • Recommendation: Add bounds checking
  1. windows/runner/Runner.rc

File Analysis: Windows resource file with version information

Vulnerabilities Found:

VULN-016: Template Injection in Version Strings (MEDIUM)

  • Location: Lines 66, 72

  • Code: rc define VERSION_AS_NUMBER %{{SPOTUBE_VERSION_AS_NUMBER}}% define VERSION_AS_STRING "%{{SPOTUBE_VERSION}}%"

  • Issue: Version strings are replaced via template substitution without validation

  • Impact: Medium - if build process is compromised, malicious version strings could be injected

  • CWE: CWE-94 (Code Injection)

  • Recommendation:

    • Validate version strings match expected format
    • Sanitize version strings before substitution
    • Use build-time validation
  1. windows/runner/runner.exe.manifest

File Analysis: Application manifest for Windows

Vulnerabilities Found:

VULN-017: Missing Requested Execution Level (MEDIUM)

  • Location: Entire file
  • Issue: Manifest doesn't specify requestedExecutionLevel, defaults to asInvoker
  • Impact: Medium - application might request elevation unnecessarily, or fail to request when needed
  • CWE: CWE-250 (Execution with Unnecessary Privileges)
  • Recommendation: Explicitly set requestedExecutionLevel to asInvoker or highestAvailable as appropriate

VULN-018: Missing UAC Shield Icon Configuration (LOW)

  • Location: Entire file
  • Issue: No UAC configuration specified
  • Impact: Low - UX issue
  • CWE: N/A
  • Recommendation: Add explicit UAC configuration if elevation is needed
  1. windows/runner/CMakeLists.txt

File Analysis: Build configuration

Vulnerabilities Found:

VULN-019: No Security Compiler Flags (LOW)

  • Location: Entire file
  • Issue: No security-hardening compiler flags specified
  • Impact: Low - missing security features like ASLR, DEP, stack canaries
  • CWE: CWE-1204 (Generation of Weak Initialization Vector)
  • Recommendation: Add security flags:
    • /GS (Stack canaries)
    • /DYNAMICBASE (ASLR)
    • /NXCOMPAT (DEP)
    • /GUARD:CF (Control Flow Guard)

LINUX RUNNER FILES

  1. linux/main.cc

File Analysis: Linux application entry point

Vulnerabilities Found:

VULN-020: Unvalidated Command Line Arguments (MEDIUM)

  • Location: Lines 3-6
  • Code:

int main(int argc, char argv) { g_autoptr(MyApplication) app = my_application_new(); return g_application_run(G_APPLICATION(app), argc, argv); }

  • Issue: Command line arguments passed directly to GTK application without validation
  • Impact: Medium - GTK handles arguments, but no application-level validation
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Add argument validation before passing to GTK
  1. linux/my_application.cc and my_application.h

File Analysis: GTK application implementation

Vulnerabilities Found:

VULN-021: Command Line Argument Injection (MEDIUM)

  • Location: Lines 74-92
  • Code:

static gboolean my_application_local_command_line(GApplication* application, gchar* arguments, int* exit_status) { MyApplication* self = MY_APPLICATION(application); // Strip out the first argument as it is the binary name. self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); // ... }

  • Issue: Arguments are duplicated and passed to Dart without validation
  • Impact: Medium - malicious arguments could be injected into Dart code
  • CWE: CWE-20 (Improper Input Validation), CWE-78 (OS Command Injection)
  • Recommendation:
    • Validate argument count and length
    • Sanitize arguments before passing to Dart
    • Implement argument whitelisting

VULN-022: Environment Variable Injection (LOW)

  • Location: Lines 110-116
  • Code:

bool is_flatpak(void) { if (getenv("container") || getenv("FLATPAK_ID") || getenv("FLATPAK")) { return true; } return false; }

  • Issue: Environment variables are read without validation
  • Impact: Low - environment variables could be manipulated, but only affects Flatpak detection
  • CWE: CWE-807 (Reliance on Untrusted Inputs in a Security Decision)
  • Recommendation: Validate environment variable values match expected format

VULN-023: Window Manager Name Injection (LOW)

  • Location: Lines 38-45
  • Code:

ifdef GDK_WINDOWING_X11 GdkScreen* screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); if (g_strcmp0(wm_name, "GNOME Shell") != 0) { use_header_bar = FALSE; } } endif

  • Issue: Window manager name is compared but not validated
  • Impact: Low - could affect UI rendering, not a security issue
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate window manager name format

VULN-024: Memory Management Issue (LOW)

  • Location: Line 79
  • Code: self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
  • Issue: Memory is allocated but only freed in dispose, could leak on error paths
  • Impact: Low - GLib handles cleanup, but explicit error handling would be better
  • CWE: CWE-401 (Missing Release of Resource)
  • Recommendation: Ensure cleanup on all error paths

macOS RUNNER FILES

  1. macos/Runner/AppDelegate.swift

File Analysis: macOS application delegate

Vulnerabilities Found:

VULN-025: Missing Security Hardening (LOW)

  • Location: Entire file
  • Issue: No explicit security configurations
  • Impact: Low - relies on default macOS security
  • CWE: CWE-250 (Execution with Unnecessary Privileges)
  • Recommendation: Review entitlements and add explicit security configurations

VULN-026: Secure Restorable State (INFORMATIONAL)

  • Location: Lines 10-12
  • Code:

override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { return true }

  • Issue: Secure restorable state is enabled (good)
  • Impact: None - this is a security feature
  • Recommendation: Keep enabled
  1. macos/Runner/MainFlutterWindow.swift

File Analysis: Main window implementation

Vulnerabilities Found:

VULN-027: Missing Input Validation (LOW)

  • Location: Lines 6-15
  • Issue: Window initialization doesn't validate frame or view controller
  • Impact: Low - would cause crashes, not security issues
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Add validation checks

SUMMARY OF CRITICAL FINDINGS

Critical/High Severity:

  1. VULN-005: Command Line Argument Injection Risk (Windows utils.cpp)
  2. VULN-010: DLL Hijacking Risk (Windows win32_window.cpp)
  3. VULN-012: Window Title Injection in SendAppLinkToInstance (Windows win32_window.cpp)

Medium Severity:

  1. VULN-001: Unvalidated Command Line Arguments (Windows main.cpp)
  2. VULN-004: Unsafe freopen_s Error Handling (Windows utils.cpp)
  3. VULN-006: Potential Buffer Overflow in UTF Conversion (Windows utils.cpp)
  4. VULN-008: Unvalidated Window Message Handling (Windows flutter_window.cpp)
  5. VULN-011: Unsafe Window Handle Casting (Windows win32_window.cpp)
  6. VULN-016: Template Injection in Version Strings (Windows Runner.rc)
  7. VULN-017: Missing Requested Execution Level (Windows manifest)
  8. VULN-020: Unvalidated Command Line Arguments (Linux main.cc)
  9. VULN-021: Command Line Argument Injection (Linux my_application.cc)

Low Severity:

  • Multiple low-severity issues related to error handling, memory management, and input validation

RECOMMENDATIONS

Immediate Actions:

  1. Fix DLL Hijacking (VULN-010): Use LoadLibraryEx with LOAD_LIBRARY_SEARCH_SYSTEM32
  2. Validate Command Line Arguments (VULN-005, VULN-021): Implement strict validation and sanitization
  3. Fix Window Title Injection (VULN-012): Add additional validation before sending app links

Short-term Actions:

  1. Add security compiler flags to CMakeLists.txt
  2. Implement argument validation in all entry points
  3. Add proper error handling throughout
  4. Fix unsafe pointer casts

Long-term Actions:

  1. Implement comprehensive input validation framework
  2. Add security testing for all runner code
  3. Regular security audits
  4. Code review process for all native code changes

TESTING RECOMMENDATIONS

  1. Fuzzing: Fuzz command line arguments, window messages, and file paths
  2. Penetration Testing: Test DLL hijacking scenarios
  3. Static Analysis: Use tools like Clang Static Analyzer, PVS-Studio
  4. Dynamic Analysis: Use AddressSanitizer, Valgrind
  5. Security Code Review: Regular reviews of native code

REFERENCES

  • CWE-20: Improper Input Validation
  • CWE-78: OS Command Injection
  • CWE-94: Code Injection
  • CWE-252: Unchecked Return Value
  • CWE-276: Incorrect Default Permissions
  • CWE-400: Uncontrolled Resource Consumption
  • CWE-401: Missing Release of Resource
  • CWE-427: Uncontrolled Search Path Element
  • CWE-476: NULL Pointer Dereference
  • CWE-704: Incorrect Type Conversion
  • CWE-807: Reliance on Untrusted Inputs in a Security Decision Audit Date: Current Severity Levels: Critical/High/Medium/Low/Informational

s-b-repo avatar Dec 08 '25 07:12 s-b-repo

Hooks Directory Security Audit Report Comprehensive Multi-Step Security Analysis

Audit Methodology

This audit follows a systematic approach examining each hook file for:

  1. Command injection vulnerabilities
  2. Path traversal issues
  3. Input validation problems
  4. Unsafe file operations
  5. URL/URI handling security
  6. Permission handling issues
  7. Memory leaks and resource management
  8. Race conditions
  9. XSS vulnerabilities
  10. Unsafe async operations

CONFIGURATOR HOOKS

  1. lib/hooks/configurators/use_check_yt_dlp_installed.dart

File Analysis: Checks if yt-dlp is installed and shows dialog if not

Vulnerabilities Found:

VULN-H001: Path Traversal in Custom Path Validation (HIGH)

  • Location: Lines 23-29
  • Code:

final customPath = KVStoreService.getYoutubeEnginePath(YoutubeClientEngine.ytDlp);

if (youtubeEngine == YoutubeClientEngine.ytDlp && !await YtDlpEngine.isInstalled() && (customPath == null || !await File(customPath).exists()) && context.mounted) {

  • Issue: customPath from KVStoreService is used directly in File() constructor without validation
  • Impact: High - Path traversal could allow accessing arbitrary files or executing malicious executables
  • CWE: CWE-22 (Path Traversal), CWE-73 (External Control of File Name or Path)
  • Exploitation:
    • If KVStoreService is compromised or returns a malicious path like ../../../etc/passwd or C:\Windows\System32\cmd.exe
    • The file existence check could be used to probe the filesystem
    • If the path is later used to execute yt-dlp, command injection could occur
  • Recommendation:
    • Validate customPath against whitelist of allowed directories
    • Normalize and resolve path before use
    • Check path doesn't contain .. or absolute path escapes
    • Validate file extension matches expected executable format
    • Use path package's normalize() and isAbsolute() checks

VULN-H002: Missing Path Sanitization (MEDIUM)

  • Location: Line 28
  • Code: !await File(customPath).exists()
  • Issue: File existence check doesn't validate path format
  • Impact: Medium - Could be used for information disclosure about filesystem structure
  • CWE: CWE-200 (Information Exposure)
  • Recommendation: Add path validation before file operations
  1. lib/hooks/configurators/use_close_behavior.dart

File Analysis: Handles application close behavior (minimize to tray vs exit)

Vulnerabilities Found:

VULN-H003: Unsafe exit() Call (MEDIUM)

  • Location: Lines 21, 32
  • Code:

..onClickAction = (value) { exit(0); } // ... } else { exit(0); }

  • Issue: exit(0) is called without cleanup or proper resource disposal
  • Impact: Medium - Could lead to resource leaks, unsaved data loss, or incomplete cleanup
  • CWE: CWE-404 (Improper Resource Shutdown or Release)
  • Recommendation:
    • Use proper application lifecycle management
    • Ensure cleanup handlers are called before exit
    • Consider using SystemNavigator.pop() on mobile or proper window close on desktop
    • Add cleanup hooks before exit

VULN-H004: Notification Action Injection (LOW)

  • Location: Lines 20-22
  • Code:

..onClickAction = (value) { exit(0); }

  • Issue: Notification action value is not validated before use
  • Impact: Low - If notification action value is used elsewhere, could be exploited
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate notification action values
  1. lib/hooks/configurators/use_deep_linking.dart

File Analysis: Handles deep linking (currently deprecated and commented out)

Vulnerabilities Found:

VULN-H005: Commented Out Code with Security Issues (INFORMATIONAL)

  • Location: Lines 22-107 (commented code)
  • Code: Multiple commented sections with URL parsing and navigation
  • Issue: Commented code contains security vulnerabilities that could be re-enabled
  • Impact: Informational - Code is disabled but vulnerabilities exist if re-enabled
  • CWE: CWE-506 (Embedded Malicious Code)
  • Vulnerabilities in commented code:
    • Line 26: Uri.parse(file.value!) - No validation of file.value
    • Line 68: uri.split(":") - String splitting without validation
    • Line 39, 49, 81, 84: Direct use of url.pathSegments.last and endSegment without validation
    • Line 33, 44, 75, 88: API calls with unvalidated IDs
  • Recommendation:
    • Remove commented code if not needed
    • If re-enabling, implement proper URL validation
    • Validate all path segments and IDs
    • Sanitize user input before API calls
    • Implement URL scheme whitelist

VULN-H006: Deprecated Function Still Exported (LOW)

  • Location: Line 18
  • Issue: Function is marked deprecated but still callable
  • Impact: Low - Could be accidentally used, leading to security issues
  • CWE: CWE-477 (Use of Obsolete Function)
  • Recommendation: Remove function entirely or add runtime warnings
  1. lib/hooks/configurators/use_disable_battery_optimizations.dart

File Analysis: Requests battery optimization permissions

Vulnerabilities Found:

VULN-H007: Hardcoded User-Facing Strings (LOW)

  • Location: Lines 15-16
  • Code:

"Your device has additional battery optimization", "Follow the steps and disable the optimizations to allow smooth functioning of this app",

  • Issue: Hardcoded strings could be used for social engineering if modified
  • Impact: Low - Not a security vulnerability per se, but could be exploited if code is modified
  • CWE: N/A
  • Recommendation: Move strings to localization files

VULN-H008: Missing Error Handling (LOW)

  • Location: Lines 11-17
  • Issue: No error handling for permission request failures
  • Impact: Low - Could lead to silent failures
  • CWE: CWE-252 (Unchecked Return Value)
  • Recommendation: Add try-catch and error logging
  1. lib/hooks/configurators/use_endless_playback.dart

File Analysis: Implements endless playback by adding radio tracks

Vulnerabilities Found:

VULN-H009: Unvalidated Track ID Usage (MEDIUM)

  • Location: Line 27
  • Code:

final tracks = await (await metadataPlugin)?.track.radio(track.id);

  • Issue: track.id is used directly in API call without validation
  • Impact: Medium - Malicious track ID could lead to API abuse or injection
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation:
    • Validate track ID format
    • Sanitize track ID before API call
    • Add rate limiting for radio requests

VULN-H010: Race Condition in Playlist Access (MEDIUM)

  • Location: Lines 22-23, 34-35
  • Code:

final playlist = ref.read(audioPlayerProvider); if (index != playlist.tracks.length - 1) return; // ... final playlist = ref.read(audioPlayerProvider); final isDuplicate = playlist.tracks.any((t) => t.id == e.id);

  • Issue: Playlist is read multiple times without synchronization
  • Impact: Medium - Race condition could lead to incorrect behavior or duplicate tracks
  • CWE: CWE-362 (Concurrent Execution using Shared Resource with Improper Synchronization)
  • Recommendation:
    • Use consistent state snapshot
    • Add synchronization mechanisms
    • Consider using ref.watch for reactive updates

VULN-H011: Missing Error Handling for Metadata Plugin (LOW)

  • Location: Line 27
  • Code: await (await metadataPlugin)?.track.radio(track.id);
  • Issue: If metadataPlugin fails, error is caught but not properly handled
  • Impact: Low - Silent failures could affect user experience
  • CWE: CWE-703 (Improper Check or Handling of Exceptional Conditions)
  • Recommendation: Add specific error handling and user feedback
  1. lib/hooks/configurators/use_fix_window_stretching.dart

File Analysis: Fixes window stretching issue on Windows

Vulnerabilities Found:

VULN-H012: Potential Integer Overflow (LOW)

  • Location: Lines 12-14
  • Code:

windowManager.getSize().then((Size value) { windowManager.setSize( Size(value.width + 1, value.height + 1), ); });

  • Issue: No bounds checking before adding 1 to window size
  • Impact: Low - Could cause window size issues, not a security vulnerability
  • CWE: CWE-190 (Integer Overflow or Wraparound)
  • Recommendation: Add bounds checking

VULN-H013: Race Condition in Window Size Operations (LOW)

  • Location: Lines 11-15
  • Issue: Async operations without proper sequencing could cause race conditions
  • Impact: Low - Window sizing issues, not security
  • CWE: CWE-362 (Concurrent Execution using Shared Resource with Improper Synchronization)
  • Recommendation: Use await/async properly or add synchronization
  1. lib/hooks/configurators/use_get_storage_perms.dart

File Analysis: Requests storage permissions on Android/iOS

Vulnerabilities Found:

VULN-H014: Permission Request Without User Context (MEDIUM)

  • Location: Lines 27, 31, 41
  • Code:

await Permission.storage.request(); // ... await Permission.audio.request();

  • Issue: Permissions are requested automatically without explicit user action
  • Impact: Medium - Could be seen as intrusive or lead to permission fatigue
  • CWE: CWE-250 (Execution with Unnecessary Privileges)
  • Recommendation:
    • Request permissions only when needed
    • Show explanation dialogs before requesting
    • Allow users to dismiss permission requests

VULN-H015: Missing Permission Status Validation (LOW)

  • Location: Lines 18-24
  • Issue: Permission status checks don't validate all possible states
  • Impact: Low - Could miss edge cases
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Handle all permission states explicitly

VULN-H016: Device Info Without Validation (LOW)

  • Location: Line 16
  • Code: final androidInfo = await DeviceInfoPlugin().androidInfo;
  • Issue: Device info is used without validation
  • Impact: Low - Malicious device info could affect behavior, but unlikely
  • CWE: CWE-807 (Reliance on Untrusted Inputs in a Security Decision)
  • Recommendation: Validate device info values
  1. lib/hooks/configurators/use_has_touch.dart

File Analysis: Detects touch input capability

Vulnerabilities Found:

VULN-H017: Global Pointer Router Registration (LOW)

  • Location: Lines 17-19, 21-23
  • Code:

GestureBinding.instance.pointerRouter.addGlobalRoute(globalRoute); // ... GestureBinding.instance.pointerRouter.removeGlobalRoute(globalRoute);

  • Issue: Global route registration could interfere with other gesture handlers
  • Impact: Low - UX issue, not security
  • CWE: CWE-665 (Improper Initialization)
  • Recommendation: Use scoped gesture detection if possible

No Critical Security Issues Found

  1. lib/hooks/configurators/use_window_listener.dart

File Analysis: Window event listener wrapper

Vulnerabilities Found:

VULN-H018: Unvalidated Window Event Name (LOW)

  • Location: Line 80
  • Code:

@override void onWindowEvent(String eventName) { return _onWindowEvent?.call(); }

  • Issue: eventName parameter is received but not used or validated
  • Impact: Low - Could be used for logging or validation in future
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate event names against whitelist if used

VULN-H019: Callback Injection Risk (LOW)

  • Location: Lines 140-200
  • Issue: Callbacks are passed directly without validation
  • Impact: Low - If callbacks come from untrusted sources, could be exploited
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate callback sources

No Critical Security Issues Found

CONTROLLER HOOKS

  1. lib/hooks/controllers/use_auto_scroll_controller.dart

File Analysis: Auto-scroll controller hook

Vulnerabilities Found:

No Security Issues Found - This is a wrapper around a third-party controller with no security implications.

  1. lib/hooks/controllers/use_package_info.dart

File Analysis: Package info hook

Vulnerabilities Found:

VULN-H020: Hardcoded Default Values (LOW)

  • Location: Lines 7, 10, 13, 16
  • Code: Default values like 'Unknown' for package info
  • Issue: Hardcoded defaults could mask missing information
  • Impact: Low - Information disclosure issue
  • CWE: CWE-200 (Information Exposure)
  • Recommendation: Use null values instead of 'Unknown' strings

VULN-H021: Async State Update Race Condition (LOW)

  • Location: Lines 65-70
  • Code:

@override void initHook() { PackageInfo.fromPlatform().then((packageInfo) { setState(() { info = packageInfo; }); }); super.initHook(); }

  • Issue: Async update could occur after widget disposal
  • Impact: Low - Could cause memory leaks or state updates on disposed widgets
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation: Check mounted before setState or use proper lifecycle management
  1. lib/hooks/controllers/use_shadcn_text_editing_controller.dart

File Analysis: Text editing controller hook

Vulnerabilities Found:

No Security Issues Found - Standard Flutter hook implementation with no security implications.

UTILITY HOOKS

  1. lib/hooks/utils/use_async_effect.dart

File Analysis: Async effect hook wrapper

Vulnerabilities Found:

VULN-H022: Missing Error Handling (MEDIUM)

  • Location: Lines 10-16
  • Code:

useEffect(() { Future.microtask(effect); return () { if (cleanup != null) { Future.microtask(cleanup); } }; }, keys);

  • Issue: No error handling for async operations
  • Impact: Medium - Unhandled exceptions could crash the app or cause undefined behavior
  • CWE: CWE-703 (Improper Check or Handling of Exceptional Conditions)
  • Recommendation:
    • Wrap async operations in try-catch
    • Add error logging
    • Consider using Future.catchError()

VULN-H023: Cleanup Execution Without Error Handling (LOW)

  • Location: Lines 13-15
  • Issue: Cleanup function execution has no error handling
  • Impact: Low - Cleanup failures could leave resources in inconsistent state
  • CWE: CWE-703 (Improper Check or Handling of Exceptional Conditions)
  • Recommendation: Add error handling for cleanup operations
  1. lib/hooks/utils/use_breakpoint_value.dart

File Analysis: Responsive breakpoint value hook

Vulnerabilities Found:

No Security Issues Found - Pure UI logic with no security implications.

  1. lib/hooks/utils/use_brightness_value.dart

File Analysis: Theme brightness value hook

Vulnerabilities Found:

No Security Issues Found - Pure UI logic with no security implications.

  1. lib/hooks/utils/use_custom_status_bar_color.dart

File Analysis: Custom status bar color hook

Vulnerabilities Found:

VULN-H024: Deprecated API Usage (LOW)

  • Location: Lines 33-35, 52-54
  • Code:

// ignore: deprecated_member_use WidgetsBinding.instance.renderView.automaticSystemUiAdjustment = automaticSystemUiAdjustment;

  • Issue: Uses deprecated API that may be removed in future Flutter versions
  • Impact: Low - Could break in future versions
  • CWE: CWE-477 (Use of Obsolete Function)
  • Recommendation: Migrate to non-deprecated API when available

VULN-H025: Invalid Use of Visible for Testing Member (LOW)

  • Location: Lines 13-14, 27-28
  • Code:

// ignore: invalid_use_of_visible_for_testing_member final previousState = SystemChrome.latestStyle;

  • Issue: Uses internal/testing API
  • Impact: Low - Could break if API changes
  • CWE: CWE-477 (Use of Obsolete Function)
  • Recommendation: Use public API if available

No Critical Security Issues Found

  1. lib/hooks/utils/use_debounce.dart

File Analysis: Debounce utility hook

Vulnerabilities Found:

VULN-H026: Timer Resource Leak Risk (LOW)

  • Location: Lines 11-14
  • Code:

useEffect(() { final timer = Timer(delay, () => state.value = value); return timer.cancel; }, [value, delay]);

  • Issue: If delay changes rapidly, multiple timers could be created
  • Impact: Low - Could cause minor performance issues
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation: Cancel previous timer before creating new one

No Critical Security Issues Found

  1. lib/hooks/utils/use_force_update.dart

File Analysis: Force update hook

Vulnerabilities Found:

VULN-H027: Invalid Use of Protected Member (LOW)

  • Location: Line 6
  • Code:

// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member return () => state.notifyListeners();

  • Issue: Uses protected/internal API
  • Impact: Low - Could break if Flutter internals change
  • CWE: CWE-477 (Use of Obsolete Function)
  • Recommendation: Use public API for forcing updates

No Critical Security Issues Found

  1. lib/hooks/utils/use_palette_color.dart

File Analysis: Image palette color extraction hook

Vulnerabilities Found:

VULN-H028: Unvalidated Image URL (HIGH)

  • Location: Lines 14, 42
  • Code:

PaletteColor usePaletteColor(String imageUrl, WidgetRef ref) { // ... final palette = await PaletteGenerator.fromImageProvider( UniversalImage.imageProvider( imageUrl, height: 50, width: 50, ), );

  • Issue: imageUrl is used directly without validation
  • Impact: High - Malicious URLs could lead to:
    • SSRF (Server-Side Request Forgery) if URL points to internal services
    • Information disclosure through error messages
    • Resource exhaustion through large images
    • XSS if URL is reflected in UI
  • CWE: CWE-20 (Improper Input Validation), CWE-918 (SSRF)
  • Exploitation:
    • imageUrl like http://localhost:8080/admin could probe internal services
    • file:///etc/passwd could attempt local file access
    • Very large images could cause memory exhaustion
  • Recommendation:
    • Validate URL scheme (only allow http/https)
    • Whitelist allowed domains
    • Validate URL format
    • Add size limits for images
    • Sanitize URLs before use
    • Use URL parsing and validation library

VULN-H029: Missing Image Size Limits (MEDIUM)

  • Location: Lines 21-26, 48-53
  • Issue: No size limits on downloaded images
  • Impact: Medium - Large images could cause memory exhaustion
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Add maximum image size limits
    • Implement image size validation before processing
    • Use streaming for large images

VULN-H030: Missing Error Handling for Image Loading (LOW)

  • Location: Lines 20-35, 46-60
  • Issue: No error handling for image loading failures
  • Impact: Low - Could cause crashes or undefined behavior
  • CWE: CWE-703 (Improper Check or Handling of Exceptional Conditions)
  • Recommendation: Add try-catch and error handling

SUMMARY OF CRITICAL FINDINGS

Critical/High Severity:

  1. VULN-H001: Path Traversal in Custom Path Validation (use_check_yt_dlp_installed.dart)
  2. VULN-H028: Unvalidated Image URL (use_palette_color.dart)

Medium Severity:

  1. VULN-H003: Unsafe exit() Call (use_close_behavior.dart)
  2. VULN-H009: Unvalidated Track ID Usage (use_endless_playback.dart)
  3. VULN-H010: Race Condition in Playlist Access (use_endless_playback.dart)
  4. VULN-H014: Permission Request Without User Context (use_get_storage_perms.dart)
  5. VULN-H022: Missing Error Handling (use_async_effect.dart)
  6. VULN-H029: Missing Image Size Limits (use_palette_color.dart)

Low Severity:

  • Multiple low-severity issues related to error handling, deprecated APIs, and input validation

RECOMMENDATIONS

Immediate Actions:

  1. Fix Path Traversal (VULN-H001): Implement strict path validation for custom yt-dlp paths
  2. Fix Image URL Validation (VULN-H028): Implement URL validation and SSRF protection
  3. Fix Unsafe exit() (VULN-H003): Use proper application lifecycle management

Short-term Actions:

  1. Add comprehensive error handling to all async operations
  2. Implement input validation for all user-controlled data
  3. Fix race conditions in state management
  4. Add resource limits (image sizes, etc.)

Long-term Actions:

  1. Implement comprehensive input validation framework
  2. Add security testing for all hooks
  3. Regular security audits
  4. Code review process for all hook changes
  5. Remove or properly secure deprecated/commented code

TESTING RECOMMENDATIONS

  1. Fuzzing: Fuzz image URLs, file paths, and track IDs
  2. Penetration Testing: Test SSRF scenarios with image URLs
  3. Static Analysis: Use Dart analyzer and security linters
  4. Dynamic Analysis: Test with malicious inputs
  5. Security Code Review: Regular reviews of hook implementations

REFERENCES

  • CWE-20: Improper Input Validation
  • CWE-22: Path Traversal
  • CWE-73: External Control of File Name or Path
  • CWE-200: Information Exposure
  • CWE-250: Execution with Unnecessary Privileges
  • CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization
  • CWE-400: Uncontrolled Resource Consumption
  • CWE-404: Improper Resource Shutdown or Release
  • CWE-477: Use of Obsolete Function
  • CWE-703: Improper Check or Handling of Exceptional Conditions
  • CWE-918: Server-Side Request Forgery (SSRF)

Audit Date: Current Severity Levels: Critical/High/Medium/Low/Informational Total Files Audited: 19 files Total Vulnerabilities Found: 30 vulnerabilities

s-b-repo avatar Dec 08 '25 07:12 s-b-repo

Services Directory Security Audit Report Comprehensive Multi-Step Security Analysis

Audit Methodology

This audit follows a systematic approach examining each service file for:

  1. Command injection vulnerabilities
  2. Path traversal issues
  3. SSRF (Server-Side Request Forgery)
  4. Code injection (eval, script execution)
  5. Input validation problems
  6. Unsafe deserialization
  7. Information disclosure
  8. Authentication/authorization flaws
  9. Cryptographic weaknesses
  10. Resource exhaustion

STEP 1: AUTHENTICATION & CREDENTIAL HANDLING

  1. lib/services/metadata/endpoints/auth.dart

File Analysis: Authentication endpoint using Hetu script engine

Vulnerabilities Found:

VULN-S001: Code Injection via Hetu eval() (CRITICAL)

  • Location: Lines 13, 16, 20, 24
  • Code:

Stream get authStateStream => hetu.eval("metadataPlugin.auth.authStateStream");

Future authenticate() async { await hetu.eval("metadataPlugin.auth.authenticate()"); }

bool isAuthenticated() { return hetu.eval("metadataPlugin.auth.isAuthenticated()") as bool; }

Future logout() async { await hetu.eval("metadataPlugin.auth.logout()"); // ... }

  • Issue: Uses hetu.eval() which executes arbitrary Hetu script code
  • Impact: Critical - If plugin system is compromised, arbitrary code execution could occur
  • CWE: CWE-94 (Code Injection), CWE-95 (Improper Neutralization of Directives)
  • Exploitation:
    • If malicious plugin is loaded, it could execute arbitrary code
    • Plugin code could access system resources, files, network
  • Recommendation:
    • Implement strict plugin sandboxing
    • Validate plugin code before loading
    • Use whitelist of allowed Hetu API calls
    • Implement plugin code signing/verification

VULN-S002: Cookie/Storage Clearing Without Validation (LOW)

  • Location: Lines 25-31
  • Code:

if (kIsMobile) { WebStorageManager.instance().deleteAllData(); CookieManager.instance().deleteAllCookies(); } if (kIsDesktop) { await WebviewWindow.clearAll(); }

  • Issue: Clears all web storage/cookies without validation
  • Impact: Low - Could clear data from other applications if shared storage
  • CWE: CWE-922 (Insecure Storage of Sensitive Information)
  • Recommendation: Clear only application-specific storage
  1. lib/services/kv_store/encrypted_kv_store.dart

File Analysis: Encrypted key-value store service

Vulnerabilities Found:

VULN-S003: Weak Encryption Key Generation (MEDIUM)

  • Location: Lines 26-43
  • Code:

static Future<String> get encryptionKey async { if (isUnsupportedPlatform) { return KVStoreService.encryptionKey; } try { final value = await _storage.read(key: 'encryption'); final key = const Uuid().v4();

if (value == null) {
  await setEncryptionKey(key);
  return key;
}

return value;

} catch (e) { return KVStoreService.encryptionKey; } }

  • Issue: Uses UUID v4 for encryption key, which may not be cryptographically secure
  • Impact: Medium - Weak keys could be predictable or brute-forced
  • CWE: CWE-326 (Inadequate Encryption Strength)
  • Recommendation:
    • Use cryptographically secure random number generator
    • Use proper key derivation functions (PBKDF2, Argon2)
    • Ensure key length meets encryption algorithm requirements

VULN-S004: Fallback to Unencrypted Storage (HIGH)

  • Location: Lines 27-28, 40-41, 46-48, 53-54
  • Code: Falls back to KVStoreService.encryptionKey on unsupported platforms or errors
  • Issue: Falls back to unencrypted storage on macOS/iOS/Linux
  • Impact: High - Sensitive data stored unencrypted on certain platforms
  • CWE: CWE-311 (Missing Encryption of Sensitive Data)
  • Recommendation:
    • Implement proper encryption for all platforms
    • Don't silently fall back to unencrypted storage
    • Log security warnings when encryption unavailable
  1. lib/services/kv_store/kv_store.dart

File Analysis: Key-value store service using SharedPreferences

Vulnerabilities Found:

VULN-S005: Path Traversal in YouTube Engine Path Storage (HIGH)

  • Location: Lines 102-117
  • Code:

static String? getYoutubeEnginePath(YoutubeClientEngine engine) { return _youtubeEnginePaths?[engine.name]; }

static Future setYoutubeEnginePath( YoutubeClientEngine engine, String path, ) async { await sharedPreferences.setString( 'ytDlpPath', jsonEncode({ ...?_youtubeEnginePaths, engine.name: path, }), ); }

  • Issue: Path is stored and retrieved without validation
  • Impact: High - Path traversal could allow execution of arbitrary executables
  • CWE: CWE-22 (Path Traversal), CWE-73 (External Control of File Name or Path)
  • Exploitation:
    • Attacker could set path to ../../../etc/passwd or C:\Windows\System32\cmd.exe
    • When path is used to execute yt-dlp, arbitrary code execution occurs
  • Recommendation:
    • Validate path format (no .., absolute paths only from whitelist)
    • Check file exists and is executable
    • Verify file signature/hash before execution
    • Use allowlist of allowed directories

VULN-S006: Weak Encryption Key Storage (MEDIUM)

  • Location: Lines 50-64
  • Code:

static String get encryptionKey { final value = sharedPreferences.getString('encryption');

final key = const Uuid().v4(); if (value == null) { setEncryptionKey(key); return key; }

return value; }

  • Issue: Encryption key stored in SharedPreferences (unencrypted storage)
  • Impact: Medium - Key could be extracted from SharedPreferences
  • CWE: CWE-922 (Insecure Storage of Sensitive Information)
  • Recommendation: Use secure storage (FlutterSecureStorage) for encryption keys

VULN-S007: Unsafe JSON Deserialization (MEDIUM)

  • Location: Lines 33-48, 92-100
  • Code:

static WindowSize? get windowSize { final raw = sharedPreferences.getString('windowSize');

if (raw == null) { return null; } return WindowSize.fromJson(jsonDecode(raw)); }

  • Issue: JSON deserialization without validation
  • Impact: Medium - Malicious JSON could cause crashes or unexpected behavior
  • CWE: CWE-502 (Deserialization of Untrusted Data)
  • Recommendation:
    • Validate JSON structure before deserialization
    • Use schema validation
    • Add try-catch with proper error handling

STEP 2: NETWORK & HTTP SERVICES

  1. lib/services/dio/dio.dart

File Analysis: Global Dio HTTP client instance

Vulnerabilities Found:

VULN-S008: Unconfigured HTTP Client (MEDIUM)

  • Location: Line 3
  • Code: final globalDio = Dio();
  • Issue: Dio instance created without security configurations
  • Impact: Medium - Missing timeout, redirect limits, certificate pinning
  • CWE: CWE-295 (Improper Certificate Validation), CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Configure timeouts
    • Implement certificate pinning
    • Set redirect limits
    • Configure proper error handling
  1. lib/services/connectivity_adapter.dart

File Analysis: Network connectivity checking service

Vulnerabilities Found:

VULN-S009: SSRF via doesConnectTo() (HIGH)

  • Location: Lines 92-107
  • Code:

Future doesConnectTo(String address) async { try { final result = await InternetAddress.lookup(address); if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) { return true; } return false; } on SocketException catch () { try { final response = await dio.head('https://$address'); return (response.statusCode ?? 500) <= 400; } on DioException catch () { return false; } } }

  • Issue: User-controlled address parameter used in HTTP request without validation
  • Impact: High - SSRF attack could probe internal networks or services
  • CWE: CWE-918 (Server-Side Request Forgery)
  • Exploitation:
    • address like localhost:8080/admin could probe internal services
    • 127.0.0.1:3306 could check for MySQL
    • 169.254.169.254 could access cloud metadata services
  • Recommendation:
    • Whitelist allowed addresses/domains
    • Block private IP ranges (10.x.x.x, 172.16.x.x, 192.168.x.x, 127.x.x.x)
    • Block localhost and link-local addresses
    • Validate address format before use

VULN-S010: Hardcoded Connectivity Check Addresses (LOW)

  • Location: Lines 109-112
  • Code:

Future _isConnected() async { return await doesConnectTo('google.com') || await doesConnectTo('www.baidu.com') || // for China await isVpnActive(); // when VPN is active that means we are connected }

  • Issue: Hardcoded addresses, but not a security issue per se
  • Impact: Low - Could fail in restricted networks
  • CWE: N/A
  • Recommendation: Make addresses configurable

STEP 3: COMMAND EXECUTION & PROCESS SERVICES

  1. lib/services/youtube_engine/yt_dlp_engine.dart

File Analysis: yt-dlp engine wrapper for YouTube video extraction

Vulnerabilities Found:

VULN-S011: Command Injection via videoId (CRITICAL)

  • Location: Lines 78-91, 94-108, 111-124, 127-147
  • Code:

@override Future<StreamManifest> getStreamManifest(String videoId) async { final formats = await YtDlp.instance.extractInfo( "https://www.youtube.com/watch?v=$videoId", formatSpecifiers: "%(formats)j", extraArgs: [ "--no-check-certificate", "--geo-bypass", "--quiet", "--ignore-errors" ], ) as List; // ... }

@override Future<List<Video>> searchVideos(String query) async { final stdout = await YtDlp.instance.extractInfoString( "ytsearch10:$query", // ... ); }

  • Issue: videoId and query are directly interpolated into URLs/commands without sanitization
  • Impact: Critical - Command injection could lead to arbitrary code execution
  • CWE: CWE-78 (OS Command Injection), CWE-20 (Improper Input Validation)
  • Exploitation:
    • videoId like dQw4w9WgXcQ&rm -rf / could inject commands
    • query like test; cat /etc/passwd could execute commands
    • URL injection: https://www.youtube.com/watch?v=test&exec=malicious
  • Recommendation:
    • Validate videoId format (alphanumeric, dashes, underscores only)
    • Sanitize query (remove special characters, URL encode)
    • Use parameterized queries/URLs
    • Whitelist allowed characters

VULN-S012: Dangerous yt-dlp Flags (HIGH)

  • Location: Lines 82-87, 98-104, 115-120, 131-139
  • Code:

extraArgs: [ "--no-check-certificate", "--geo-bypass", "--quiet", "--ignore-errors" ]

  • Issue: --no-check-certificate disables SSL certificate validation
  • Impact: High - Man-in-the-middle attacks possible
  • CWE: CWE-295 (Improper Certificate Validation)
  • Recommendation:
    • Remove --no-check-certificate flag
    • Implement proper certificate validation
    • Use certificate pinning if needed

VULN-S013: Unsafe JSON Parsing (MEDIUM)

  • Location: Lines 142-144
  • Code:

final json = jsonDecode( "[${stdout.split("\n").where((s) => s.trim().isNotEmpty).join(",")}]", ) as List;

  • Issue: JSON constructed from stdout without validation
  • Impact: Medium - Malicious stdout could inject JSON or cause parsing errors
  • CWE: CWE-502 (Deserialization of Untrusted Data)
  • Recommendation:
    • Validate JSON structure before parsing
    • Use proper JSON parsing with error handling
    • Sanitize stdout before parsing

VULN-S014: Path Traversal in URL Parsing (MEDIUM)

  • Location: Line 21
  • Code: Uri.parse(f["url"])
  • Issue: URL parsed without validation
  • Impact: Medium - Malicious URLs could be used for SSRF
  • CWE: CWE-918 (Server-Side Request Forgery)
  • Recommendation: Validate URLs before parsing and use
  1. lib/services/youtube_engine/youtube_explode_engine.dart

File Analysis: YouTube Explode engine using isolates

Vulnerabilities Found:

VULN-S015: Command Injection via Isolate Communication (HIGH)

  • Location: Lines 68-104, 120-124, 127-129, 131-141
  • Code:

receivePort.listen((message) async { final SendPort replyPort = message[0]; final String methodName = message[1]; final List arguments = message[2];

// ... var result = switch (methodName) { "search" => youtubeExplode.search .search( arguments[0] as String, // ... ), "video" => youtubeExplode.videos.get(arguments[0] as String), // ... };

replyPort.send(await result); });

  • Issue: Arguments passed to isolate without validation
  • Impact: High - Malicious arguments could cause crashes or unexpected behavior
  • CWE: CWE-20 (Improper Input Validation)
  • Exploitation:
    • Malicious videoId or query could cause crashes
    • Type confusion attacks possible
  • Recommendation:
    • Validate all arguments before passing to isolate
    • Type check arguments
    • Sanitize string inputs
    • Add length limits

VULN-S016: Unvalidated videoId Usage (MEDIUM)

  • Location: Lines 159-170, 200-202, 206-212, 216-224
  • Code:

@override Future<StreamManifest> getStreamManifest(String videoId) async { await IsolatedYoutubeExplode.initialize();

final streamManifest = await _youtubeExplode.manifest( videoId, // ... ); // ... }

  • Issue: videoId used without format validation
  • Impact: Medium - Invalid videoIds could cause errors or crashes
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate videoId format (YouTube video ID pattern)
  1. lib/services/youtube_engine/newpipe_engine.dart

File Analysis: NewPipe extractor engine

Vulnerabilities Found:

VULN-S017: Unvalidated videoId and Query (MEDIUM)

  • Location: Lines 73-79, 83-86, 90-96, 100-111
  • Code:

@override Future<StreamManifest> getStreamManifest(String videoId) async { final video = await NewPipeExtractor.getVideoInfo(videoId); // ... }

@override Future<List<Video>> searchVideos(String query) async { final results = await NewPipeExtractor.search( query, // ... ); // ... }

  • Issue: videoId and query used without validation
  • Impact: Medium - Invalid inputs could cause crashes
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate inputs before use

VULN-S018: Unsafe URL Parsing (MEDIUM)

  • Location: Line 54
  • Code: final id = Uri.parse(info.url).queryParameters["v"]!;
  • Issue: URL parsed and query parameter accessed without null check
  • Impact: Medium - Could cause null pointer exception
  • CWE: CWE-476 (NULL Pointer Dereference)
  • Recommendation: Add null checks and validation

STEP 4: DATA PARSING & DESERIALIZATION

  1. lib/services/metadata/endpoints/search.dart

File Analysis: Search endpoint for metadata plugin

Vulnerabilities Found:

VULN-S019: Unvalidated Search Query (MEDIUM)

  • Location: Lines 17-33, 35-63, 65-95, 97-129, 131-159
  • Code:

Future<SpotubeSearchResponseObject> all(String query) async { if (query.isEmpty) { return SpotubeSearchResponseObject(/ ... /); }

final raw = await hetuMetadataSearch.invoke( "all", positionalArgs: [query], ) as Map; // ... }

  • Issue: Search query passed to Hetu script without validation
  • Impact: Medium - Malicious queries could cause script injection
  • CWE: CWE-94 (Code Injection), CWE-20 (Improper Input Validation)
  • Recommendation:
    • Validate query format and length
    • Sanitize special characters
    • Add query length limits

VULN-S020: Unsafe JSON Deserialization (MEDIUM)

  • Location: Multiple locations
  • Code: raw.cast<String, dynamic>() used without validation
  • Issue: JSON casting without structure validation
  • Impact: Medium - Malicious JSON could cause type confusion
  • CWE: CWE-502 (Deserialization of Untrusted Data)
  • Recommendation: Validate JSON structure before casting
  1. lib/services/metadata/endpoints/track.dart

File Analysis: Track endpoint for metadata plugin

Vulnerabilities Found:

VULN-S021: Unvalidated Track ID (MEDIUM)

  • Location: Lines 13-20, 22-28, 30-43
  • Code:

Future<SpotubeFullTrackObject> getTrack(String id) async { final raw = await hetuMetadataTrack.invoke("getTrack", positionalArgs: [id]) as Map; // ... }

Future<List<SpotubeFullTrackObject>> radio(String id) async { final result = await hetuMetadataTrack.invoke( "radio", positionalArgs: [id], ); // ... }

  • Issue: Track IDs passed without validation
  • Impact: Medium - Malicious IDs could cause script injection
  • CWE: CWE-20 (Improper Input Validation), CWE-94 (Code Injection)
  • Recommendation: Validate ID format and length
  1. lib/services/metadata/endpoints/playlist.dart

File Analysis: Playlist endpoint for metadata plugin

Vulnerabilities Found:

VULN-S022: Unvalidated Playlist Operations (MEDIUM)

  • Location: Multiple methods
  • Issue: Playlist IDs, names, descriptions passed without validation
  • Impact: Medium - Injection attacks possible
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate all inputs

VULN-S023: Missing Authorization Checks (HIGH)

  • Location: Lines 43-66, 68-85, 87-100, 102-113, 115-127, 129-134
  • Issue: No authorization checks before playlist operations
  • Impact: High - Users could modify playlists they don't own
  • CWE: CWE-284 (Improper Access Control)
  • Recommendation: Implement proper authorization checks
  1. lib/services/sourced_track/sourced_track.dart

File Analysis: Sourced track service for audio streaming

Vulnerabilities Found:

VULN-S024: SSRF via Stream URL Validation (HIGH)

  • Location: Lines 254-299
  • Code:

Future<SourcedTrack> refreshStream() async { // ... for (final source in sources) { final res = await globalDio.head( source.url, options: Options(validateStatus: (status) => status != null && status < 500), ); // ... } // ... }

  • Issue: Stream URLs from untrusted sources used in HTTP requests
  • Impact: High - SSRF attack could probe internal networks
  • CWE: CWE-918 (Server-Side Request Forgery)
  • Exploitation:
    • Malicious plugin could provide URLs like http://localhost:8080/admin
    • Could probe internal services or cloud metadata
  • Recommendation:
    • Validate URLs before use
    • Block private IP ranges
    • Whitelist allowed domains
    • Implement URL validation

VULN-S025: Unsafe JSON Encoding/Decoding (MEDIUM)

  • Location: Lines 70, 86-88, 233
  • Code:

sourceInfo: Value(jsonEncode(siblings.first)), // ... final item = SpotubeAudioSourceMatchObject.fromJson( jsonDecode(cachedSource.sourceInfo), );

  • Issue: JSON encoding/decoding without validation
  • Impact: Medium - Malicious JSON could cause deserialization issues
  • CWE: CWE-502 (Deserialization of Untrusted Data)
  • Recommendation: Validate JSON structure

STEP 5: LOGGING & ERROR HANDLING

  1. lib/services/logger/logger.dart

File Analysis: Application logging service

Vulnerabilities Found:

VULN-S026: Information Disclosure in Logs (MEDIUM)

  • Location: Lines 114-129
  • Code:

static Future reportError( dynamic error, [ StackTrace? stackTrace, message = "", ]) async { log.e(message, error: error, stackTrace: stackTrace);

if (kReleaseMode) { await logFile.writeAsString( "[${DateTime.now()}]\n" "$error\n$stackTrace\n" "-\n", mode: FileMode.writeOnlyAppend, ); } }

  • Issue: Full error messages and stack traces logged, could contain sensitive data
  • Impact: Medium - Sensitive information could be exposed in logs
  • CWE: CWE-532 (Insertion of Sensitive Information into Log File)
  • Recommendation:
    • Sanitize error messages before logging
    • Remove sensitive data (passwords, tokens, paths)
    • Implement log rotation and secure storage

VULN-S027: Path Traversal in Log File Path (MEDIUM)

  • Location: Lines 131-143
  • Code:

static String _getXdgStateHome() { // ... if (const bool.hasEnvironment("XDG_STATE_HOME")) { String xdgStateHomeRaw = Platform.environment["XDG_STATE_HOME"] ?? ""; if (xdgStateHomeRaw.isNotEmpty) { return xdgStateHomeRaw; } } return join(Platform.environment["HOME"] ?? "", ".local", "state"); }

  • Issue: Environment variable used in path without validation
  • Impact: Medium - Path traversal could write logs to arbitrary locations
  • CWE: CWE-22 (Path Traversal)
  • Recommendation:
    • Validate environment variable values
    • Normalize paths
    • Check path doesn't contain ..

VULN-S028: Log File Creation Without Permissions Check (LOW)

  • Location: Lines 107-111
  • Code:

final file = File(join(dir, ".spotube_logs")); if (!await file.exists()) { await file.create(recursive: true); }

  • Issue: Log file created without setting proper permissions
  • Impact: Low - Logs could be readable by other users
  • CWE: CWE-276 (Incorrect Default Permissions)
  • Recommendation: Set appropriate file permissions (600 on Unix)

STEP 6: PLUGIN SYSTEM

  1. lib/services/metadata/endpoints/core.dart

File Analysis: Core metadata plugin endpoint

Vulnerabilities Found:

VULN-S029: Code Injection via Hetu Script Invocation (CRITICAL)

  • Location: Lines 17-20, 29-32, 47-52
  • Code:

Future<PluginUpdateAvailable?> checkUpdate( PluginConfiguration pluginConfig, ) async { final result = await hetuMetadataPluginUpdater.invoke( "checkUpdate", positionalArgs: [pluginConfig.toJson()], ); // ... }

Future scrobble(Map<String, dynamic> details) { return hetuMetadataPluginUpdater.invoke( "scrobble", positionalArgs: [details], ); }

  • Issue: Plugin configuration and data passed to Hetu script without validation
  • Impact: Critical - Malicious plugins could execute arbitrary code
  • CWE: CWE-94 (Code Injection)
  • Recommendation:
    • Implement strict plugin sandboxing
    • Validate plugin code before loading
    • Use code signing for plugins
    • Limit plugin API access
  1. lib/services/metadata/apis/localstorage.dart

File Analysis: LocalStorage API for plugins

Vulnerabilities Found:

VULN-S030: Key Injection in LocalStorage (MEDIUM)

  • Location: Lines 10-12, 20-77
  • Code:

String prefix(String key) { return 'spotube_plugin.$pluginSlug.$key'; }

@override Future containsKey(String key) async { return _prefs.containsKey(prefix(key)); }

  • Issue: Keys are prefixed but not validated
  • Impact: Medium - Malicious keys could access other plugin data
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation:
    • Validate key format
    • Sanitize keys
    • Prevent key collisions

SUMMARY OF CRITICAL FINDINGS

Critical Severity:

  1. VULN-S001: Code Injection via Hetu eval() (auth.dart)
  2. VULN-S011: Command Injection via videoId (yt_dlp_engine.dart)
  3. VULN-S029: Code Injection via Hetu Script Invocation (core.dart)

High Severity:

  1. VULN-S004: Fallback to Unencrypted Storage (encrypted_kv_store.dart)
  2. VULN-S005: Path Traversal in YouTube Engine Path Storage (kv_store.dart)
  3. VULN-S009: SSRF via doesConnectTo() (connectivity_adapter.dart)
  4. VULN-S012: Dangerous yt-dlp Flags (yt_dlp_engine.dart)
  5. VULN-S015: Command Injection via Isolate Communication (youtube_explode_engine.dart)
  6. VULN-S023: Missing Authorization Checks (playlist.dart)
  7. VULN-S024: SSRF via Stream URL Validation (sourced_track.dart)

Medium Severity:

  • Multiple issues with input validation, JSON deserialization, and information disclosure

Low Severity:

  • Various issues with error handling, permissions, and configuration

RECOMMENDATIONS

Immediate Actions:

  1. Fix Code Injection (VULN-S001, VULN-S029): Implement strict plugin sandboxing
  2. Fix Command Injection (VULN-S011, VULN-S015): Validate and sanitize all inputs
  3. Fix Path Traversal (VULN-S005): Implement strict path validation
  4. Fix SSRF (VULN-S009, VULN-S024): Implement URL validation and IP blocking

Short-term Actions:

  1. Remove dangerous yt-dlp flags
  2. Implement proper encryption for all platforms
  3. Add input validation throughout
  4. Implement authorization checks
  5. Sanitize log output

Long-term Actions:

  1. Implement comprehensive security testing
  2. Add security code review process
  3. Regular security audits
  4. Implement plugin code signing
  5. Add security monitoring and alerting

TESTING RECOMMENDATIONS

  1. Fuzzing: Fuzz all inputs (videoId, query, paths, URLs)
  2. Penetration Testing: Test SSRF, command injection, path traversal
  3. Static Analysis: Use security linters and analyzers
  4. Dynamic Analysis: Test with malicious inputs
  5. Plugin Security Testing: Test plugin sandboxing

REFERENCES

  • CWE-20: Improper Input Validation
  • CWE-22: Path Traversal
  • CWE-73: External Control of File Name or Path
  • CWE-78: OS Command Injection
  • CWE-94: Code Injection
  • CWE-95: Improper Neutralization of Directives
  • CWE-284: Improper Access Control
  • CWE-295: Improper Certificate Validation
  • CWE-311: Missing Encryption of Sensitive Data
  • CWE-326: Inadequate Encryption Strength
  • CWE-400: Uncontrolled Resource Consumption
  • CWE-476: NULL Pointer Dereference
  • CWE-502: Deserialization of Untrusted Data
  • CWE-532: Insertion of Sensitive Information into Log File
  • CWE-918: Server-Side Request Forgery (SSRF)
  • CWE-922: Insecure Storage of Sensitive Information

Audit Date: Current Severity Levels: Critical/High/Medium/Low Total Files Audited: 37+ files Total Vulnerabilities Found: 30+ vulnerabilities

s-b-repo avatar Dec 08 '25 08:12 s-b-repo

API Security Audit Report Comprehensive Multi-Step Security Analysis

Audit Methodology

This audit follows a systematic 8-step approach examining the API system for:

  1. Code injection vulnerabilities (Hetu script evaluation)
  2. Input validation issues
  3. Data serialization/deserialization vulnerabilities
  4. Authentication and authorization flaws
  5. Plugin loading and bytecode execution risks
  6. Error handling and information disclosure
  7. Resource exhaustion and DoS risks
  8. Type confusion and unsafe casting

STEP 1: HETU SCRIPT EVALUATION & CODE INJECTION

1.1 lib/services/metadata/metadata.dart - Plugin Initialization

VULN-API-001: Code Injection via entryPoint (CRITICAL)

  • Location: Lines 143-149
  • Code:

hetu.eval(""" import "module:plugin" as plugin

var Plugin = plugin.${config.entryPoint}

var metadataPlugin = Plugin() """);

  • Issue: config.entryPoint is directly interpolated into Hetu script code without validation
  • Impact: Critical - Arbitrary code execution if malicious entryPoint is provided
  • CWE: CWE-94 (Code Injection), CWE-95 (Improper Neutralization of Directives)
  • Exploitation:
    • If entryPoint contains: MaliciousClass\n// malicious code here\nvar Plugin = plugin.RealClass
    • The malicious code would be executed during plugin initialization
    • Could access file system, network, or other system resources
  • Recommendation:
    • Validate entryPoint against whitelist of allowed identifiers
    • Use regex to ensure only valid identifier format: ^[a-zA-Z_][a-zA-Z0-9_]$
    • Sanitize entryPoint before interpolation
    • Consider using hetu.fetch() with validation instead of string interpolation

VULN-API-002: Unsafe Bytecode Loading (HIGH)

  • Location: Line 142
  • Code: hetu.loadBytecode(bytes: byteCode, moduleName: "plugin");
  • Issue: Bytecode loaded without verification or signature checking
  • Impact: High - Malicious bytecode could execute arbitrary code
  • CWE: CWE-502 (Deserialization of Untrusted Data)
  • Recommendation:
    • Implement bytecode signature verification
    • Validate bytecode structure before loading
    • Use code signing for plugins

1.2 lib/services/metadata/endpoints/auth.dart - Authentication

VULN-API-003: Code Injection via hetu.eval() (CRITICAL)

  • Location: Lines 12-24
  • Code: dart Stream get authStateStream => hetu.eval("metadataPlugin.auth.authStateStream");

Future authenticate() async { await hetu.eval("metadataPlugin.auth.authenticate()"); }

bool isAuthenticated() { return hetu.eval("metadataPlugin.auth.isAuthenticated()") as bool; }

Future logout() async { await hetu.eval("metadataPlugin.auth.logout()"); // ... }

  • Issue: Uses hetu.eval() which executes arbitrary Hetu script code
  • Impact: Critical - If plugin is compromised, arbitrary code execution
  • CWE: CWE-94 (Code Injection)
  • Exploitation:
    • Malicious plugin could override metadataPlugin.auth object
    • Could execute code during property access or method calls
    • No sandboxing prevents access to system resources
  • Recommendation:
    • Use hetu.invoke() with method name validation instead of eval()
    • Implement plugin sandboxing
    • Validate plugin code before loading
    • Use whitelist of allowed API calls

VULN-API-004: Unsafe Type Casting (MEDIUM)

  • Location: Line 20
  • Code: return hetu.eval("metadataPlugin.auth.isAuthenticated()") as bool;
  • Issue: Result cast to bool without validation
  • Impact: Medium - Type confusion could cause crashes or unexpected behavior
  • CWE: CWE-704 (Incorrect Type Conversion)
  • Recommendation: Validate type before casting

STEP 2: INPUT VALIDATION

2.1 lib/services/metadata/endpoints/search.dart - Search Endpoint

VULN-API-005: Unvalidated Search Query (HIGH)

  • Location: Lines 17-33, 35-63, 65-95, 97-129, 131-159
  • Code:

Future<SpotubeSearchResponseObject> all(String query) async { if (query.isEmpty) { return SpotubeSearchResponseObject(/ ... /); }

final raw = await hetuMetadataSearch.invoke( "all", positionalArgs: [query], ) as Map; // ... }

  • Issue: Search query passed directly to Hetu script without validation
  • Impact: High - Malicious queries could cause:
    • Script injection if query is used in string concatenation
    • Resource exhaustion with extremely long queries
    • DoS attacks
  • CWE: CWE-20 (Improper Input Validation), CWE-400 (Uncontrolled Resource Consumption)
  • Exploitation:
    • Query like "; malicious_code(); " could inject code
    • Very long queries could exhaust memory
    • Special characters could break plugin logic
  • Recommendation:
    • Validate query length (max 500 characters)
    • Sanitize special characters
    • Use parameterized method calls
    • Add rate limiting

VULN-API-006: Unvalidated Pagination Parameters (MEDIUM)

  • Location: Multiple methods with limit and offset parameters
  • Code:

Future<SpotubePaginationResponseObject<SpotubeFullTrackObject>> tracks( String query, { int? limit, int? offset, }) async { // ... namedArgs: { "limit": limit, "offset": offset, }..removeWhere((key, value) => value == null),

  • Issue: limit and offset not validated for bounds
  • Impact: Medium - Could cause:
    • Resource exhaustion with very large limits
    • Negative offsets could cause errors
    • Integer overflow
  • CWE: CWE-20 (Improper Input Validation), CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Validate limit (1-100)
    • Validate offset (>= 0)
    • Add maximum bounds checking

2.2 lib/services/metadata/endpoints/track.dart - Track Endpoint

VULN-API-007: Unvalidated Track ID (HIGH)

  • Location: Lines 13-20, 22-28, 30-43
  • Code: dart Future<SpotubeFullTrackObject> getTrack(String id) async { final raw = await hetuMetadataTrack.invoke("getTrack", positionalArgs: [id]) as Map; // ... }

Future<List<SpotubeFullTrackObject>> radio(String id) async { final result = await hetuMetadataTrack.invoke( "radio", positionalArgs: [id], ); // ... }

  • Issue: Track IDs passed without format validation
  • Impact: High - Malicious IDs could:
    • Cause script injection
    • Access unauthorized tracks
    • Cause plugin crashes
  • CWE: CWE-20 (Improper Input Validation), CWE-94 (Code Injection)
  • Exploitation:
    • ID like "id\"; malicious_code(); " could inject code
    • IDs from other users could access unauthorized data
  • Recommendation:
    • Validate ID format (alphanumeric, dashes, underscores only)
    • Validate ID length
    • Check authorization before fetching

VULN-API-008: Unvalidated Track ID Lists (MEDIUM)

  • Location: Lines 22-28
  • Code:

Future save(List<String> ids) async { await hetuMetadataTrack.invoke("save", positionalArgs: [ids]); }

  • Issue: List of IDs not validated
  • Impact: Medium - Large lists could cause resource exhaustion
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Validate list length (max 50 items)
    • Validate each ID in the list
    • Add rate limiting

2.3 lib/services/metadata/endpoints/playlist.dart - Playlist Endpoint

VULN-API-009: Unvalidated Playlist ID (HIGH)

  • Location: Multiple methods
  • Issue: Playlist IDs passed without validation
  • Impact: High - Similar to track ID issues
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate playlist ID format and length

VULN-API-010: Unvalidated Playlist Names and Descriptions (MEDIUM)

  • Location: Lines 43-66, 68-85
  • Code:

Future<SpotubeFullPlaylistObject?> create( String userId, { required String name, String? description, // ... }) async { final raw = await hetuMetadataPlaylist.invoke( "create", positionalArgs: [userId], namedArgs: { "name": name, "description": description, // ... }, ); }

  • Issue: Names and descriptions not validated
  • Impact: Medium - Could contain:
    • XSS payloads if rendered in UI
    • Extremely long strings causing DoS
    • Special characters breaking plugin logic
  • CWE: CWE-20 (Improper Input Validation), CWE-79 (XSS)
  • Recommendation:
    • Validate length (name: 1-100 chars, description: 0-500 chars)
    • Sanitize HTML/special characters
    • Validate encoding

VULN-API-011: Missing Authorization Checks (CRITICAL)

  • Location: Lines 68-85, 87-100, 102-113, 115-127, 129-134
  • Code:

Future update(String playlistId, { ... }) async { await hetuMetadataPlaylist.invoke("update", ...); }

Future addTracks(String playlistId, { ... }) async { await hetuMetadataPlaylist.invoke("addTracks", ...); }

Future deletePlaylist(String playlistId) async { return await hetuMetadataPlaylist.invoke("deletePlaylist", ...); }

  • Issue: No authorization checks before playlist operations
  • Impact: Critical - Users could:
    • Modify playlists they don't own
    • Delete other users' playlists
    • Add/remove tracks from unauthorized playlists
  • CWE: CWE-284 (Improper Access Control), CWE-639 (Authorization Bypass)
  • Exploitation:
    • Attacker could guess playlist IDs
    • Modify or delete playlists belonging to other users
  • Recommendation:
    • Implement ownership verification
    • Check permissions before all write operations
    • Validate user context

2.4 lib/services/metadata/endpoints/album.dart - Album Endpoint

VULN-API-012: Unvalidated Album ID (MEDIUM)

  • Location: Lines 13-20, 22-41
  • Issue: Album IDs passed without validation
  • Impact: Medium - Similar to track ID issues
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate album ID format

2.5 lib/services/metadata/endpoints/artist.dart - Artist Endpoint

VULN-API-013: Unvalidated Artist ID (MEDIUM)

  • Location: Lines 13-20, 22-42, 44-64, 66-78, 80-101
  • Issue: Artist IDs passed without validation
  • Impact: Medium - Similar to track ID issues
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation: Validate artist ID format

2.6 lib/services/metadata/endpoints/browse.dart - Browse Endpoint

VULN-API-014: Unvalidated Section ID (MEDIUM)

  • Location: Lines 52-86

  • Code: dart Future<SpotubePaginationResponseObject<Object>> sectionItems( String id, { // ... }) async { final raw = await hetuMetadataBrowse.invoke( "sectionItems", positionalArgs: [id], // ... ); }

  • Issue: Section ID not validated

  • Impact: Medium - Malicious IDs could cause errors

  • CWE: CWE-20 (Improper Input Validation)

  • Recommendation: Validate section ID format

2.7 lib/services/metadata/endpoints/user.dart - User Endpoint

VULN-API-015: Unvalidated User ID Lists (MEDIUM)

  • Location: Lines 108-131

  • Code: dart Future<List> isSavedTracks(List<String> ids) async { final values = await hetuMetadataUser.invoke( "isSavedTracks", positionalArgs: [ids], ); return (values as List).cast(); }

  • Issue: Lists of IDs not validated for length or content

  • Impact: Medium - Large lists could cause resource exhaustion

  • CWE: CWE-400 (Uncontrolled Resource Consumption)

  • Recommendation:

    • Validate list length (max 50 items)
    • Validate each ID format
    • Add rate limiting

2.8 lib/services/metadata/endpoints/audio_source.dart - Audio Source

VULN-API-016: Unvalidated Track Objects (HIGH)

  • Location: Lines 21-28, 30-37
  • Code:

Future<List<SpotubeAudioSourceMatchObject>> matches( SpotubeFullTrackObject track, ) async { final raw = await hetuMetadataAudioSource .invoke("matches", positionalArgs: [track.toJson()]) as List; // ... }

Future<List<SpotubeAudioSourceStreamObject>> streams( SpotubeAudioSourceMatchObject match, ) async { final raw = await hetuMetadataAudioSource .invoke("streams", positionalArgs: [match.toJson()]) as List; // ... }

  • Issue: Track/match objects serialized to JSON without validation
  • Impact: High - Malicious JSON could:
    • Cause deserialization issues in plugin
    • Inject code if JSON is evaluated
    • Cause resource exhaustion
  • CWE: CWE-502 (Deserialization of Untrusted Data)
  • Recommendation:
    • Validate object structure before serialization
    • Sanitize JSON output
    • Add size limits

2.9 lib/services/metadata/endpoints/core.dart - Core Endpoint

VULN-API-017: Unvalidated Plugin Configuration (HIGH)

  • Location: Lines 14-27

  • Code: dart Future<PluginUpdateAvailable?> checkUpdate( PluginConfiguration pluginConfig, ) async { final result = await hetuMetadataPluginUpdater.invoke( "checkUpdate", positionalArgs: [pluginConfig.toJson()], ); // ... }

  • Issue: Plugin configuration serialized without validation

  • Impact: High - Malicious config could cause issues

  • CWE: CWE-502 (Deserialization of Untrusted Data)

  • Recommendation: Validate plugin configuration structure

VULN-API-018: Unvalidated Scrobble Data (MEDIUM)

  • Location: Lines 47-52

  • Code: dart Future scrobble(Map<String, dynamic> details) { return hetuMetadataPluginUpdater.invoke( "scrobble", positionalArgs: [details], ); }

  • Issue: Scrobble data map not validated

  • Impact: Medium - Malicious data could cause plugin errors

  • CWE: CWE-20 (Improper Input Validation)

  • Recommendation:

    • Validate required fields
    • Validate data types
    • Sanitize string values

STEP 3: DATA SERIALIZATION/DESERIALIZATION

3.1 Unsafe JSON Deserialization

VULN-API-019: Unsafe Type Casting in All Endpoints (HIGH)

  • Location: All endpoint files

  • Code Pattern: dart final raw = await hetuMetadataSearch.invoke(...) as Map; return SpotubeSearchResponseObject.fromJson( raw.cast<String, dynamic>(), );

  • Issue: Results cast to Map/List without validation

  • Impact: High - Type confusion could cause:

    • Crashes
    • Unexpected behavior
    • Security bypasses
  • CWE: CWE-502 (Deserialization of Untrusted Data), CWE-704 (Incorrect Type Conversion)

  • Exploitation:

    • Plugin could return unexpected types
    • Malicious data structures could bypass validation
  • Recommendation:

    • Validate type before casting
    • Use type-safe deserialization
    • Add try-catch with proper error handling

VULN-API-020: Unsafe JSON Structure Assumptions (MEDIUM)

  • Location: Multiple endpoints
  • Code Pattern:

// From browse.dart final isPlaylist = json["owner"] != null; final isAlbum = json["artists"] != null;

  • Issue: Assumes JSON structure without validation
  • Impact: Medium - Unexpected structures could cause errors
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation:
    • Validate JSON schema before processing
    • Use schema validation library
    • Handle missing fields gracefully

STEP 4: AUTHENTICATION & AUTHORIZATION

4.1 Authentication Flow

VULN-API-021: No Authentication State Validation (HIGH)

  • Location: All endpoints except auth.dart
  • Issue: Endpoints don't check if user is authenticated
  • Impact: High - Unauthenticated users could access protected resources
  • CWE: CWE-306 (Missing Authentication for Critical Function)
  • Recommendation:
    • Check authentication state before sensitive operations
    • Implement authentication middleware
    • Validate session tokens

VULN-API-022: Weak Authentication Check (MEDIUM)

  • Location: auth.dart line 19-21
  • Code:

bool isAuthenticated() { return hetu.eval("metadataPlugin.auth.isAuthenticated()") as bool; }

  • Issue: Relies on plugin to report authentication state
  • Impact: Medium - Malicious plugin could report false authentication
  • CWE: CWE-287 (Improper Authentication)
  • Recommendation:
    • Verify authentication state independently
    • Don't trust plugin-reported state
    • Implement server-side validation

STEP 5: PLUGIN LOADING & BYTECODE EXECUTION

5.1 Plugin Configuration

VULN-API-023: Unvalidated Plugin Configuration Fields (HIGH)

  • Location: metadata_plugin_provider.dart lines 122-146
  • Code:

final pluginConfig = PluginConfiguration( name: plugin.name, author: plugin.author, description: plugin.description, version: plugin.version, entryPoint: plugin.entryPoint, // Not validated! // ... );

  • Issue: Plugin configuration fields loaded from database without validation
  • Impact: High - Malicious database entries could inject code
  • CWE: CWE-20 (Improper Input Validation)
  • Recommendation:
    • Validate all configuration fields
    • Sanitize entryPoint before use
    • Validate version format
    • Check field lengths

VULN-API-024: Path Traversal in Plugin Extraction (MEDIUM)

  • Location: metadata_plugin_provider.dart lines 290-297
  • Code:

Future<Directory> _getPluginExtractionDir(PluginConfiguration plugin) async { final pluginDir = await _getPluginRootDir(); final pluginExtractionDirPath = join( pluginDir.path, "${ServiceUtils.sanitizeFilename(plugin.author)}-${ServiceUtils.sanitizeFilename(plugin.name)}-${plugin.version}", ); return Directory(pluginExtractionDirPath); }

  • Issue: Uses sanitizeFilename but path construction could still be vulnerable
  • Impact: Medium - Path manipulation could extract plugins to wrong locations
  • CWE: CWE-22 (Path Traversal)
  • Recommendation:
    • Validate final path is within plugin root
    • Use path.resolve() to normalize
    • Check path doesn't contain ..

STEP 6: ERROR HANDLING & INFORMATION DISCLOSURE

6.1 Error Handling

VULN-API-025: Information Disclosure via Error Messages (MEDIUM)

  • Location: All endpoints
  • Issue: Errors from Hetu script could expose sensitive information
  • Impact: Medium - Stack traces or error messages could reveal:
    • Internal plugin structure
    • File paths
    • API endpoints
    • Implementation details
  • CWE: CWE-209 (Information Exposure Through an Error Message)
  • Recommendation:
    • Sanitize error messages
    • Don't expose stack traces to users
    • Log detailed errors server-side only

VULN-API-026: Missing Error Handling (LOW)

  • Location: All endpoints
  • Issue: No try-catch blocks around Hetu invocations
  • Impact: Low - Unhandled exceptions could crash application
  • CWE: CWE-703 (Improper Check or Handling of Exceptional Conditions)
  • Recommendation: Add comprehensive error handling

STEP 7: RESOURCE EXHAUSTION & DoS

7.1 Resource Limits

VULN-API-027: No Rate Limiting (HIGH)

  • Location: All endpoints
  • Issue: No rate limiting on API calls
  • Impact: High - Could cause:
    • DoS attacks
    • Resource exhaustion
    • Plugin abuse
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Implement rate limiting per user/IP
    • Add request throttling
    • Monitor API usage

VULN-API-028: No Timeout on Hetu Invocations (MEDIUM)

  • Location: All endpoints using hetu.invoke()
  • Issue: No timeout on plugin method calls
  • Impact: Medium - Malicious plugins could hang indefinitely
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Add timeout to all Hetu invocations
    • Implement circuit breaker pattern
    • Kill long-running plugin operations

VULN-API-029: No Memory Limits (MEDIUM)

  • Location: Plugin execution
  • Issue: No memory limits on plugin execution
  • Impact: Medium - Plugins could exhaust memory
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Set memory limits for Hetu engine
    • Monitor memory usage
    • Kill plugins exceeding limits

VULN-API-030: Large Response Data (MEDIUM)

  • Location: All endpoints returning lists
  • Issue: No limits on response size
  • Impact: Medium - Large responses could exhaust memory
  • CWE: CWE-400 (Uncontrolled Resource Consumption)
  • Recommendation:
    • Enforce pagination limits
    • Validate response size
    • Stream large responses

STEP 8: TYPE CONFUSION & UNSAFE CASTING

8.1 Type Safety Issues

VULN-API-031: Unsafe Type Casting Throughout (HIGH)

  • Location: All endpoints
  • Code Pattern:

final raw = await hetuMetadataSearch.invoke(...) as Map; return (result as List).cast();

  • Issue: Multiple unsafe type casts without validation
  • Impact: High - Type confusion could cause:
    • Crashes
    • Security bypasses
    • Data corruption
  • CWE: CWE-704 (Incorrect Type Conversion)
  • Recommendation:
    • Validate types before casting
    • Use type-safe deserialization
    • Add runtime type checks

VULN-API-032: Unsafe List Casting (MEDIUM)

  • Location: Multiple endpoints
  • Code Pattern:

return (values as List).cast(); return raw.cast<String, dynamic>();

  • Issue: List casting without element validation
  • Impact: Medium - Invalid elements could cause errors
  • CWE: CWE-704 (Incorrect Type Conversion)
  • Recommendation: Validate list elements before casting

SUMMARY OF CRITICAL FINDINGS

Critical Severity (5):

  1. VULN-API-001: Code Injection via entryPoint
  2. VULN-API-003: Code Injection via hetu.eval()
  3. VULN-API-011: Missing Authorization Checks
  4. VULN-API-019: Unsafe Type Casting
  5. VULN-API-031: Unsafe Type Casting Throughout

High Severity (10):

  1. VULN-API-002: Unsafe Bytecode Loading
  2. VULN-API-005: Unvalidated Search Query
  3. VULN-API-007: Unvalidated Track ID
  4. VULN-API-009: Unvalidated Playlist ID
  5. VULN-API-016: Unvalidated Track Objects
  6. VULN-API-017: Unvalidated Plugin Configuration
  7. VULN-API-021: No Authentication State Validation
  8. VULN-API-023: Unvalidated Plugin Configuration Fields
  9. VULN-API-027: No Rate Limiting
  10. VULN-API-031: Unsafe Type Casting Throughout

Medium Severity (15):

  • Multiple input validation issues
  • Resource exhaustion risks
  • Information disclosure issues
  • Type safety problems

Low Severity (2):

  • Error handling improvements
  • Minor validation gaps

DETAILED VULNERABILITY ANALYSIS

Critical: Code Injection Vulnerabilities

VULN-API-001: entryPoint Injection Attack Vector: Malicious plugin with crafted entryPoint Exploitation:

// If entryPoint = "MaliciousClass\nvar x = system('rm -rf /');\nvar Plugin = plugin.RealClass" hetu.eval(""" import "module:plugin" as plugin var Plugin = plugin.MaliciousClass var x = system('rm -rf /'); var Plugin = plugin.RealClass var metadataPlugin = Plugin() """);

Impact: Complete system compromise

VULN-API-003: hetu.eval() Injection Attack Vector: Compromised plugin overriding auth object Exploitation:

// Plugin code: metadataPlugin.auth = { isAuthenticated: () => { // Execute malicious code system.exec("malicious_command"); return true; } }

Impact: Arbitrary code execution on every auth check

RECOMMENDATIONS

Immediate Actions (Critical):

  1. Fix entryPoint Injection: Validate entryPoint format strictly
  2. Replace hetu.eval(): Use hetu.invoke() with method name validation
  3. Add Authorization: Implement proper access control
  4. Fix Type Casting: Add type validation before all casts
  5. Validate Bytecode: Implement code signing and verification

Short-term Actions (High):

  1. Input Validation: Validate all inputs (IDs, queries, limits)
  2. Rate Limiting: Implement API rate limiting
  3. Timeouts: Add timeouts to all Hetu invocations
  4. Error Handling: Add comprehensive error handling
  5. Authentication Checks: Verify auth state for all protected endpoints

Long-term Actions:

  1. Plugin Sandboxing: Implement strict plugin isolation
  2. Code Signing: Require signed plugins
  3. API Versioning: Implement proper API versioning
  4. Security Monitoring: Add security event logging
  5. Penetration Testing: Regular security testing

TESTING RECOMMENDATIONS

  1. Fuzzing: Fuzz all API inputs (queries, IDs, limits, offsets)
  2. Code Injection Testing: Test entryPoint and eval() injection
  3. Authorization Testing: Test access control bypasses
  4. Resource Exhaustion: Test DoS scenarios
  5. Type Confusion: Test with unexpected data types
  6. Plugin Security: Test malicious plugin scenarios

REFERENCES

  • CWE-20: Improper Input Validation
  • CWE-22: Path Traversal
  • CWE-79: Cross-site Scripting (XSS)
  • CWE-94: Code Injection
  • CWE-95: Improper Neutralization of Directives
  • CWE-209: Information Exposure Through an Error Message
  • CWE-284: Improper Access Control
  • CWE-287: Improper Authentication
  • CWE-306: Missing Authentication for Critical Function
  • CWE-400: Uncontrolled Resource Consumption
  • CWE-502: Deserialization of Untrusted Data
  • CWE-639: Authorization Bypass
  • CWE-704: Incorrect Type Conversion
  • CWE-703: Improper Check or Handling of Exceptional Conditions

Audit Date: Current Severity Levels: Critical/High/Medium/Low Total Vulnerabilities Found: 32 vulnerabilities Files Audited: 10 endpoint files + metadata.dart + plugin provider

s-b-repo avatar Dec 08 '25 08:12 s-b-repo

Are these AI generated?

import "module:plugin" as plugin
var Plugin = plugin.MaliciousClass
var x = system('rm -rf /');
var Plugin = plugin.RealClass
var metadataPlugin = Plugin()

WTF is system? It doesn't even exist. Clear signs of hallucinations. And plugins are only allowed to few exposed high level API such as HttpClient and Webview etc. which are well sandboxed. Also, hetu_script bytecode is evaluated on a sandbox environment and no plugin can access each other's context/sandbox. Each plugin is sandbox inside in its own instance so kinda impossible for to access variables/resources of other plugins or Spotube itself.

And there are lots of other reports. Like 99% of it doesn't even relate to the project. It's stating "potentially" not "obviously". Please create vulnerability issues providing legitimate evidence and reproducing steps. And these kind AI generated reports that clearly have hallucinations, only harms the project as it misdirects everyone and creates unnecessary panics.

KRTirtho avatar Dec 08 '25 12:12 KRTirtho

only the text its from your code you can check which parts its from and where i find it im bad with reports if something is not there i can remove it from report its alot of stuff. also sandbox scape is a thing so it should still be fixed

s-b-repo avatar Dec 08 '25 13:12 s-b-repo

please dont say its not part of your project

STEP 2: INPUT VALIDATION

2.1 lib/services/metadata/endpoints/search.dart - Search Endpoint

VULN-API-005: Unvalidated Search Query (HIGH)

Location: Lines 17-33, 35-63, 65-95, 97-129, 131-159
Code:

Future all(String query) async { if (query.isEmpty) { return SpotubeSearchResponseObject(/ ... /); }

final raw = await hetuMetadataSearch.invoke( "all", positionalArgs: [query], ) as Map; // ... }

s-b-repo avatar Dec 08 '25 13:12 s-b-repo

also fixing this will improve your apps preformance cause of mem leaks etc

s-b-repo avatar Dec 08 '25 13:12 s-b-repo

also i have provided a working one before for you i even added in my hacking framework its ok ill make some modules in my framework for these exploits i just wanted to warn you not my problem anymore

s-b-repo avatar Dec 08 '25 14:12 s-b-repo

Well lot of this will be invalidated anyways as I'm working on a quickjs based plugin system due to hetu_script's terrible developer experience. Check the rquickjs-based-migration branch.

KRTirtho avatar Dec 08 '25 16:12 KRTirtho

Well lot of this will be invalidated anyways as I'm working on a quickjs based plugin system due to hetu_script's terrible developer experience. Check the rquickjs-based-migration branch.

how is quick js

s-b-repo avatar Dec 09 '25 06:12 s-b-repo