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-2013 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',
63 private $config = array();
66 private $blackListExempt = array();
67 private $classBlackListExempt = array();
69 private $validExt = array('png', 'gif', 'jpg', 'css', 'js', 'php', 'txt', 'html', 'htm', 'tpl', 'pdf', 'md5', 'xml');
70 private $classBlackList = array(
71 // Class names specified here must be in lowercase as the implementation
72 // of the tokenizer converts all tokens to lowercase.
75 'reflectionzendextension',
76 'reflectionextension',
78 'reflectionfunctionabstract',
81 'reflectionparameter',
84 'reflectionexception',
92 private $blackList = array(
141 'realpath_cache_get',
142 'realpath_cache_size',
187 'call_user_func_array',
191 //mutliple files per function call
197 'move_uploaded_file',
200 'create_cache_directory',
202 'write_array_to_file',
203 'write_encoded_file',
204 'create_custom_directory',
209 'sugar_file_put_contents',
214 // Functions that have callbacks can circumvent our security measures.
215 // List retrieved through PHP's XML documentation, and running the
216 // following script in the reference directory:
218 // grep -R callable . | grep -v \.svn | grep methodparam | cut -d: -f1 | sort -u | cut -d"." -f2 | sed 's/\-/\_/g' | cut -d"/" -f4
223 // PHP internal - arrays
227 'array_intersect_uassoc',
228 'array_intersect_ukey',
232 'array_udiff_uassoc',
234 'array_uintersect_assoc',
235 'array_uintersect_uassoc',
237 'array_walk_recursive',
243 // EIO functions that accept callbacks.
277 'eio_sync_file_range',
285 // PHP internal - error functions
287 'set_exception_handler',
289 // Forms Data Format functions
292 // PHP internal - function handling
293 'call_user_func_array',
295 'forward_static_call_array',
296 'forward_static_call',
297 'register_shutdown_function',
298 'register_tick_function',
302 'setcompletecallback',
304 'setexceptioncallback',
307 'setwarningcallback',
308 'setworkloadcallback',
311 // Firebird/InterBase
312 'ibase_set_event_handler',
315 'ldap_set_rebind_proc',
318 'libxml_set_external_entity_loader',
320 // Mailparse functions
321 'mailparse_msg_extract_part_file',
322 'mailparse_msg_extract_part',
323 'mailparse_msg_extract_whole_part_file',
325 // Memcache(d) functions
334 'set_local_infile_handler',
336 // PHP internal - network functions
337 'header_register_callback',
340 'newt_entry_set_filter',
341 'newt_set_suspend_callback',
345 'timestampnoncehandler',
348 // PHP internal - output control
351 // PHP internal - PCNTL
354 // PHP internal - PCRE
355 'preg_replace_callback',
358 'sqlitecreateaggregate',
359 'sqlitecreatefunction',
360 'sqlite_create_aggregate',
361 'sqlite_create_function',
367 'readline_callback_handler_install',
368 'readline_completion_function',
370 // PHP internal - session handling
371 'session_set_save_handler',
373 // PHP internal - SPL
376 'spl_autoload_register',
379 'sybase_set_message_handler',
381 // PHP internal - variable handling
385 'xml_set_character_data_handler',
386 'xml_set_default_handler',
387 'xml_set_element_handler',
388 'xml_set_end_namespace_decl_handler',
389 'xml_set_external_entity_ref_handler',
390 'xml_set_notation_decl_handler',
391 'xml_set_processing_instruction_handler',
392 'xml_set_start_namespace_decl_handler',
393 'xml_set_unparsed_entity_decl_handler',
399 private $methodsBlackList = array('setlevel', 'put' => array('sugarautoloader'), 'unlink' => array('sugarautoloader'));
401 public function printToWiki(){
402 echo "'''Default Extensions'''<br>";
403 foreach($this->validExt as $b){
404 echo '#' . $b . '<br>';
407 echo "'''Default Black Listed Functions'''<br>";
408 foreach($this->blackList as $b){
409 echo '#' . $b . '<br>';
415 public function __construct()
418 'blackListExempt' => 'MODULE_INSTALLER_PACKAGE_SCAN_BLACK_LIST_EXEMPT',
419 'blackList' => 'MODULE_INSTALLER_PACKAGE_SCAN_BLACK_LIST',
420 'classBlackListExempt' => 'MODULE_INSTALLER_PACKAGE_SCAN_CLASS_BLACK_LIST_EXEMPT',
421 'classBlackList' => 'MODULE_INSTALLER_PACKAGE_SCAN_CLASS_BLACK_LIST',
422 'validExt' => 'MODULE_INSTALLER_PACKAGE_SCAN_VALID_EXT',
423 'methodsBlackList' => 'MODULE_INSTALLER_PACKAGE_SCAN_METHOD_LIST',
426 $disableConfigOverride = defined('MODULE_INSTALLER_DISABLE_CONFIG_OVERRIDE')
427 && MODULE_INSTALLER_DISABLE_CONFIG_OVERRIDE;
429 $disableDefineOverride = defined('MODULE_INSTALLER_DISABLE_DEFINE_OVERRIDE')
430 && MODULE_INSTALLER_DISABLE_DEFINE_OVERRIDE;
432 if (!$disableConfigOverride && !empty($GLOBALS['sugar_config']['moduleInstaller'])) {
433 $this->config = $GLOBALS['sugar_config']['moduleInstaller'];
436 foreach ($params as $param => $constName) {
438 if (!$disableConfigOverride && isset($this->config[$param]) && is_array($this->config[$param])) {
439 $this->{$param} = array_merge($this->{$param}, $this->config[$param]);
442 if (!$disableDefineOverride && defined($constName)) {
443 $value = constant($constName);
444 $value = explode(',', $value);
445 $value = array_map('trim', $value);
446 $value = array_filter($value, 'strlen');
447 $this->{$param} = array_merge($this->{$param}, $value);
452 private $issues = array();
453 private $pathToModule = '';
456 *returns a list of issues
458 public function getIssues(){
459 return $this->issues;
463 *returns true or false if any issues were found
465 public function hasIssues(){
466 return !empty($this->issues);
470 *Ensures that a file has a valid extension
472 private function isValidExtension($file){
473 $file = strtolower($file);
475 $extPos = strrpos($file, '.');
476 //make sure they don't override the files.md5
477 if($extPos === false || $file == 'files.md5')return false;
478 $ext = substr($file, $extPos + 1);
479 return in_array($ext, $this->validExt);
484 *Scans a directory and calls on scan file for each file
486 public function scanDir($path){
487 static $startPath = '';
488 if(empty($startPath))$startPath = $path;
489 if(!is_dir($path))return false;
491 while($e = $d->read()){
492 $next = $path . '/' . $e;
494 if(substr($e, 0, 1) == '.')continue;
495 $this->scanDir($next);
497 $issues = $this->scanFile($next);
506 * Check if the file contents looks like PHP
507 * @param string $contents File contents
510 public function isPHPFile($contents)
512 if(stripos($contents, '<?php') !== false) return true;
513 for($tag=0;($tag = stripos($contents, '<?', $tag)) !== false;$tag++) {
514 if(strncasecmp(substr($contents, $tag, 13), '<?xml version', 13) == 0) {
515 // <?xml version is OK, skip it
519 // found <?, it's PHP
526 * 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
527 * $var() and ` are always prevented then whatever is in the blacklist.
528 * It will also ensure that all files are of valid extension types
531 public function scanFile($file){
533 if(!$this->isValidExtension($file)){
534 $issues[] = translate('ML_INVALID_EXT');
535 $this->issues['file'][$file] = $issues;
538 $contents = file_get_contents($file);
539 if(!$this->isPHPFile($contents)) return $issues;
540 $tokens = @token_get_all($contents);
541 $checkFunction = false;
544 foreach($tokens as $index=>$token){
545 if(is_string($token[0])){
548 $issues['backtick'] = translate('ML_INVALID_FUNCTION') . " '`'";
550 if($checkFunction)$issues[] = $possibleIssue;
553 $checkFunction = false;
556 $token['_msi'] = token_name($token[0]);
558 case T_WHITESPACE: continue;
560 if(in_array('eval', $this->blackList) && !in_array('eval', $this->blackListExempt))
561 $issues[]= translate('ML_INVALID_FUNCTION') . ' eval()';
564 $token[1] = strtolower($token[1]);
565 if($lastToken !== false && $lastToken[0] == T_NEW) {
566 if(!in_array($token[1], $this->classBlackList))break;
567 if(in_array($token[1], $this->classBlackListExempt))break;
568 } elseif ($token[0] == T_DOUBLE_COLON) {
569 if(!in_array($lastToken[1], $this->classBlackList))break;
570 if(in_array($lastToken[1], $this->classBlackListExempt))break;
572 //if nothing else fit, lets check the last token to see if this is a possible method call
573 if ($lastToken !== false &&
574 ($lastToken[0] == T_OBJECT_OPERATOR || $lastToken[0] == T_DOUBLE_COLON))
576 // check static blacklist for methods
577 if(!empty($this->methodsBlackList[$token[1]])) {
578 if($this->methodsBlackList[$token[1]] == '*') {
579 $issues[]= translate('ML_INVALID_METHOD') . ' ' .$token[1]. '()';
582 if($lastToken[0] == T_DOUBLE_COLON && $index > 2 && $tokens[$index-2][0] == T_STRING) {
583 $classname = strtolower($tokens[$index-2][1]);
584 if(in_array($classname, $this->methodsBlackList[$token[1]])) {
585 $issues[]= translate('ML_INVALID_METHOD') . ' ' .$classname . '::' . $token[1]. '()';
591 //this is a method call, check the black list
592 if(in_array($token[1], $this->methodsBlackList)){
593 $issues[]= translate('ML_INVALID_METHOD') . ' ' .$token[1]. '()';
599 if(!in_array($token[1], $this->blackList))break;
600 if(in_array($token[1], $this->blackListExempt))break;
604 $checkFunction = true;
605 $possibleIssue = translate('ML_INVALID_FUNCTION') . ' ' . $token[1] . '()';
609 $checkFunction = false;
613 if ($token[0] != T_WHITESPACE)
621 $this->issues['file'][$file] = $issues;
629 * checks files.md5 file to see if the file is from sugar
630 * ONLY WORKS ON FILES
632 public function sugarFileExists($path){
633 static $md5 = array();
634 if(empty($md5) && file_exists('files.md5'))
636 include('files.md5');
639 if(isset($md5['./' . $path]))return true;
646 *This function will scan the Manifest for disabled actions specified in $GLOBALS['sugar_config']['moduleInstaller']['disableActions']
647 *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
649 public function scanManifest($manifestPath){
651 if(!file_exists($manifestPath)){
652 $this->issues['manifest'][$manifestPath] = translate('ML_NO_MANIFEST');
655 $fileIssues = $this->scanFile($manifestPath);
656 //if the manifest contains malicious code do not open it
657 if(!empty($fileIssues)){
661 list($manifest, $installdefs) = MSLoadManifest($manifestPath);
662 $fileIssues = $this->checkConfig($manifestPath);
663 if(!empty($fileIssues)){
667 //scan for disabled actions
668 if(isset($this->config['disableActions'])){
669 foreach($this->config['disableActions'] as $action){
670 if(isset($installdefs[$this->manifestMap[$action]])){
671 $issues[] = translate('ML_INVALID_ACTION_IN_MANIFEST') . $this->manifestMap[$action];
676 //now lets scan for files that will override our files
677 if(empty($this->config['disableRestrictedCopy']) && isset($installdefs['copy'])){
678 foreach($installdefs['copy'] as $copy){
679 $from = str_replace('<basepath>', $this->pathToModule, $copy['from']);
681 if(substr_count($from, '..')){
682 $this->issues['copy'][$from] = translate('ML_PATH_MAY_NOT_CONTAIN').' ".." -' . $from;
684 if(substr_count($to, '..')){
685 $this->issues['copy'][$to] = translate('ML_PATH_MAY_NOT_CONTAIN'). ' ".." -' . $to;
687 while(substr_count($from, '//')){
688 $from = str_replace('//', '/', $from);
690 while(substr_count($to, '//')){
691 $to = str_replace('//', '/', $to);
693 $this->scanCopy($from, $to);
697 $this->issues['manifest'][$manifestPath] = $issues;
707 * Takes in where the file will is specified to be copied from and to
708 * and ensures that there is no official sugar file there. If the file exists it will check
709 * against the MD5 file list to see if Sugar Created the file
712 function scanCopy($from, $to){
713 //if the file doesn't exist for the $to then it is not overriding anything
714 if(!file_exists($to))return;
715 //if $to is a dir and $from is a file then make $to a full file path as well
716 if(is_dir($to) && is_file($from)){
717 if(substr($to,-1) === '/'){
718 $to = substr($to, 0 , strlen($to) - 1);
720 $to .= '/'. basename($from);
722 //if the $to is a file and it is found in sugarFileExists then don't allow overriding it
723 if(is_file($to) && $this->sugarFileExists($to)){
724 $this->issues['copy'][$from] = translate('ML_OVERRIDE_CORE_FILES') . '(' . $to . ')';
729 while($e = $d->read()){
730 if($e == '.' || $e == '..')continue;
731 $this->scanCopy($from .'/'. $e, $to .'/' . $e);
743 *Main external function that takes in a path to a package and then scans
744 *that package's manifest for disabled actions and then it scans the PHP files
745 *for restricted function calls
748 public function scanPackage($path){
749 $this->pathToModule = $path;
750 $this->scanManifest($path . '/manifest.php');
751 if(empty($this->config['disableFileScan'])){
752 $this->scanDir($path);
757 *This function will take all issues of the current instance and print them to the screen
759 public function displayIssues($package='Package'){
760 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').
761 '</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>.'.
762 '<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>';
765 foreach($this->issues as $type=>$issues){
766 echo '<div class="error"><h2>'. ucfirst($type) .' ' . translate('ML_ISSUES') . '</h2> </div>';
767 echo '<div id="details' . $type . '" >';
768 foreach($issues as $file=>$issue){
769 $file = str_replace($this->pathToModule . '/', '', $file);
770 echo '<div style="position:relative;left:10px"><b>' . $file . '</b></div><div style="position:relative;left:20px">';
771 if(is_array($issue)){
772 foreach($issue as $i){
783 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') . "\" />";
788 * Lock config settings
790 public function lockConfig()
792 if(empty($this->config_hash)) {
793 $this->config_hash = md5(serialize($GLOBALS['sugar_config']));
798 * Check if config was modified. Return
799 * @param string $file
800 * @return array Errors if something wrong, false if no problems
802 public function checkConfig($file)
804 $config_hash_after = md5(serialize($GLOBALS['sugar_config']));
805 if($config_hash_after != $this->config_hash) {
806 $this->issues['file'][$file] = array(translate('ML_CONFIG_OVERRIDE'));
807 return $this->issues;
816 * Outside of the class to isolate the context
817 * @param string $manifest_file
820 function MSLoadManifest($manifest_file)
822 include( $manifest_file );
823 return array($manifest, $installdefs);