game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
shell_utils.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// shell_utils.h
4// ==============================================================================
5// Safe shell command building utilities to prevent command injection attacks
6// ==============================================================================
7// This file provides functions for safely escaping shell arguments and
8// environment variables to prevent command injection vulnerabilities.
9//
10// SECURITY: Always use these functions when building shell commands from
11// user-provided or external data (game names, paths, environment variables).
12//
13// ## Usage Example
14// @code
15// #include "shell_utils.h"
16//
17// // Safe environment variable
18// std::string cmd = ShellUtils::formatEnvVar("WINEPREFIX", userProvidedPath);
19//
20// // Safe argument
21// cmd += " wine " + ShellUtils::escapeArg(executablePath);
22//
23// // Safe command building
24// std::vector<std::string> args = {"wine", execPath, "--flag"};
25// std::string fullCmd = ShellUtils::buildCommand(args, envVars);
26// @endcode
27// ==============================================================================
28
29#pragma once
30
31#include <map>
32#include <regex>
33#include <string>
34#include <vector>
35
36// ==============================================================================
37// ShellUtils - Static utility class for safe shell command building
38// ==============================================================================
39
40/**
41 * @class ShellUtils
42 * @brief Utilities for safely building shell commands
43 *
44 * Provides functions to escape shell arguments and environment variables
45 * to prevent command injection attacks. All methods are static.
46 */
47class ShellUtils
48{
49 public:
50 // ==========================================================================
51 // Argument Escaping
52 // ==========================================================================
53
54 /**
55 * @brief Escape a string for safe use as a shell argument
56 * @param arg The argument to escape
57 * @return Escaped argument safe for shell use
58 *
59 * Uses single quotes with proper escaping of embedded single quotes.
60 * This is the safest method as single-quoted strings prevent all
61 * shell expansion except for the quote character itself.
62 *
63 * Example: "hello'world" becomes "'hello'\''world'"
64 */
65 static std::string escapeArg(const std::string& arg)
66 {
67 if (arg.empty())
68 {
69 return "''";
70 }
71
72 // If the string contains only safe characters, no escaping needed
73 if (isSafeString(arg))
74 {
75 return arg;
76 }
77
78 // Use single quotes - they prevent all shell expansion
79 // To include a single quote, end the quoted section, add escaped quote, restart
80 std::string result = "'";
81 for (char c : arg)
82 {
83 if (c == '\'')
84 {
85 // End quote, add escaped single quote, restart quote
86 result += "'\\''";
87 }
88 else
89 {
90 result += c;
91 }
92 }
93 result += "'";
94 return result;
95 }
96
97 /**
98 * @brief Escape a string for use in double quotes
99 * @param arg The argument to escape
100 * @return Escaped string (without surrounding quotes)
101 *
102 * Escapes characters that have special meaning in double quotes:
103 * `$`, backtick, `\`, `"`, `!`, and newlines.
104 *
105 * Note: Caller must add the surrounding double quotes.
106 * Prefer escapeArg() with single quotes when possible.
107 */
108 static std::string escapeForDoubleQuotes(const std::string& arg)
109 {
110 std::string result;
111 result.reserve(arg.size() * 2); // Reserve extra space for escapes
112
113 for (char c : arg)
114 {
115 switch (c)
116 {
117 case '$':
118 case '`':
119 case '\\':
120 case '"':
121 case '!':
122 result += '\\';
123 result += c;
124 break;
125 case '\n':
126 result += "\\n";
127 break;
128 case '\r':
129 result += "\\r";
130 break;
131 default:
132 result += c;
133 break;
134 }
135 }
136 return result;
137 }
138
139 // ==========================================================================
140 // Environment Variable Handling
141 // ==========================================================================
142
143 /**
144 * @brief Validate an environment variable name
145 * @param name The variable name to validate
146 * @return true if name is a valid shell variable name
147 *
148 * Valid names match: [A-Za-z_][A-Za-z0-9_]*
149 */
150 static bool isValidEnvName(const std::string& name)
151 {
152 if (name.empty())
153 return false;
154
155 // First character must be letter or underscore
156 char first = name[0];
157 if (!((first >= 'A' && first <= 'Z') || (first >= 'a' && first <= 'z') || first == '_'))
158 {
159 return false;
160 }
161
162 // Rest must be alphanumeric or underscore
163 for (size_t i = 1; i < name.size(); ++i)
164 {
165 char c = name[i];
166 if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
167 c == '_'))
168 {
169 return false;
170 }
171 }
172
173 return true;
174 }
175
176 /**
177 * @brief Format an environment variable assignment safely
178 * @param name Variable name (must be valid - checked)
179 * @param value Variable value (will be escaped)
180 * @return Safe "NAME='value'" string, or empty if name is invalid
181 *
182 * Example: formatEnvVar("PATH", "/usr/bin:/tmp") returns "PATH='/usr/bin:/tmp'"
183 */
184 static std::string formatEnvVar(const std::string& name, const std::string& value)
185 {
186 if (!isValidEnvName(name))
187 {
188 return ""; // Invalid name - return empty to indicate error
189 }
190
191 return name + "=" + escapeArg(value);
192 }
193
194 /**
195 * @brief Format multiple environment variables safely
196 * @param envVars Map of variable names to values
197 * @param skipInvalid If true, skip invalid names; if false, return empty on any invalid
198 * @return Space-separated environment variable assignments
199 */
200 static std::string formatEnvVars(const std::map<std::string, std::string>& envVars,
201 bool skipInvalid = true)
202 {
203 std::string result;
204 bool first = true;
205
206 for (const auto& [name, value] : envVars)
207 {
208 if (!isValidEnvName(name))
209 {
210 if (!skipInvalid)
211 return ""; // Error - invalid name
212 continue; // Skip invalid names
213 }
214
215 if (!first)
216 result += " ";
217 first = false;
218
219 result += formatEnvVar(name, value);
220 }
221
222 return result;
223 }
224
225 // ==========================================================================
226 // Command Building
227 // ==========================================================================
228
229 /**
230 * @brief Build a complete shell command from parts
231 * @param args Command and arguments (args[0] is the command)
232 * @param envVars Optional environment variables to prepend
233 * @return Complete command string safe for shell execution
234 *
235 * Example:
236 * buildCommand({"wine", "/path/to/game.exe", "--flag"},
237 * {{"WINEPREFIX", "/home/user/.wine"}})
238 * Returns: "WINEPREFIX='/home/user/.wine' wine '/path/to/game.exe' '--flag'"
239 */
240 static std::string buildCommand(const std::vector<std::string>& args,
241 const std::map<std::string, std::string>& envVars = {})
242 {
243 std::string result;
244
245 // Add environment variables
246 if (!envVars.empty())
247 {
248 result = formatEnvVars(envVars);
249 if (!result.empty())
250 result += " ";
251 }
252
253 // Add command and arguments
254 for (size_t i = 0; i < args.size(); ++i)
255 {
256 if (i > 0)
257 result += " ";
258 result += escapeArg(args[i]);
259 }
260
261 return result;
262 }
263
264 /**
265 * @brief Split a shell argument string into tokens, respecting quoting
266 * @param args The argument string (e.g., "--arg \"value with spaces\" --other")
267 * @return Vector of unquoted token strings, each safe to pass through escapeArg()
268 *
269 * Handles single-quoted and double-quoted groups. Each returned token is the
270 * raw (unquoted) value; pass each through escapeArg() before appending to a
271 * shell command. This replaces the insecure "use as-is when quotes detected"
272 * pattern that was a shell-injection vector.
273 */
274 static std::vector<std::string> splitArgs(const std::string& args)
275 {
276 std::vector<std::string> tokens;
277 std::string current;
278 enum class Q
279 {
280 None,
281 Single,
282 Double
283 } q = Q::None;
284
285 for (size_t i = 0; i < args.size(); ++i)
286 {
287 char c = args[i];
288 if (q == Q::None)
289 {
290 if (c == '\'')
291 q = Q::Single;
292 else if (c == '"')
293 q = Q::Double;
294 else if (c == ' ' || c == '\t')
295 {
296 if (!current.empty())
297 {
298 tokens.push_back(current);
299 current.clear();
300 }
301 }
302 else
303 current += c;
304 }
305 else if (q == Q::Single)
306 {
307 if (c == '\'')
308 q = Q::None;
309 else
310 current += c;
311 }
312 else // Double
313 {
314 if (c == '"')
315 q = Q::None;
316 else if (c == '\\' && i + 1 < args.size())
317 {
318 char next = args[i + 1];
319 if (next == '"' || next == '\\')
320 {
321 current += next;
322 ++i;
323 }
324 else
325 current += c;
326 }
327 else
328 current += c;
329 }
330 }
331 if (!current.empty())
332 tokens.push_back(current);
333 return tokens;
334 }
335
336 /**
337 * @brief Build command with a wrapper (e.g., game-performance, mangohud)
338 * @param wrapper The wrapper command (e.g., "game-performance", "mangohud")
339 * @param args Command and arguments
340 * @param envVars Environment variables
341 * @return Complete command with wrapper
342 */
343 static std::string
344 buildCommandWithWrapper(const std::string& wrapper, const std::vector<std::string>& args,
345 const std::map<std::string, std::string>& envVars = {})
346 {
347 std::string result;
348
349 // Add environment variables
350 if (!envVars.empty())
351 {
352 result = formatEnvVars(envVars);
353 if (!result.empty())
354 result += " ";
355 }
356
357 // Add wrapper
358 result += escapeArg(wrapper) + " ";
359
360 // Add command and arguments
361 for (size_t i = 0; i < args.size(); ++i)
362 {
363 if (i > 0)
364 result += " ";
365 result += escapeArg(args[i]);
366 }
367
368 return result;
369 }
370
371 // ==========================================================================
372 // Path Utilities
373 // ==========================================================================
374
375 /**
376 * @brief Check if a path is safe (no directory traversal, no special chars)
377 * @param path The path to check
378 * @return true if path appears safe
379 *
380 * Rejects paths with:
381 * - Parent directory references (..)
382 * - Null bytes
383 * - Newlines
384 */
385 static bool isSafePath(const std::string& path)
386 {
387 // Check for null bytes
388 if (path.find('\0') != std::string::npos)
389 return false;
390
391 // Check for newlines (can break command structure)
392 if (path.find('\n') != std::string::npos || path.find('\r') != std::string::npos)
393 return false;
394
395 // Check for parent directory traversal
396 // Look for .. that's either at start, end, or surrounded by slashes
397 size_t pos = 0;
398 while ((pos = path.find("..", pos)) != std::string::npos)
399 {
400 // Check if this is a directory traversal
401 bool atStart = (pos == 0);
402 bool atEnd = (pos + 2 == path.size());
403 bool precededBySlash = (pos > 0 && path[pos - 1] == '/');
404 bool followedBySlash = (pos + 2 < path.size() && path[pos + 2] == '/');
405
406 if ((atStart || precededBySlash) && (atEnd || followedBySlash))
407 {
408 return false; // Directory traversal detected
409 }
410 pos += 2;
411 }
412
413 return true;
414 }
415
416 /**
417 * @brief Escape a path for shell use with validation
418 * @param path The path to escape
419 * @param allowTraversal If false (default), reject paths with ..
420 * @return Escaped path, or empty string if validation fails
421 */
422 static std::string escapePath(const std::string& path, bool allowTraversal = false)
423 {
424 if (!allowTraversal && !isSafePath(path))
425 {
426 return ""; // Invalid path
427 }
428 return escapeArg(path);
429 }
430
431 // ==========================================================================
432 // JSON Escaping (for database storage)
433 // ==========================================================================
434
435 /**
436 * @brief Escape a string for JSON
437 * @param str The string to escape
438 * @return JSON-safe string (without surrounding quotes)
439 */
440 static std::string escapeJson(const std::string& str)
441 {
442 std::string result;
443 result.reserve(str.size() * 2);
444
445 for (char c : str)
446 {
447 switch (c)
448 {
449 case '"':
450 result += "\\\"";
451 break;
452 case '\\':
453 result += "\\\\";
454 break;
455 case '\b':
456 result += "\\b";
457 break;
458 case '\f':
459 result += "\\f";
460 break;
461 case '\n':
462 result += "\\n";
463 break;
464 case '\r':
465 result += "\\r";
466 break;
467 case '\t':
468 result += "\\t";
469 break;
470 default:
471 if (static_cast<unsigned char>(c) < 0x20)
472 {
473 // Control character - encode as \uXXXX
474 char buf[8];
475 snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned char>(c));
476 result += buf;
477 }
478 else
479 {
480 result += c;
481 }
482 break;
483 }
484 }
485 return result;
486 }
487
488 /**
489 * @brief Build a JSON object from key-value pairs
490 * @param pairs Map of keys to values
491 * @return JSON object string
492 */
493 static std::string buildJsonObject(const std::map<std::string, std::string>& pairs)
494 {
495 std::string result = "{";
496 bool first = true;
497
498 for (const auto& [key, value] : pairs)
499 {
500 if (!first)
501 result += ",";
502 first = false;
503
504 result += "\"" + escapeJson(key) + "\":\"" + escapeJson(value) + "\"";
505 }
506
507 result += "}";
508 return result;
509 }
510
511 /**
512 * @brief Build a JSON array from strings
513 * @param items Vector of strings
514 * @return JSON array string
515 */
516 static std::string buildJsonArray(const std::vector<std::string>& items)
517 {
518 std::string result = "[";
519 bool first = true;
520
521 for (const auto& item : items)
522 {
523 if (!first)
524 result += ",";
525 first = false;
526
527 result += "\"" + escapeJson(item) + "\"";
528 }
529
530 result += "]";
531 return result;
532 }
533
534 private:
535 ShellUtils() = delete; // Static class, no instantiation
536
537 /**
538 * @brief Check if a string contains only safe characters (no escaping needed)
539 */
540 static bool isSafeString(const std::string& str)
541 {
542 for (char c : str)
543 {
544 // Safe characters: alphanumeric, dash, underscore, period, forward slash, colon
545 if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
546 c == '-' || c == '_' || c == '.' || c == '/' || c == ':'))
547 {
548 return false;
549 }
550 }
551 return true;
552 }
553};
Utilities for safely building shell commands.
Definition shell_utils.h:48
static bool isSafePath(const std::string &path)
Check if a path is safe (no directory traversal, no special chars).
static std::string buildCommand(const std::vector< std::string > &args, const std::map< std::string, std::string > &envVars={})
Build a complete shell command from parts.
static std::string formatEnvVar(const std::string &name, const std::string &value)
Format an environment variable assignment safely.
static std::string escapeJson(const std::string &str)
Escape a string for JSON.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
static bool isValidEnvName(const std::string &name)
Validate an environment variable name.
static std::string buildJsonArray(const std::vector< std::string > &items)
Build a JSON array from strings.
static std::string escapeForDoubleQuotes(const std::string &arg)
Escape a string for use in double quotes.
static std::string formatEnvVars(const std::map< std::string, std::string > &envVars, bool skipInvalid=true)
Format multiple environment variables safely.
static std::vector< std::string > splitArgs(const std::string &args)
Split a shell argument string into tokens, respecting quoting.
static std::string buildCommandWithWrapper(const std::string &wrapper, const std::vector< std::string > &args, const std::map< std::string, std::string > &envVars={})
Build command with a wrapper (e.g., game-performance, mangohud).
static std::string buildJsonObject(const std::map< std::string, std::string > &pairs)
Build a JSON object from key-value pairs.
static std::string escapePath(const std::string &path, bool allowTraversal=false)
Escape a path for shell use with validation.
@ None
No specific store (generic fixes only).