2 /*********************************************************************************
3 * SugarCRM Community Edition is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
6 * This program is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU Affero General Public License version 3 as published by the
8 * Free Software Foundation with the addition of the following permission added
9 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
18 * You should have received a copy of the GNU Affero General Public License along with
19 * this program; if not, see http://www.gnu.org/licenses or write to the Free
20 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26 * The interactive user interfaces in modified source and object code versions
27 * of this program must display Appropriate Legal Notices, as required under
28 * Section 5 of the GNU Affero General Public License version 3.
30 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31 * these Appropriate Legal Notices must retain the display of the "Powered by
32 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33 * technical reasons, the Appropriate Legal Notices must display the words
34 * "Powered by SugarCRM".
35 ********************************************************************************/
38 require_once 'include/php-sql-parser.php';
44 class SugarSQLValidate
47 * Parse SQL query WHERE and ORDER BY clauses and validate that nothing bad is happening there
48 * @param string $where
49 * @param string $order_by
52 public function validateQueryClauses($where, $order_by = '')
54 if(empty($where) && empty($order_by)) {
58 if(empty($where) && !empty($order_by)) {
62 $parser = new PHPSQLParser();
63 $testquery = "SELECT dummy FROM dummytable WHERE $where";
65 if(!empty($order_by)) {
66 $testquery .= " ORDER BY $order_by";
69 $parsed = $parser->parse($testquery);
70 //$GLOBALS['log']->debug("PARSE: ".var_export($parsed, true));
72 if(count($parsed) != $clauses) {
73 // we assume: SELECT, FROM, WHERE, maybe ORDER
76 $parts = array_keys($parsed);
77 if($parts[0] != "SELECT" || $parts[1] != "FROM" || $parts[2] != "WHERE") {
78 // check the keys to be SELECT, FROM, WHERE
81 if(!empty($order_by) && $parts[3] != "ORDER") {
85 // verify SELECT didn't change
86 if(count($parsed["SELECT"]) != 1 || $parsed["SELECT"][0] !== array ('expr_type' => 'colref','alias' => '`dummy`', 'base_expr' => 'dummy', 'sub_tree' => false)) {
87 $GLOBALS['log']->debug("validation failed SELECT");
90 // verify FROM didn't change
91 if(count($parsed["FROM"]) != 1 || $parsed["FROM"][0] !== array ('table' => 'dummytable', 'alias' => 'dummytable', 'join_type' => 'JOIN', 'ref_type' => '', 'ref_clause' => '', 'base_expr' => false, 'sub_tree' => false)) {
92 $GLOBALS['log']->debug("validation failed FROM");
96 if(!$this->validateExpression($parsed["WHERE"], true)) {
97 $GLOBALS['log']->debug("validation failed WHERE");
101 if(!empty($order_by) && !$this->validateExpression($parsed["ORDER"])) {
102 $GLOBALS['log']->debug("validation failed ORDER");
109 * Prohibited functions
112 protected $bad_functions = array("benchmark", "encode", "sleep",
113 "generate_series", "load_file", "sys_eval", "user_name",
114 "xp_cmdshell", "sys_exec", "sp_replwritetovarbin");
117 * Validate parsed SQL expression
118 * @param array $expr Parsed expression
121 protected function validateExpression($expr, $allow_some_subqueries = false)
123 foreach($expr as $term) {
124 if(!is_array($term)) continue;
126 if(isset($term['expr_type']) && $term['expr_type'] == 'subquery') {
127 if(!$allow_some_subqueries || !$this->allowedSubquery($term)) {
128 // subqueries are verboten, except for some very special ones
129 $GLOBALS['log']->debug("validation failed subquery");
133 if(!empty($term['sub_tree']) && !$this->validateExpression($term['sub_tree'], $allow_some_subqueries)) {
137 if(isset($term['type']) && $term['type'] == 'expression') {
140 if($term['expr_type'] == 'const' || $term['expr_type'] == 'expression') {
141 // constants are OK, expressions checked above
144 if($term['expr_type'] == 'function') {
145 // prohibit some functions
146 if(in_array(strtolower($term['base_expr']), $this->bad_functions)) {
147 $GLOBALS['log']->debug("validation failed function");
151 if($term['expr_type'] == 'colref' && !$this->validateColumnName($term['base_expr'])) {
152 // check column names
153 $GLOBALS['log']->debug("validation failed column name");
156 if(!empty($term['alias']) && $term['alias'] != $term['base_expr'] && $term['alias'] != "`".$term['base_expr']."`") {
157 $GLOBALS['log']->debug("validation failed alias: ".var_export($term, true));
165 * Tables allowed in subqueries
168 protected $subquery_allowed_tables = array(
169 'email_addr_bean_rel' => true,
170 'email_addresses' => true,
172 'emails_beans' => true,
173 'emails_text' => true,
175 'team_sets_teams' => true);
178 * Allow some subqueries to pass
179 * Needed since OPI uses subqueries for email searches... sigh
180 * @param array $term term structure of the subquery
182 protected function allowedSubquery($term)
184 // Must be SELECT ... FROM ... WHERE ...
185 if(empty($term['sub_tree']) || empty($term['sub_tree']['SELECT']) || empty($term['sub_tree']['FROM']) || empty($term['sub_tree']['WHERE'])) {
186 $GLOBALS['log']->debug("subquery validation failed: missing item");
190 foreach($term['sub_tree']['SELECT'] as $select) {
191 if($select['expr_type'] == 'operator' && $select['base_expr'] == '*') {
194 if($select['expr_type'] != 'colref') {
195 $GLOBALS['log']->debug("subquery validation failed: column: {$select['expr_type']}");
196 // allow only columns in select
201 foreach($term['sub_tree']['FROM'] as $from) {
202 if(empty($this->subquery_allowed_tables[$from['table']])) {
203 $GLOBALS['log']->debug("subquery validation failed: table: {$from['table']}");
204 // only specific tables are allowed
207 if(!empty($from['ref_clause']) && !$this->validateQueryClauses($from['ref_clause'])) {
208 // validate join condition, if bad, bail out
209 $GLOBALS['log']->debug("subquery validation failed: join: {$from['ref_clause']}");
214 if(!$this->validateExpression($term['sub_tree']['WHERE'])) {
215 // validate where clause, no sub-subqueries allowed here
216 $GLOBALS['log']->debug("subquery validation failed: where clause");
225 * This method validates the column name portion of the SQL statement and returns true if it is deemed safe.
226 * We check against querying for the user_hash column.
228 * @param $name String portion of the column name from SQL
229 * @return boolean True if column name is deemed safe, false otherwise
231 protected function validateColumnName($name)
233 if($name == ",") return true; // sometimes , gets as column name
234 $name = strtolower($name); // case does not matter
236 $parts = explode(".", $name);
237 if(count($parts) > 2) {
242 foreach($parts AS $part)
244 //the user_hash column is forbidden in passed in SQL
245 if($part == "user_hash")
250 //Remove leading and trailing ` characters for the part
251 if(preg_match('/^[\`](.+?)[\`]$/', $part, $matches))
256 //We added an exception for # symbol (see Bug 50324)
257 //This should be removed when Bug 50360 is resolved
258 if(preg_match('/[^a-z0-9._#]/', $part)) {