]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarSQLValidate.php
Release 6.4.0
[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-2011 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                 // check subtrees
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");
129                     return false;
130                 }
131                 } else {
132                     if(!empty($term['sub_tree']) && !$this->validateExpression($term['sub_tree'], $allow_some_subqueries)) {
133                     return false;
134                     }
135                 }
136                 if(isset($term['type']) && $term['type'] == 'expression') {
137                     continue;
138                 }
139                 if($term['expr_type'] == 'const' || $term['expr_type'] == 'expression') {
140                     // constants are OK, expressions checked above
141                     continue;
142                 }
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");
147                         return false;
148                     }
149                 }
150                 if($term['expr_type'] == 'colref' && !$this->validateColumnName($term['base_expr'])) {
151                     // check column names
152                     $GLOBALS['log']->debug("validation failed column name");
153                     return false;
154                 }
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));
157                     return false;
158                 }
159             }
160             return true;
161         }
162
163         /**
164          * Tables allowed in subqueries
165          * @var array
166          */
167         protected $subquery_allowed_tables = array(
168                 'email_addr_bean_rel' => true,
169                 'email_addresses' => true,
170                 'emails' => true,
171                 'emails_beans' => true,
172                 'emails_text' => true,
173                 'teams' => true,
174                 'team_sets_teams' => true);
175
176         /**
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
180          */
181         protected function allowedSubquery($term)
182         {
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");
186                 return false;
187             }
188
189             foreach($term['sub_tree']['SELECT'] as $select) {
190                 if($select['expr_type'] == 'operator' && $select['base_expr'] == '*') {
191                     continue;
192                 }
193                 if($select['expr_type'] != 'colref') {
194                     $GLOBALS['log']->debug("subquery validation failed: column: {$select['expr_type']}");
195                     // allow only columns in select
196                     return false;
197                 }
198             }
199
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
204                     return false;
205                 }
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']}");
209                 return false;
210                 }
211             }
212
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");
216                 return false;
217             }
218
219             return true;
220         }
221
222         /**
223          * Validate column name
224          * @param string $name
225          * @return bool
226          */
227         protected function validateColumnName($name)
228         {
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)) {
232                 // bad chars in name
233                 return false;
234             }
235             $parts = explode(".", $name);
236             if(count($parts) > 2) {
237                 // too many dots
238                 return false;
239             }
240             if($parts[0] == "user_hash" || (!empty($parts[1]) && $parts[1] == "user_hash")) {
241                 // this column is verboten
242                 return false;
243             }
244             return true;
245         }
246 }