rfc:is_literal
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
rfc:is_literal [2020/12/23 19:53] – New examples, with a focus on escaping craigfrancis | rfc:is_literal [2021/05/02 16:38] – Add performance stats, and notes from Dan craigfrancis | ||
---|---|---|---|
Line 1: | Line 1: | ||
====== PHP RFC: Is Literal Check ====== | ====== PHP RFC: Is Literal Check ====== | ||
- | * Version: 0.2 | + | * Version: 0.6 |
* Date: 2020-03-21 | * Date: 2020-03-21 | ||
- | * Updated: | + | * Updated: |
* Author: Craig Francis, craig# | * Author: Craig Francis, craig# | ||
* Status: Draft | * Status: Draft | ||
Line 11: | Line 11: | ||
===== Introduction ===== | ===== Introduction ===== | ||
- | Add an // | + | A new function, |
- | As in, at runtime, being able to check if a variable has been created by literals, defined within a PHP script, by a trusted developer. | + | This takes the concept of "taint checking" |
- | This simple check can be used to warn or completely block SQL Injection, Command Line Injection, and many cases of HTML Injection | + | It does not allow a variable to be marked as untainted, and it does not allowing escaping |
- | ===== The Problem ===== | + | For example, a database library that supports parametrised queries at the driver level, today a programmer could use either of these: |
- | Escaping strings for SQL, HTML, Commands, etc is **very** error prone. | + | <code php> |
+ | $db-> | ||
- | The vast majority of programmers should never do this (mistakes will be made). | + | $db-> |
+ | </ | ||
- | Unsafe values | + | By rejecting the SQL that was not written as a literal |
- | This is primarily for security reasons, but it also causes data to be damaged | + | This definition of an " |
- | Take these mistakes: | + | By adding a way for libraries to check if the strings they receive came from the developer (from trusted PHP source code), it allows the library to check they are being used in a safe way. |
- | echo "< | + | ===== Why ===== |
- | Flawed because the attribute value is not quoted, e.g. //$url = '/ onerror=alert(1)' | + | The [[https://owasp.org/www-project-top-ten/|OWASP Top 10]] lists common vulnerabilities sorted by prevalence, exploitability, |
- | echo "< | + | **Injection vulnerabilities** remain at the top of the list (common prevalence, easy for attackers to detect/exploit, severe impact); and **XSS** comes in at 7 (widespread prevalence, easy for attackers to detect/ |
- | Flawed | + | This is because |
- | echo '<a href="' | + | ===== Examples ===== |
- | Flawed because a link can include JavaScript, e.g. //$url = ' | + | The [[https:// |
- | | + | <code php> |
- | var url = "<? | + | // INSECURE |
- | </script> | + | $qb-> |
+ | ->from(' | ||
+ | | ||
+ | </code> | ||
- | Flawed because | + | The definition of the //where()// method could check with //is_literal()// and throw an exception, advising the programmer to replace it with a safer use of placeholders: |
- | echo '<a href="/ | + | <code php> |
+ | $qb-> | ||
+ | | ||
+ | | ||
+ | ->setParameter(' | ||
+ | </code> | ||
- | Flawed because | + | Similarly, Twig allows [[https://twig.symfony.com/doc/2.x/recipes.html# |
- | | + | <code php> |
+ | // INSECURE | ||
+ | echo $twig-> | ||
+ | </code> | ||
- | Flawed because the encoding is not guaranteed to be UTF-8 (or ISO-8859-1 before PHP 5.4), so the value could be corrupted. | + | If // |
- | Also flawed because some browsers | + | <code php> |
+ | echo $twig-> | ||
+ | </code> | ||
- | example.html: | + | ===== Failed Solutions ===== |
- | <img src={{ url }} alt='' | + | |
- | + | ||
- | $loader | + | |
- | $twig = new \Twig\Environment($loader, | + | |
- | + | ||
- | echo $twig-> | + | |
- | Flawed because Twig is not context aware (in this case, an unquoted HTML attribute), e.g. // | + | ==== Education ==== |
- | $sql = ' | + | Developer training has not worked, it simply does not scale (people start programming every day), and learning about every single issue is difficult. |
- | Flawed because the value has not been quoted, e.g. //$id = ' | + | Keeping in mind that programmers will frequently do just enough to complete their task (busy), where they often copy/paste a solution to their problem they find online (risky), modify it for their needs (risky), then move on. |
- | $sql = 'SELECT 1 FROM user WHERE id="' . $mysqli-> | + | We cannot keep saying they 'need to be careful', and relying on them to never make a mistake. |
- | Flawed if ' | + | ==== Escaping ==== |
- | $sql = ' | + | Escaping is hard, and error prone. |
- | Flawed if 'SET NAMES latin1' | + | We have a list of common [[https:// |
- | $parameters = " | + | Developers should use parameterised queries |
- | + | ||
- | // $parameters = ' | + | |
- | + | ||
- | mail('a@example.com', ' | + | |
- | Flawed because it's not possible to safely escape values in // | + | ==== Taint Checking ==== |
- | ===== Previous Solutions ===== | + | Some languages implement a "taint flag" which tracks whether values are considered " |
- | [[https:// | + | There is a [[https:// |
- | [[https:// | + | These solutions rely on the assumption that the output of an escaping function is safe for a particular context. This sounds reasonable in theory, but the operation of escaping functions, and the context for which their output is safe, are very hard to define. This leads to a feature that is both complex and unreliable. |
- | * " | + | This proposal avoids the complexity by addressing a different part of the problem: separating inputs supplied by the programmer, from inputs supplied |
- | * this amount | + | |
- | * It would have effected every SQL function, such as // | + | |
- | * Each of those functions would need a bypass for cases where unsafe SQL was intentionally being used (e.g. phpMyAdmin taking SQL from POST data) because some applications intentionally "pass raw, user submitted, SQL" (Ronald Chmara [[https:// | + | |
- | I also agree that "SQL injection is almost a solved problem [by using] prepared statements" | + | ==== Static Analysis ==== |
- | ===== Related JavaScript Implementation ===== | + | While I agree with [[https:// |
- | This RFC is taking some ideas from TC39, where a similar idea is being discussed for JavaScript, to support the introduction of Trusted Types. | + | But they nearly always focus on other issues (type checking, basic logic flaws, code formatting, etc). |
- | https:// | + | Those that attempt to address injection vulnerabilities, |
- | https://github.com/ | + | |
- | They are looking at " | + | For a quick example, psalm, even in its strictest errorLevel (1), and/or running // |
- | ===== Solution ===== | + | <code php> |
+ | $db = new mysqli(' | ||
- | Literals are safe values, defined within | + | $id = (string) ($_GET[' |
- | | + | $db-> |
- | is_literal($a); // true | + | </code> |
- | + | ||
- | $a = ' | + | |
- | is_literal($a); | + | |
- | + | ||
- | $a = ' | + | |
- | is_literal($a); | + | |
- | + | ||
- | $a = ' | + | |
- | is_literal($a); // false | + | |
- | + | ||
- | $a = sprintf(' | + | |
- | is_literal($a); // false | + | |
- | + | ||
- | $c = count($ids); | + | |
- | $a = ' | + | |
- | | + | |
- | + | ||
- | $limit = 10; | + | |
- | $a = 'LIMIT ' . ($limit + 1); | + | |
- | is_literal($a); | + | |
- | This uses a similar definition | + | When psalm comes to taint checking the usage of a library (like Doctrine), it assumes all methods are safe, because none of them note the sinks (and even if they did, you're back to escaping being an issue). |
- | Thanks to [[https:// | + | But the biggest problem is that Static Analysis is simply not used by most developers, especially those who are new to programming (usage tends to be higher by those writing well tested libraries). |
- | And thanks to [[https:// | + | ===== Proposal ===== |
- | Commands can be checked to ensure they are a " | + | This RFC proposes adding three functions: |
- | This approach allows all systems/frameworks | + | * // |
+ | | ||
+ | * //literal_implode(string $glue, array $pieces): string// to implode an array of literals, with a literal. | ||
- | Unlike | + | A literal is defined as a value (string) which has been written by the programmer. The value may be passed between functions, as long as it is not modified in any way. |
- | ==== Solution: SQL Injection ==== | + | <code php> |
+ | is_literal(' | ||
- | Database abstractions (e.g. ORMs) will be able to ensure they are provided with strings that are safe. | + | $a = ' |
+ | $b = ' | ||
- | [[https://www.doctrine-project.org/projects/doctrine-orm/ | + | is_literal($a); |
+ | is_literal($a | ||
- | $users = $queryBuilder | + | is_literal(literal_combine($a, $b)); // true |
- | ->select(' | + | |
- | ->from(' | + | |
- | -> | + | |
- | -> | + | |
- | -> | + | |
- | + | ||
- | | + | |
- | This mistake can be easily identified by: | + | is_literal($_GET[' |
+ | is_literal(' | ||
+ | is_literal(rand(0, | ||
+ | is_literal(sprintf(' | ||
+ | </ | ||
- | public function where($predicates) | + | There is no way to manually mark a string as a literal |
- | { | + | |
- | if (function_exists(' | + | |
- | throw new Exception(' | + | |
- | } | + | |
- | ... | + | |
- | } | + | |
- | [[https:// | + | *Technical detail: Strings that are concatenated in place at compile time are treated as a literal.* |
- | $users | + | ===== Previous Work ===== |
- | [[http://propelorm.org/ | + | Google uses " |
- | $users = UserQuery:: | + | Google also uses [[https:// |
- | The // | + | Perl has a [[https://perldoc.perl.org/perlsec# |
- | ==== Solution: SQL Injection, Basic ==== | + | [[https:// |
- | A simple example: | + | As noted above, there is the [[https:// |
- | $sql = ' | + | And there is the [[https:// |
- | + | ||
- | $result = $db-> | + | |
- | Checked in the framework | + | * " |
+ | * this amount of work isn't ideal for "just for one use case" ([[https:// | ||
+ | * It would have effected every SQL function, such as // | ||
+ | * Each of those functions would need a bypass for cases where unsafe SQL was intentionally being used (e.g. phpMyAdmin taking SQL from POST data) because some applications intentionally "pass raw, user submitted, SQL" (Ronald Chmara [[https:// | ||
+ | |||
+ | I also agree that "SQL injection is almost a solved problem [by using] prepared statements" | ||
+ | |||
+ | ===== Usage ===== | ||
+ | |||
+ | By libraries: | ||
- | | + | <code php> |
- | + | class db { | |
- | | + | |
- | + | function | |
- | if (!is_literal($sql)) { | + | if (function_exists(' |
- | throw new Exception(' | + | if ($this-> |
+ | // Programmer aware, and is choosing to bypass this check. | ||
+ | | ||
+ | trigger_error(' | ||
+ | } else { | ||
+ | throw new Exception(' | ||
} | } | ||
- | | ||
- | $statement = $this-> | ||
- | $statement-> | ||
- | return $statement-> | ||
- | | ||
} | } | ||
- | | ||
} | } | ||
+ | function unsafe_disable_injection_protection() { | ||
+ | $this-> | ||
+ | } | ||
+ | function where($sql, $parameters = []) { | ||
+ | $this-> | ||
+ | // ... | ||
+ | } | ||
+ | } | ||
- | This also works with string concatenation: | + | $db-> |
+ | $db-> | ||
+ | </ | ||
- | define(' | + | Table and Fields in SQL, which cannot use parameters; for example //ORDER BY//: |
- | + | ||
- | $sql = ' | + | |
- | + | ||
- | is_literal($sql); | + | |
- | + | ||
- | $sql .= ' AND id = ' . $mysqli-> | + | |
- | + | ||
- | is_literal($sql); | + | |
- | ==== Solution: SQL Injection, ORDER BY ==== | + | <code php> |
+ | $order_fields | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ]; | ||
- | To ensure //ORDER BY// can be set via the user, but only use acceptable values: | + | $order_id = array_search(($_GET[' |
- | | + | $sql = literal_combine(' ORDER BY ', $order_fields[$order_id]); |
- | ' | + | </ |
- | ' | + | |
- | ' | + | |
- | ]; | + | |
- | + | ||
- | $order_id | + | |
- | + | ||
- | $sql = ' ORDER BY ' | + | |
- | ==== Solution: SQL Injection, | + | Undefined number of parameters; for example //WHERE IN//: |
- | Most SQL strings can be a simple concatenations of literal values, but // | + | <code php> |
+ | function where_in_sql($count) { // Should check for 0 | ||
+ | $sql = []; | ||
+ | for ($k = 0; $k < $count; $k++) { | ||
+ | $sql[] = '?'; | ||
+ | } | ||
+ | return literal_implode(',', | ||
+ | } | ||
+ | $sql = literal_combine(' | ||
+ | </code> | ||
- | There needs to be a special case for // | + | ===== Considerations ===== |
- | $in_sql | + | ==== Naming ==== |
- | + | ||
- | $sql = ' | + | |
- | ==== Solution: CLI Injection ==== | + | Literal string is the standard name for strings in source code. See https:// |
- | Rather than using functions such as: | + | > A string literal is the notation for representing a string value within the text of a computer program. In PHP, strings can be created with single quotes, double quotes or using the heredoc or the nowdoc syntax. ... The heredoc preserves the line breaks and other whitespace (including indentation) in the text. |
- | * //exec()// | + | Alternatives suggestions have included |
- | * //shell_exec()// | + | |
- | * //system()// | + | |
- | * //passthru()// | + | |
- | Frameworks (or PHP) could introduce something similar to //pcntl_exec()//, | + | ==== Supporting Int/Float/Boolean values. ==== |
- | Or, take a safe literal for the command, and use parameters for the arguments (like SQL does): | + | When converting to string, they aren't guaranteed (and often don't) have the exact same value they have in source code. |
- | $output = parameterised_exec(' | + | For example, |
- | ' | + | |
- | ]); | + | |
- | Rough implementation: | + | It's also a very low value feature, where there might not be space for a flag to be added. |
- | function parameterised_exec($cmd, | + | ==== Supporting Concatenation |
- | + | ||
- | if (!is_literal($cmd)) { | + | |
- | throw new Exception(' | + | |
- | } | + | |
- | + | ||
- | $offset | + | |
- | $k = 0; | + | |
- | while (($pos | + | |
- | if (!isset($args[$k])) { | + | |
- | throw new Exception(' | + | |
- | exit(); | + | |
- | } | + | |
- | $arg = escapeshellarg($args[$k]); | + | |
- | $cmd = substr($cmd, | + | |
- | $offset = ($pos + strlen($arg)); | + | |
- | $k++; | + | |
- | } | + | |
- | if (isset($args[$k])) { | + | |
- | throw new Exception(' | + | |
- | exit(); | + | |
- | } | + | |
- | + | ||
- | return exec($cmd); | + | |
- | + | ||
- | } | + | |
- | ==== Solution: HTML Injection ==== | + | Unfortunately early testing suggests there will be too much of a performance impact, and is why // |
- | Template engines should receive variables separately from the raw HTML. | + | It isn't needed for most libraries, like an ORM or Query Builder, where their methods nearly always take a small literal string. |
- | Often the engine will get the HTML from static files (safe): | + | It was considered because it would have made it easier for existing projects currently using string concatenation to adopt. |
- | $html = file_get_contents('/ | + | Joe Watkins has created a version that does support string concatenation, |
- | But small snippets of HTML are often easier to define as a literal | + | Máté Kocsis did the [[https:// |
- | $template_html = ' | + | In my own [[https://github.com/craigfrancis/ |
- | < | + | |
- | < | + | |
- | Where the variables | + | Dan Ackroyd also notes that the use of // |
- | $values = [ | + | <code php> |
- | '// | + | $sortOrder |
- | | + | |
- | ' | + | |
- | ' | + | |
- | ], | + | |
- | '// | + | |
- | ' | + | |
- | ], | + | |
- | ]; | + | |
- | + | ||
- | echo template_parse($template_html, | + | |
- | The templating engine can then accept and apply the supplied variables for the relevant context. | + | // 300 lines of code, or multiple function calls |
- | As a simple example, this can be done with: | + | $sql .= ' ORDER BY name ' . $sortOrder; |
- | | + | // 300 lines of code, or multiple |
- | + | ||
- | if (!is_literal($html)) { | + | $db->query($sql); |
- | throw new Exception(' | + | </code> |
- | } | + | |
- | + | If a developer changed the literal //' | |
- | $dom = new DomDocument(); | + | |
- | $dom->loadHTML('<? | + | <code php> |
- | + | $sql = literal_combine($sql, ' | |
- | $xpath = new DOMXPath($dom); | + | </ |
- | + | ||
- | foreach ($values as $query => $attributes) { | + | ==== Performance ==== |
- | + | ||
- | if (!is_literal($query)) { | + | The proposed implementation has: |
- | throw new Exception('Invalid Template XPath.'); | + | |
- | } | + | |
- | + | ||
- | foreach ($xpath->query($query) as $element) { | + | Also, see the section above, where string concatenation support would have introduced a ~1% performance hit. |
- | | + | |
- | + | ==== Values from INI/JSON/YAML ==== | |
- | if (!is_literal($attribute)) { | + | |
- | throw new Exception('Invalid Template Attribute.'); | + | As noted by [[https://news-web.php.net/ |
- | } | + | |
- | + | ==== Existing String Functions ==== | |
- | if ($attribute) { | + | |
- | $safe = false; | + | Trying to determine |
- | if ($attribute | + | |
- | if (preg_match('/ | + | For any use-case where dynamic strings are required, it would be better to build those strings with an appropriate query builder, or by using // |
- | $safe = true; // Not " | + | |
- | } | + | |
- | } else if ($attribute == ' | + | |
- | if (in_array($value, [' | + | |
- | | + | |
- | } | + | |
- | } else if (preg_match(' | + | |
- | if (preg_match(' | + | |
- | | + | |
- | } | + | |
- | } | + | |
- | | + | |
- | $element-> | + | |
- | } | + | |
- | } else { | + | |
- | $element-> | + | |
- | } | + | |
- | + | ||
- | } | + | |
- | } | + | |
- | + | ||
- | } | + | |
- | + | ||
- | $html = ''; | + | |
- | $body = $dom-> | + | |
- | if ($body-> | + | |
- | foreach | + | |
- | $html .= $dom-> | + | |
- | } | + | |
- | } | + | |
- | + | ||
- | return $html; | + | |
- | + | ||
- | } | + | |
===== Backward Incompatible Changes ===== | ===== Backward Incompatible Changes ===== | ||
- | None | + | No known BC breaks, except for code-bases that already contain userland functions // |
===== Proposed PHP Version(s) ===== | ===== Proposed PHP Version(s) ===== | ||
- | PHP 8.1? | + | PHP 8.1 |
===== RFC Impact ===== | ===== RFC Impact ===== | ||
Line 399: | Line 314: | ||
==== To SAPIs ==== | ==== To SAPIs ==== | ||
- | Not sure | + | None known |
==== To Existing Extensions ==== | ==== To Existing Extensions ==== | ||
Line 411: | Line 326: | ||
===== Open Issues ===== | ===== Open Issues ===== | ||
- | On [[https:// | + | None |
- | - Would this cause performance issues? Presumably not as bad a type checking. | + | ===== Unaffected PHP Functionality ===== |
- | - Can // | + | |
- | - Should the function be named // | + | |
- | - Systems/ | + | |
- | ===== Alternatives ===== | + | None known |
- | - The current Taint Extension (notes above) | + | ===== Future Scope ===== |
- | - Using static analysis (not at runtime), for example [[https:// | + | |
- | ===== Unaffected PHP Functionality ===== | + | As noted by MarkR, the biggest benefit will come when it can be used by PDO and similar functions (// |
- | Not sure | + | **Phase 2** could introduce a way for programmers to specify certain PHP function/ |
- | ===== Future Scope ===== | + | For example, a project could require the second argument for // |
- | Certain functions (// | + | **Phase 3** could set a default of 'only literals' |
- | PHP could also have a mode where output | + | And, for a bit of silliness |
===== Proposed Voting Choices ===== | ===== Proposed Voting Choices ===== | ||
- | N/A | + | Accept the RFC. Yes/No |
===== Patches and Tests ===== | ===== Patches and Tests ===== | ||
- | A volunteer is needed to help with implementation. | + | N/A |
===== Implementation ===== | ===== Implementation ===== | ||
+ | |||
+ | Dan Ackroyd has [[https:// | ||
+ | |||
+ | Joe Watkins has [[https:// | ||
+ | |||
+ | ===== References ===== | ||
N/A | N/A | ||
Line 448: | Line 365: | ||
N/A | N/A | ||
+ | |||
+ | ===== Thanks ===== | ||
+ | |||
+ | - **Dan Ackroyd**, DanAck, for starting the first implementation (which made this a reality), and followup on the version that uses functions instead of string concat. | ||
+ | - **Joe Watkins**, krakjoe, for finding how to set the literal flag (tricky), and creating the implementation that does support string concat. | ||
+ | - **Rowan Tommins**, IMSoP, for re-writing this RFC to focus on the key features, and putting it in context of how it can be used by libraries. | ||
+ | - **Nikita Popov**, NikiC, for suggesting where the literal flag could be stored. Initially this was going to be the " | ||
+ | - **Mark Randall**, MarkR, for alternative ideas, and noting that " | ||
+ | - **Xinchen Hui**, who created the Taint Extension, allowing me to test the idea; and noting how Taint in PHP5 was complex, but "with PHP7's new zend_string, | ||
rfc/is_literal.txt · Last modified: 2022/02/14 00:36 by craigfrancis