2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
39 private $manifestMap = array(
40 'pre_execute'=>'pre_execute',
41 'install_mkdirs'=>'mkdir',
42 'install_copy'=>'copy',
43 'install_images'=>'image_dir',
44 'install_menus'=>'menu',
45 'install_userpage'=>'user_page',
46 'install_dashlets'=>'dashlets',
47 'install_administration'=>'administration',
48 'install_connectors'=>'connectors',
49 'install_vardefs'=>'vardefs',
50 'install_layoutdefs'=>'layoutdefs',
51 'install_layoutfields'=>'layoutfields',
52 'install_relationships'=>'relationships',
53 'install_languages'=>'language',
54 'install_logichooks'=>'logic_hooks',
55 'post_execute'=>'post_execute',
59 private $blackListExempt = array();
60 private $classBlackListExempt = array();
62 private $validExt = array('png', 'gif', 'jpg', 'css', 'js', 'php', 'txt', 'html', 'htm', 'tpl', 'pdf', 'md5', 'xml');
63 private $classBlackList = array(
64 // Class names specified here must be in lowercase as the implementation
65 // of the tokenizer converts all tokens to lowercase.
68 'reflectionzendextension',
69 'reflectionextension',
71 'reflectionfunctionabstract',
74 'reflectionparameter',
77 'reflectionexception',
80 private $blackList = array(
127 'realpath_cache_get',
128 'realpath_cache_size',
171 'call_user_func_array',
175 //mutliple files per function call
181 'move_uploaded_file',
184 'create_cache_directory',
186 'write_array_to_file',
187 'write_encoded_file',
188 'create_custom_directory',
193 'sugar_file_put_contents',
198 // Functions that have callbacks can circumvent our security measures.
199 // List retrieved through PHP's XML documentation, and running the
200 // following script in the reference directory:
202 // grep -R callable . | grep -v \.svn | grep methodparam | cut -d: -f1 | sort -u | cut -d"." -f2 | sed 's/\-/\_/g' | cut -d"/" -f4
207 // PHP internal - arrays
211 'array_intersect_uassoc',
212 'array_intersect_ukey',
216 'array_udiff_uassoc',
218 'array_uintersect_assoc',
219 'array_uintersect_uassoc',
221 'array_walk_recursive',
227 // EIO functions that accept callbacks.
261 'eio_sync_file_range',
269 // PHP internal - error functions
271 'set_exception_handler',
273 // Forms Data Format functions
276 // PHP internal - function handling
277 'call_user_func_array',
279 'forward_static_call_array',
280 'forward_static_call',
281 'register_shutdown_function',
282 'register_tick_function',
286 'setcompletecallback',
288 'setexceptioncallback',
291 'setwarningcallback',
292 'setworkloadcallback',
295 // Firebird/InterBase
296 'ibase_set_event_handler',
299 'ldap_set_rebind_proc',
302 'libxml_set_external_entity_loader',
304 // Mailparse functions
305 'mailparse_msg_extract_part_file',
306 'mailparse_msg_extract_part',
307 'mailparse_msg_extract_whole_part_file',
309 // Memcache(d) functions
318 'set_local_infile_handler',
320 // PHP internal - network functions
321 'header_register_callback',
324 'newt_entry_set_filter',
325 'newt_set_suspend_callback',
329 'timestampnoncehandler',
332 // PHP internal - output control
335 // PHP internal - PCNTL
338 // PHP internal - PCRE
339 'preg_replace_callback',
342 'sqlitecreateaggregate',
343 'sqlitecreatefunction',
344 'sqlite_create_aggregate',
345 'sqlite_create_function',
351 'readline_callback_handler_install',
352 'readline_completion_function',
354 // PHP internal - session handling
355 'session_set_save_handler',
357 // PHP internal - SPL
360 'spl_autoload_register',
363 'sybase_set_message_handler',
365 // PHP internal - variable handling
369 'xml_set_character_data_handler',
370 'xml_set_default_handler',
371 'xml_set_element_handler',
372 'xml_set_end_namespace_decl_handler',
373 'xml_set_external_entity_ref_handler',
374 'xml_set_notation_decl_handler',
375 'xml_set_processing_instruction_handler',
376 'xml_set_start_namespace_decl_handler',
377 'xml_set_unparsed_entity_decl_handler',
380 public function printToWiki(){
381 echo "'''Default Extensions'''<br>";
382 foreach($this->validExt as $b){
383 echo '#' . $b . '<br>';
386 echo "'''Default Black Listed Functions'''<br>";
387 foreach($this->blackList as $b){
388 echo '#' . $b . '<br>';
394 public function __construct(){
395 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['blackListExempt'])){
396 $this->blackListExempt = array_merge($this->blackListExempt, $GLOBALS['sugar_config']['moduleInstaller']['blackListExempt']);
398 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['blackList'])){
399 $this->blackList = array_merge($this->blackList, $GLOBALS['sugar_config']['moduleInstaller']['blackList']);
401 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['classBlackListExempt'])){
402 $this->classBlackListExempt = array_merge($this->classBlackListExempt, $GLOBALS['sugar_config']['moduleInstaller']['classBlackListExempt']);
404 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['classBlackList'])){
405 $this->classBlackList = array_merge($this->classBlackList, $GLOBALS['sugar_config']['moduleInstaller']['classBlackList']);
407 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['validExt'])){
408 $this->validExt = array_merge($this->validExt, $GLOBALS['sugar_config']['moduleInstaller']['validExt']);
413 private $issues = array();
414 private $pathToModule = '';
417 *returns a list of issues
419 public function getIssues(){
420 return $this->issues;
424 *returns true or false if any issues were found
426 public function hasIssues(){
427 return !empty($this->issues);
431 *Ensures that a file has a valid extension
433 private function isValidExtension($file){
434 $file = strtolower($file);
436 $extPos = strrpos($file, '.');
437 //make sure they don't override the files.md5
438 if($extPos === false || $file == 'files.md5')return false;
439 $ext = substr($file, $extPos + 1);
440 return in_array($ext, $this->validExt);
445 *Scans a directory and calls on scan file for each file
447 public function scanDir($path){
448 static $startPath = '';
449 if(empty($startPath))$startPath = $path;
450 if(!is_dir($path))return false;
452 while($e = $d->read()){
453 $next = $path . '/' . $e;
455 if(substr($e, 0, 1) == '.')continue;
456 $this->scanDir($next);
458 $issues = $this->scanFile($next);
467 * Check if the file contents looks like PHP
468 * @param string $contents File contents
471 public function isPHPFile($contents)
473 if(stripos($contents, '<?php') !== false) return true;
474 for($tag=0;($tag = stripos($contents, '<?', $tag)) !== false;$tag++) {
475 if(strncasecmp(substr($contents, $tag, 13), '<?xml version', 13) == 0) {
476 // <?xml version is OK, skip it
480 // found <?, it's PHP
487 * Given a file it will open it's contents and check if it is a PHP file (not safe to just rely on extensions) if it finds <?php tags it will use the tokenizer to scan the file
488 * $var() and ` are always prevented then whatever is in the blacklist.
489 * It will also ensure that all files are of valid extension types
492 public function scanFile($file){
494 if(!$this->isValidExtension($file)){
495 $issues[] = translate('ML_INVALID_EXT');
496 $this->issues['file'][$file] = $issues;
499 $contents = file_get_contents($file);
500 if(!$this->isPHPFile($contents)) return $issues;
501 $tokens = @token_get_all($contents);
502 $checkFunction = false;
505 foreach($tokens as $index=>$token){
506 if(is_string($token[0])){
509 $issues['backtick'] = translate('ML_INVALID_FUNCTION') . " '`'";
511 if($checkFunction)$issues[] = $possibleIssue;
514 $checkFunction = false;
517 $token['_msi'] = token_name($token[0]);
519 case T_WHITESPACE: continue;
521 if(in_array('eval', $this->blackList) && !in_array('eval', $this->blackListExempt))
522 $issues[]= translate('ML_INVALID_FUNCTION') . ' eval()';
525 $token[1] = strtolower($token[1]);
526 if($lastToken !== false && $lastToken[0] == T_NEW) {
527 if(!in_array($token[1], $this->classBlackList))break;
528 if(in_array($token[1], $this->classBlackListExempt))break;
529 } elseif ($token[0] == T_DOUBLE_COLON) {
530 if(!in_array($lastToken[1], $this->classBlackList))break;
531 if(in_array($lastToken[1], $this->classBlackListExempt))break;
533 if(!in_array($token[1], $this->blackList))break;
534 if(in_array($token[1], $this->blackListExempt))break;
536 if ($lastToken !== false &&
537 ($lastToken[0] == T_OBJECT_OPERATOR || $lastToken[0] == T_DOUBLE_COLON))
543 $checkFunction = true;
544 $possibleIssue = translate('ML_INVALID_FUNCTION') . ' ' . $token[1] . '()';
548 $checkFunction = false;
552 if ($token[0] != T_WHITESPACE)
560 $this->issues['file'][$file] = $issues;
568 * checks files.md5 file to see if the file is from sugar
569 * ONLY WORKS ON FILES
571 public function sugarFileExists($path){
572 static $md5 = array();
573 if(empty($md5) && file_exists('files.md5'))
575 include('files.md5');
578 if(isset($md5['./' . $path]))return true;
585 *This function will scan the Manifest for disabled actions specified in $GLOBALS['sugar_config']['moduleInstaller']['disableActions']
586 *if $GLOBALS['sugar_config']['moduleInstaller']['disableRestrictedCopy'] is set to false or not set it will call on scanCopy to ensure that it is not overriding files
588 public function scanManifest($manifestPath){
590 if(!file_exists($manifestPath)){
591 $this->issues['manifest'][$manifestPath] = translate('ML_NO_MANIFEST');
594 $fileIssues = $this->scanFile($manifestPath);
595 //if the manifest contains malicious code do not open it
596 if(!empty($fileIssues)){
599 include($manifestPath);
602 //scan for disabled actions
603 if(isset($GLOBALS['sugar_config']['moduleInstaller']['disableActions'])){
604 foreach($GLOBALS['sugar_config']['moduleInstaller']['disableActions'] as $action){
605 if(isset($installdefs[$this->manifestMap[$action]])){
606 $issues[] = translate('ML_INVALID_ACTION_IN_MANIFEST') . $this->manifestMap[$action];
611 //now lets scan for files that will override our files
612 if(empty($GLOBALS['sugar_config']['moduleInstaller']['disableRestrictedCopy']) && isset($installdefs['copy'])){
613 foreach($installdefs['copy'] as $copy){
614 $from = str_replace('<basepath>', $this->pathToModule, $copy['from']);
616 if(substr_count($from, '..')){
617 $this->issues['copy'][$from] = translate('ML_PATH_MAY_NOT_CONTAIN').' ".." -' . $from;
619 if(substr_count($to, '..')){
620 $this->issues['copy'][$to] = translate('ML_PATH_MAY_NOT_CONTAIN'). ' ".." -' . $to;
622 while(substr_count($from, '//')){
623 $from = str_replace('//', '/', $from);
625 while(substr_count($to, '//')){
626 $to = str_replace('//', '/', $to);
628 $this->scanCopy($from, $to);
632 $this->issues['manifest'][$manifestPath] = $issues;
642 * Takes in where the file will is specified to be copied from and to
643 * and ensures that there is no official sugar file there. If the file exists it will check
644 * against the MD5 file list to see if Sugar Created the file
647 function scanCopy($from, $to){
648 //if the file doesn't exist for the $to then it is not overriding anything
649 if(!file_exists($to))return;
650 //if $to is a dir and $from is a file then make $to a full file path as well
651 if(is_dir($to) && is_file($from)){
652 if(substr($to,-1) === '/'){
653 $to = substr($to, 0 , strlen($to) - 1);
655 $to .= '/'. basename($from);
657 //if the $to is a file and it is found in sugarFileExists then don't allow overriding it
658 if(is_file($to) && $this->sugarFileExists($to)){
659 $this->issues['copy'][$from] = translate('ML_OVERRIDE_CORE_FILES') . '(' . $to . ')';
664 while($e = $d->read()){
665 if($e == '.' || $e == '..')continue;
666 $this->scanCopy($from .'/'. $e, $to .'/' . $e);
678 *Main external function that takes in a path to a package and then scans
679 *that package's manifest for disabled actions and then it scans the PHP files
680 *for restricted function calls
683 public function scanPackage($path){
684 $this->pathToModule = $path;
685 $this->scanManifest($path . '/manifest.php');
686 if(empty($GLOBALS['sugar_config']['moduleInstaller']['disableFileScan'])){
687 $this->scanDir($path);
692 *This function will take all issues of the current instance and print them to the screen
694 public function displayIssues($package='Package'){
695 echo '<h2>'.str_replace('{PACKAGE}' , $package ,translate('ML_PACKAGE_SCANNING')). '</h2><BR><h2 class="error">' . translate('ML_INSTALLATION_FAILED') . '</h2><br><p>' .str_replace('{PACKAGE}' , $package ,translate('ML_PACKAGE_NOT_CONFIRM')). '</p><ul><li>'. translate('ML_OBTAIN_NEW_PACKAGE') . '<li>' . translate('ML_RELAX_LOCAL').
696 '</ul></p><br>' . translate('ML_SUGAR_LOADING_POLICY') . ' <a href=" http://kb.sugarcrm.com/custom/module-loader-restrictions-for-sugar-open-cloud/">' . translate('ML_SUGAR_KB') . '</a>.'.
697 '<br>' . translate('ML_AVAIL_RESTRICTION'). ' <a href=" http://developers.sugarcrm.com/wordpress/2009/08/14/module-loader-restrictions/">' . translate('ML_SUGAR_DZ') . '</a>.<br><br>';
700 foreach($this->issues as $type=>$issues){
701 echo '<div class="error"><h2>'. ucfirst($type) .' ' . translate('ML_ISSUES') . '</h2> </div>';
702 echo '<div id="details' . $type . '" >';
703 foreach($issues as $file=>$issue){
704 $file = str_replace($this->pathToModule . '/', '', $file);
705 echo '<div style="position:relative;left:10px"><b>' . $file . '</b></div><div style="position:relative;left:20px">';
706 if(is_array($issue)){
707 foreach($issue as $i){
718 echo "<br><input class='button' onclick='document.location.href=\"index.php?module=Administration&action=UpgradeWizard&view=module\"' type='button' value=\"" . translate('LBL_UW_BTN_BACK_TO_MOD_LOADER') . "\" />";