]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarSQLValidate.php
Release 6.5.16
[Github/sugarcrm.git] / include / SugarSQLValidate.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
5  * 
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.
12  * 
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
16  * details.
17  * 
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
21  * 02110-1301 USA.
22  * 
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.
25  * 
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.
29  * 
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  ********************************************************************************/
36
37
38 require_once 'include/php-sql-parser.php';
39
40 /**
41  * SQL Validator class
42  * @api
43  */
44 class SugarSQLValidate
45 {
46         /**
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
50          * @return bool
51          */
52         public function validateQueryClauses($where, $order_by = '')
53         {
54             if(empty($where) && empty($order_by)) {
55                 return true;
56             }
57
58             if(empty($where) && !empty($order_by)) {
59                 $where = "deleted=0";
60             }
61
62                 $parser = new PHPSQLParser();
63                 $testquery = "SELECT dummy FROM dummytable WHERE $where";
64                 $clauses = 3;
65                 if(!empty($order_by)) {
66                     $testquery .= " ORDER BY $order_by";
67                     $clauses++;
68                 }
69                 $parsed = $parser->parse($testquery);
70                 //$GLOBALS['log']->debug("PARSE: ".var_export($parsed, true));
71
72                 if(count($parsed) != $clauses) {
73                     // we assume: SELECT, FROM, WHERE, maybe ORDER
74                     return false;
75                 }
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
79                     return false;
80                 }
81                 if(!empty($order_by) && $parts[3] != "ORDER") {
82                     // extra key is ORDER
83                     return false;
84                 }
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");
88             return false;
89         }
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");
93             return false;
94         }
95         // check WHERE
96         if(!$this->validateExpression($parsed["WHERE"], true)) {
97             $GLOBALS['log']->debug("validation failed WHERE");
98             return false;
99         }
100         // check ORDER
101         if(!empty($order_by) && !$this->validateExpression($parsed["ORDER"])) {
102             $GLOBALS['log']->debug("validation failed ORDER");
103             return false;
104         }
105                 return true;
106         }
107
108         /**
109          * Prohibited functions
110          * @var array
111          */
112         protected $bad_functions = array("benchmark", "encode", "sleep",
113         "generate_series", "load_file", "sys_eval", "user_name",
114         "xp_cmdshell", "sys_exec", "sp_replwritetovarbin");
115
116         /**
117          * Validate parsed SQL expression
118          * @param array $expr Parsed expression
119          * @return bool
120          */
121         protected function validateExpression($expr, $allow_some_subqueries = false)
122         {
123             foreach($expr as $term) {
124                 if(!is_array($term)) continue;
125                 // check subtrees
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");
130                     return false;
131                 }
132                 } else {
133                     if(!empty($term['sub_tree']) && !$this->validateExpression($term['sub_tree'], $allow_some_subqueries)) {
134                     return false;
135                     }
136                 }
137                 if(isset($term['type']) && $term['type'] == 'expression') {
138                     continue;
139                 }
140                 if($term['expr_type'] == 'const' || $term['expr_type'] == 'expression') {
141                     // constants are OK, expressions checked above
142                     continue;
143                 }
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");
148                         return false;
149                     }
150                 }
151                 if($term['expr_type'] == 'colref' && !$this->validateColumnName($term['base_expr'])) {
152                     // check column names
153                     $GLOBALS['log']->debug("validation failed column name");
154                     return false;
155                 }
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));
158                     return false;
159                 }
160             }
161             return true;
162         }
163
164         /**
165          * Tables allowed in subqueries
166          * @var array
167          */
168         protected $subquery_allowed_tables = array(
169                 'email_addr_bean_rel' => true,
170                 'email_addresses' => true,
171                 'emails' => true,
172                 'emails_beans' => true,
173                 'emails_text' => true,
174                 'teams' => true,
175                 'team_sets_teams' => true);
176
177         /**
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
181          */
182         protected function allowedSubquery($term)
183         {
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");
187                 return false;
188             }
189
190             foreach($term['sub_tree']['SELECT'] as $select) {
191                 if($select['expr_type'] == 'operator' && $select['base_expr'] == '*') {
192                     continue;
193                 }
194                 if($select['expr_type'] != 'colref') {
195                     $GLOBALS['log']->debug("subquery validation failed: column: {$select['expr_type']}");
196                     // allow only columns in select
197                     return false;
198                 }
199             }
200
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
205                     return false;
206                 }
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']}");
210                 return false;
211                 }
212             }
213
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");
217                 return false;
218             }
219
220             return true;
221         }
222
223         /**
224          * validateColumnName
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.
227      *
228          * @param $name String portion of the column name from SQL
229          * @return boolean True if column name is deemed safe, false otherwise
230          */
231         protected function validateColumnName($name)
232         {
233             if($name == ",") return true; // sometimes , gets as column name
234             $name = strtolower($name); // case does not matter
235
236             $parts = explode(".", $name);
237             if(count($parts) > 2) {
238                 // too many dots
239                 return false;
240             }
241
242         foreach($parts AS $part)
243         {
244             //the user_hash column is forbidden in passed in SQL
245             if($part == "user_hash")
246             {
247                 return false;
248             }
249
250             //Remove leading and trailing ` characters for the part
251             if(preg_match('/^[\`](.+?)[\`]$/', $part, $matches))
252             {
253                $part = $matches[1];
254             }
255
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)) {
259                 // bad chars in name
260                 return false;
261             }
262
263         }
264
265             return true;
266         }
267 }