Skip to content

Sample Rule

Pavel Bansky edited this page Jan 8, 2018 · 11 revisions

Following rule demonstrates all the features of DevSkim rule format.

Description

The rule is detecting unsafe content being generated as an output in PHP. Typically form variables that are being displayed on the web page without proper HTML encoding. For example echo($_POST["name"]) is considered unsafe, because the user controlled variable name can contain malicious HTML/JavaScript content. Such content can be used in Cross Site Scripting attacks.

Notice that the rule is conditioned and is not being triggered when the variable is properly encoded. For example echo(htmlentities($_POST["name"])) is considered safe, because the function htmlentities will safely escape all HTML content in the variable.

The htmlentities function is also offered by one of the fix_its records in the rule.

{
  "name": "XSS: Do not echo unencoded GET/POST/COOKIE values",
  "id": "DS163877",
  "description": "When using $_GET/POST/COOKIE values via echo, failure to  encode the values will lead to Cross Site Scription (XSS), where a malicious party can inject script into the webpage.",
  "recommendation": "HTML Entity Encode (for content going into HTML) or URL Encode (for content going into JavaScript variables) the data",
  "applies_to": [
      "php"
  ],
  "tags": [
      "Implementation.PHP"
  ],
  "severity": "moderate",
  "_comment": "",
  "rule_info": "DS163877.md",
  "patterns": [
      {
          "pattern": "\\becho.*(\\$_(POST|GET|REQUEST|COOKIE)\\[.*\\]).*;",
          "type": "regex",
          "scopes": [
              "code"
          ],
          "_comment": ""
      }
  ],
  "conditions" : [
      {
          "pattern" : 
          {
              "pattern": "\\b(htmlentities|htmlspecialchars|rawurlencode|urlencode)\\s*\\(.*(\\$_(POST|GET|REQUEST|COOKIE)\\[.*\\]).*\\)",
              "type": "regex",
              "scopes": [
                  "code"
              ],
              "_comment": ""
          },
          "search_in":"finding-only",
          "negate_finding": true,
          "_comment": "" 
      }          
  ],
  "fix_its": [
      {
          "name": "HTML Entity encode the data",
          "type": "regex-replace",
          "_comment": "",
          "replacement": "htmlentities($1)",
          "pattern": {
              "pattern": "(\\$_(POST|GET|REQUEST|COOKIE)\\[.*\\])",
              "type": "regex",
              "scopes": [
                  "code"
              ],
              "_comment": ""
          }
      },
      {
          "name": "URL encode the data",
          "type": "regex-replace",
          "_comment": "",
          "replacement": "rawurlencode($1)",
          "pattern": {
              "pattern": "(\\$_(POST|GET|REQUEST|COOKIE)\\[.*\\])",
              "type": "regex",
              "scopes": [
                  "code"
              ],
              "_comment": ""
          }
      }
  ]
}