Skip to content

Fix/command shell injection vulnerabilities - #555

Draft
lo-simon wants to merge 5 commits into
sony:masterfrom
lo-simon:fix/command-shell-injection-vulnerabilities
Draft

lo-simon wants to merge 5 commits into
sony:masterfrom
lo-simon:fix/command-shell-injection-vulnerabilities

Conversation

@lo-simon

Copy link
Copy Markdown
Collaborator

This code builds a shell command string by concatenating an untrusted/dynamic value (authorization_code_uri) directly into a command, then executes it with system(). This is a shell injection vulnerability.

Problem:

std::string browser_cmd;
#if defined(_WIN32) && !defined(__cplusplus_winrt)
browser_cmd = "start \"\" \"" + utility::us2s(authorization_code_uri.to_string()) + "\"";
#else
browser_cmd = "xdg-open \"" + utility::us2s(authorization_code_uri.to_string()) + "\"";
#endif
std::ignore = system(browser_cmd.c_str());
  1. Untrusted input in a shell command: authorization_code_uri is a URI, likely built from a server/discovered endpoint and user-supplied authorisation parameters (OAuth-style flows often embed client IDs, redirect URIs, state tokens, scopes, etc.). If any part of that URI's content is attacker-influenced or comes from a compromised/malicious server response, it can contain characters that break out of the surrounding double quotes.
  2. system() invokes a full shell (cmd.exe /c on Windows, /bin/sh -c on POSIX). The shell interprets special characters like:
    • " - closes the quoted string early, allowing injection of additional shell syntax.
    • &, &&, |, ;, `, $( ) - command chaining/substitution.
    • On Windows, cmd.exe is particularly dangerous with &, |, ^, and %VAR% expansion.
    For example, if the URI string contained:
http://example.com/"&calc.exe&"

the resulting command becomes:

start "" "http://example.com/"&calc.exe&""

The shell sees this as: open the browser to http://example.com/, then run calc.exe as a separate command. An attacker could substitute calc.exe with any arbitrary command (e.g. downloading and executing malware, deleting files, exfiltrating data).

  1. No escaping/sanitization: The code just wraps the value in "..." without escaping embedded quotes or shell metacharacters, so quoting alone does not neutralise the risk.
  2. Why URIs are especially risky here: Although URIs are typically percent-encoded for the HTTP layer, nothing prevents literal ", &, |, etc. from appearing in a URI string (e.g., unencoded query parameters, redirect URIs controlled by configuration, or a malicious/misbehaving OAuth server returning a crafted authorization_code_uri). The code doesn't validate or encode for shell safety - it only assumes URI safety, which is a different threat model.

Solution:

• Windows: use CreateProcessW with exePath.c_str() as lpApplicationName and the constructed cmdLine as lpCommandLine. No cmd.exe is spawned - the string is parsed only by the target executable's own argument-parsing logic, not a shell. Shell metacharacters (&, |, ;, backtick, $(), etc.) are inert here.
• POSIX: use posix_spawnp with an explicit argv[] - the URI is passed as a single argument, never interpreted by /bin/sh.
This directly addresses the original vulnerability (shell metacharacter injection via system()).

…ignedness: ‘const unsigned int’ and ‘int’
…ith a details::launch_browser() helper that avoids invoking a command shell
…escapes embedded " before building cmdLine, closing the argument-injection, which validate the scheme before launching
@garethsb

Copy link
Copy Markdown
Contributor

Hi @lo-simon, getting rid of system() here is definitely worthwhile. The authorization code URI is built from authorization_endpoint in the authorization server metadata, so a malicious or compromised server controls part of a string the shell interprets.

Discussed this with my 🤖 buddy...

A few comments on the current approach:

  1. Windows includes. The PR removes <Windows.h> and <shellapi.h>, but the new code uses MultiByteToWideChar, CreateProcessW, STARTUPINFOW and CloseHandle. It only compiles if another header happens to pull in Windows.h. The !defined(__cplusplus_winrt) guard has also been dropped.

  2. Windows string conversion. On Windows, utility::string_t is already std::wstring, so converting with us2s and then back with MultiByteToWideChar isn't needed.

  3. Windows quoting. Escaping " as \" follows the CommandLineToArgvW rules, but even by those rules it's incomplete: backslashes before a quote aren't doubled, so a URI ending in \ escapes the closing quote. More importantly, rundll32 passes the rest of its command line to FileProtocolHandler as raw text rather than splitting it into arguments, so the added quotes and backslashes may reach the browser literally. The hard-coded C:\Windows\System32 path also breaks if Windows isn't on C:. ShellExecuteW(nullptr, L"open", uri, nullptr, nullptr, SW_SHOWNORMAL) avoids all of this: it doesn't run cmd.exe or build a command line, and it is presumably why <shellapi.h> was included originally.

  4. Scheme validation. The last commit message says the scheme is validated before launching, but I can't see that in the diff. This is the main remaining risk: a server can still supply a file: URI or a custom scheme, and xdg-open, open or FileProtocolHandler will pass it to whatever program handles that scheme. Rejecting anything other than https (or http) fixes this on every platform at once.

  5. Zombie processes on POSIX. system() waited for the child to exit, but nothing calls waitpid after posix_spawnp, so every authorization attempt leaves a zombie xdg-open process. Calling waitpid keeps the previous blocking behaviour and also lets the function report whether xdg-open itself succeeded. At the moment, true only means the process was spawned.

  6. Other POSIX platforms. Previously every non-Windows platform used xdg-open. Now only __linux__ and __APPLE__ do, so FreeBSD and similar systems always return false.

Minor: the brace and if( style doesn't match the rest of the file. On macOS, Apple recommends _NSGetEnviron() over extern char** environ in shared libraries.

Two simpler alternatives:

A. Don't launch a browser from the library. request_authorization_code_handler is supplied by the application, and only nmos-cpp-node uses make_request_authorization_code_handler. The default handler could just log the URI at a severity the user will see. Applications that want a browser to open can supply their own handler. This is fully portable and leaves nothing to inject into.

B. Keep the launch, but check the scheme first and use each OS's URL-opening mechanism. The scheme check is what fixes the remaining risk. Once system() is gone, a server can't inject shell commands, but it can still send a file: URI or a custom scheme that makes the OS start another program. One check before any platform-specific code covers every platform. On Windows, ShellExecuteW passes the URL straight to the default handler and doesn't build a command line, so there's nothing to escape. That makes it much shorter than the rundll32 and CreateProcessW approach. On POSIX, waitpid reaps the child process like system() did. Keeping CreateProcessW would also be fine if it got the same scheme check and waitpid; it would just be longer.

Untested sketch:

bool launch_browser(const web::uri& uri)
{
    if (U("https") != uri.scheme() && U("http") != uri.scheme()) return false;
#if defined(_WIN32)
    return reinterpret_cast<INT_PTR>(::ShellExecuteW(nullptr, L"open", uri.to_string().c_str(), nullptr, nullptr, SW_SHOWNORMAL)) > 32;
#else
#if defined(__APPLE__)
    const char* executable = "open";
#else
    const char* executable = "xdg-open";
#endif
    const auto u = utility::us2s(uri.to_string());
    char* const argv[] = { const_cast<char*>(executable), const_cast<char*>(u.c_str()), nullptr };
    pid_t pid;
    if (0 != posix_spawnp(&pid, executable, nullptr, nullptr, argv, environ)) return false;
    int status = 0;
    return pid == waitpid(pid, &status, 0) && WIFEXITED(status) && 0 == WEXITSTATUS(status);
#endif
}

I'd lean towards A if we're happy for the library to stop opening browsers by default, and B otherwise. Both are shorter than the current change, and both close the file: and custom-scheme hole.

Co-authored-by: Gareth's 🤖 buddy

@lo-simon

Copy link
Copy Markdown
Collaborator Author

Thank you, @garethsb. Yes, option A is definitely a good choice; let the application provide the handler to open the browser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants