2 /*********************************************************************************
3 * SugarCRM Community Edition is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2011 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) {
125 if(isset($term['expr_type']) && $term['expr_type'] == 'subquery') {
126 if(!$allow_some_subqueries || !$this->allowedSubquery($term)) {
127 // subqueries are verboten, except for some very special ones
128 $GLOBALS['log']->debug("validation failed subquery");
132 if(!empty($term['sub_tree']) && !$this->validateExpression($term['sub_tree'], $allow_some_subqueries)) {
136 if(isset($term['type']) && $term['type'] == 'expression') {
139 if($term['expr_type'] == 'const' || $term['expr_type'] == 'expression') {
140 // constants are OK, expressions checked above
143 if($term['expr_type'] == 'function') {
144 // prohibit some functions
145 if(in_array(strtolower($term['base_expr']), $this->bad_functions)) {
146 $GLOBALS['log']->debug("validation failed function");
150 if($term['expr_type'] == 'colref' && !$this->validateColumnName($term['base_expr'])) {
151 // check column names
152 $GLOBALS['log']->debug("validation failed column name");
155 if(!empty($term['alias']) && $term['alias'] != $term['base_expr'] && $term['alias'] != "`".$term['base_expr']."`") {
156 $GLOBALS['log']->debug("validation failed alias: ".var_export($term, true));
164 * Tables allowed in subqueries
167 protected $subquery_allowed_tables = array(
168 'email_addr_bean_rel' => true,
169 'email_addresses' => true,
171 'emails_beans' => true,
172 'emails_text' => true,
174 'team_sets_teams' => true);
177 * Allow some subqueries to pass
178 * Needed since OPI uses subqueries for email searches... sigh
179 * @param array $term term structure of the subquery
181 protected function allowedSubquery($term)
183 // Must be SELECT ... FROM ... WHERE ...
184 if(empty($term['sub_tree']) || empty($term['sub_tree']['SELECT']) || empty($term['sub_tree']['FROM']) || empty($term['sub_tree']['WHERE'])) {
185 $GLOBALS['log']->debug("subquery validation failed: missing item");
189 foreach($term['sub_tree']['SELECT'] as $select) {
190 if($select['expr_type'] == 'operator' && $select['base_expr'] == '*') {
193 if($select['expr_type'] != 'colref') {
194 $GLOBALS['log']->debug("subquery validation failed: column: {$select['expr_type']}");
195 // allow only columns in select
200 foreach($term['sub_tree']['FROM'] as $from) {
201 if(empty($this->subquery_allowed_tables[$from['table']])) {
202 $GLOBALS['log']->debug("subquery validation failed: table: {$from['table']}");
203 // only specific tables are allowed
206 if(!empty($from['ref_clause']) && !$this->validateQueryClauses($from['ref_clause'])) {
207 // validate join condition, if bad, bail out
208 $GLOBALS['log']->debug("subquery validation failed: join: {$from['ref_clause']}");
213 if(!$this->validateExpression($term['sub_tree']['WHERE'])) {
214 // validate where clause, no sub-subqueries allowed here
215 $GLOBALS['log']->debug("subquery validation failed: where clause");
223 * Validate column name
224 * @param string $name
227 protected function validateColumnName($name)
229 if($name == ",") return true; // sometimes , gets as column name
230 $name = strtolower($name); // case does not matter
231 if(preg_match("/[^a-z0-9._]/", $name)) {
235 $parts = explode(".", $name);
236 if(count($parts) > 2) {
240 if($parts[0] == "user_hash" || (!empty($parts[1]) && $parts[1] == "user_hash")) {
241 // this column is verboten