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/26 11:41] – 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 can also cause data to be damaged | + | This definition of an " |
- | Take these mistakes, where the value has come from the user: | + | 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, and unfortunately very common, | + | The [[https:// |
- | 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 "< | + | ===== Examples ===== |
- | Flawed because | + | The [[https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/ |
- | | + | <code php> |
+ | // INSECURE | ||
+ | $qb-> | ||
+ | | ||
+ | | ||
+ | </code> | ||
- | Flawed because a link can include JavaScript, e.g. //$url = ' | + | The definition of the //where()// method could check with // |
- | | + | <code php> |
- | var url = "<? | + | $qb-> |
- | </script> | + | |
+ | | ||
+ | | ||
+ | </code> | ||
- | Flawed because | + | Similarly, Twig allows [[https://twig.symfony.com/doc/2.x/recipes.html# |
- | echo '<a href="/path/?name=' . htmlentities($name) . '"> | + | <code php> |
+ | // INSECURE | ||
+ | echo $twig-> | ||
+ | </ | ||
- | Flawed because | + | If //createTemplate()// checked with //is_literal()//, the programmer could be advised to write this instead: |
- | | + | <code php> |
+ | 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. | + | ===== Failed Solutions ===== |
- | Also flawed because some browsers (e.g. IE 11), if the charset isn't defined (header or meta tag), could guess the output as UTF-7, e.g. // | + | ==== Education ==== |
- | example.html: | + | Developer training has not worked, it simply does not scale (people start programming every day), and learning about every single issue is difficult. |
- | <img src={{ url }} alt='' | + | |
- | + | ||
- | $loader = new \Twig\Loader\FilesystemLoader(' | + | |
- | $twig = new \Twig\Environment($loader, [' | + | |
- | + | ||
- | echo $twig-> | + | |
- | Flawed because Twig is not context aware (in this case, an unquoted HTML attribute), e.g. //$url = '/ onerror=alert(1)'// | + | 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 |
- | $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 because the value has not been quoted, e.g. //$id = ' | + | ==== Escaping ==== |
- | $sql = ' | + | Escaping is hard, and error prone. |
- | Flawed if ' | + | We have a list of common [[https://github.com/craigfrancis/php-is-literal-rfc/blob/main/ |
- | $sql = ' | + | Developers should use parameterised queries |
- | Flawed if 'SET NAMES latin1' | + | ==== Taint Checking ==== |
- | $parameters = "-f$email"; | + | Some languages implement a "taint flag" which tracks whether values are considered "safe". |
- | + | ||
- | // $parameters = ' | + | |
- | + | ||
- | mail(' | + | |
- | Flawed because it's not possible to safely escape values in //$additional_parameters// for //mail()//, e.g. //$email = ' | + | There is a [[https://github.com/laruence/taint|Taint extension |
- | ===== Previous Solutions ===== | + | 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. |
- | [[https:// | + | This proposal avoids the complexity by addressing a different part of the problem: separating inputs supplied |
- | [[https:// | + | ==== Static Analysis ==== |
- | * " | + | While I agree with [[https:// |
- | * 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" | + | But they nearly always focus on other issues |
- | ===== Related JavaScript Implementation ===== | + | Those that attempt to address injection vulnerabilities, |
- | This RFC is taking some ideas from TC39, where a similar idea is being discussed for JavaScript, to support | + | For a quick example, psalm, even in its strictest errorLevel (1), and/or running // |
- | https:// | + | <code php> |
- | https:// | + | $db = new mysqli(' |
- | They are looking at " | + | $id = (string) ($_GET[' |
- | ===== Solution ===== | + | $db-> |
+ | </ | ||
- | Literals | + | When psalm comes to taint checking the usage of a library (like Doctrine), it assumes all methods |
- | $a = ' | + | But the biggest problem is that Static Analysis is simply not used by most developers, especially those who are new to programming |
- | is_literal($a); | + | |
- | + | ||
- | $a = ' | + | |
- | is_literal($a); | + | |
- | + | ||
- | $a = ' | + | |
- | is_literal($a); | + | |
- | + | ||
- | $a = ' | + | |
- | is_literal($a); | + | |
- | + | ||
- | $a = sprintf(' | + | |
- | is_literal($a); | + | |
- | + | ||
- | $c = count($ids); | + | |
- | $a = 'WHERE id IN (' . implode(',', | + | |
- | is_literal($a); | + | |
- | + | ||
- | $limit = 10; | + | |
- | $a = 'LIMIT ' . ($limit + 1); | + | |
- | is_literal($a); | + | |
- | This uses a similar definition of [[https:// | + | ===== Proposal ===== |
- | Thanks to [[https:// | + | This RFC proposes adding three functions: |
- | And thanks to [[https://chat.stackoverflow.com/transcript/message/ | + | * // |
+ | * //literal_combine(string $piece, string $pieces): string// | ||
+ | * // | ||
- | Commands can be checked to ensure they are a " | + | A literal is defined as a value (string) which has been written |
- | This approach allows all systems/ | + | <code php> |
+ | is_literal(' | ||
- | Unlike the Taint extension, there must **not** be an equivalent // | + | $a = ' |
+ | $b = ' | ||
- | ==== Solution: SQL Injection ==== | + | is_literal($a); |
+ | is_literal($a . $b); // false, no concat at run time (details below). | ||
- | Database abstractions | + | is_literal(literal_combine($a, |
- | [[https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/query-builder.html# | + | is_literal($_GET[' |
+ | is_literal(' | ||
+ | is_literal(rand(0, | ||
+ | is_literal(sprintf(' | ||
+ | </code> | ||
- | $users = $queryBuilder | + | There is no way to manually mark a string as a literal |
- | ->select(' | + | |
- | -> | + | |
- | -> | + | |
- | -> | + | |
- | -> | + | |
- | + | ||
- | // example.php? | + | |
- | This mistake can be easily identified by: | + | *Technical detail: Strings that are concatenated in place at compile time are treated as a literal.* |
- | public function where($predicates) | + | ===== Previous Work ===== |
- | { | + | |
- | if (function_exists(' | + | |
- | throw new Exception(' | + | |
- | } | + | |
- | ... | + | |
- | } | + | |
- | [[https://redbeanphp.com/index.php?p=/finding|RedBean]] could check //$sql// is a literal: | + | Google uses " |
- | $users = R::find(' | + | Google also uses [[https:// |
- | [[http://propelorm.org/Propel/ | + | Perl has a [[https://perldoc.perl.org/perlsec#Taint-mode|Taint Mode]], via the -T flag, where all input is marked as " |
- | $users = UserQuery::create()->where('id = ' . $_GET[' | + | [[https:// |
- | The // | + | As noted above, there is the [[https://github.com/laruence/taint|Taint extension for PHP]] by Xinchen Hui. |
- | ==== Solution: SQL Injection, | + | And there is the [[https:// |
- | A simple example: | + | * " |
+ | * 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:// | ||
- | $sql = ' | + | I also agree that "SQL injection is almost a solved problem [by using] prepared statements" |
- | + | ||
- | $result = $db-> | + | |
- | Checked in the framework by: | + | ===== Usage ===== |
- | | + | By libraries: |
- | + | ||
- | | + | <code php> |
- | + | class db { | |
- | if (!is_literal($sql)) { | + | |
- | throw new Exception(' | + | function |
+ | if (function_exists(' | ||
+ | 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 403: | Line 314: | ||
==== To SAPIs ==== | ==== To SAPIs ==== | ||
- | Not sure | + | None known |
==== To Existing Extensions ==== | ==== To Existing Extensions ==== | ||
Line 415: | 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 452: | 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