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',
87 private $blackList = array(
134 'realpath_cache_get',
135 'realpath_cache_size',
178 'call_user_func_array',
182 //mutliple files per function call
188 'move_uploaded_file',
191 'create_cache_directory',
193 'write_array_to_file',
194 'write_encoded_file',
195 'create_custom_directory',
200 'sugar_file_put_contents',
205 // Functions that have callbacks can circumvent our security measures.
206 // List retrieved through PHP's XML documentation, and running the
207 // following script in the reference directory:
209 // grep -R callable . | grep -v \.svn | grep methodparam | cut -d: -f1 | sort -u | cut -d"." -f2 | sed 's/\-/\_/g' | cut -d"/" -f4
214 // PHP internal - arrays
218 'array_intersect_uassoc',
219 'array_intersect_ukey',
223 'array_udiff_uassoc',
225 'array_uintersect_assoc',
226 'array_uintersect_uassoc',
228 'array_walk_recursive',
234 // EIO functions that accept callbacks.
268 'eio_sync_file_range',
276 // PHP internal - error functions
278 'set_exception_handler',
280 // Forms Data Format functions
283 // PHP internal - function handling
284 'call_user_func_array',
286 'forward_static_call_array',
287 'forward_static_call',
288 'register_shutdown_function',
289 'register_tick_function',
293 'setcompletecallback',
295 'setexceptioncallback',
298 'setwarningcallback',
299 'setworkloadcallback',
302 // Firebird/InterBase
303 'ibase_set_event_handler',
306 'ldap_set_rebind_proc',
309 'libxml_set_external_entity_loader',
311 // Mailparse functions
312 'mailparse_msg_extract_part_file',
313 'mailparse_msg_extract_part',
314 'mailparse_msg_extract_whole_part_file',
316 // Memcache(d) functions
325 'set_local_infile_handler',
327 // PHP internal - network functions
328 'header_register_callback',
331 'newt_entry_set_filter',
332 'newt_set_suspend_callback',
336 'timestampnoncehandler',
339 // PHP internal - output control
342 // PHP internal - PCNTL
345 // PHP internal - PCRE
346 'preg_replace_callback',
349 'sqlitecreateaggregate',
350 'sqlitecreatefunction',
351 'sqlite_create_aggregate',
352 'sqlite_create_function',
358 'readline_callback_handler_install',
359 'readline_completion_function',
361 // PHP internal - session handling
362 'session_set_save_handler',
364 // PHP internal - SPL
367 'spl_autoload_register',
370 'sybase_set_message_handler',
372 // PHP internal - variable handling
376 'xml_set_character_data_handler',
377 'xml_set_default_handler',
378 'xml_set_element_handler',
379 'xml_set_end_namespace_decl_handler',
380 'xml_set_external_entity_ref_handler',
381 'xml_set_notation_decl_handler',
382 'xml_set_processing_instruction_handler',
383 'xml_set_start_namespace_decl_handler',
384 'xml_set_unparsed_entity_decl_handler',
386 private $methodsBlackList = array('setlevel');
388 public function printToWiki(){
389 echo "'''Default Extensions'''<br>";
390 foreach($this->validExt as $b){
391 echo '#' . $b . '<br>';
394 echo "'''Default Black Listed Functions'''<br>";
395 foreach($this->blackList as $b){
396 echo '#' . $b . '<br>';
402 public function __construct()
405 'blackListExempt' => 'MODULE_INSTALLER_PACKAGE_SCAN_BLACK_LIST_EXEMPT',
406 'blackList' => 'MODULE_INSTALLER_PACKAGE_SCAN_BLACK_LIST',
407 'classBlackListExempt' => 'MODULE_INSTALLER_PACKAGE_SCAN_CLASS_BLACK_LIST_EXEMPT',
408 'classBlackList' => 'MODULE_INSTALLER_PACKAGE_SCAN_CLASS_BLACK_LIST',
409 'validExt' => 'MODULE_INSTALLER_PACKAGE_SCAN_VALID_EXT',
412 $disableConfigOverride = defined('MODULE_INSTALLER_DISABLE_CONFIG_OVERRIDE')
413 && MODULE_INSTALLER_DISABLE_CONFIG_OVERRIDE;
415 $disableDefineOverride = defined('MODULE_INSTALLER_DISABLE_DEFINE_OVERRIDE')
416 && MODULE_INSTALLER_DISABLE_DEFINE_OVERRIDE;
418 if (!$disableConfigOverride && !empty($GLOBALS['sugar_config']['moduleInstaller'])) {
419 $this->config = $GLOBALS['sugar_config']['moduleInstaller'];
422 foreach ($params as $param => $constName) {
424 if (!$disableConfigOverride && isset($this->config[$param]) && is_array($this->config[$param])) {
425 $this->{$param} = array_merge($this->{$param}, $this->config[$param]);
428 if (!$disableDefineOverride && defined($constName)) {
429 $value = constant($constName);
430 $value = explode(',', $value);
431 $value = array_map('trim', $value);
432 $value = array_filter($value, 'strlen');
433 $this->{$param} = array_merge($this->{$param}, $value);
438 private $issues = array();
439 private $pathToModule = '';
442 *returns a list of issues
444 public function getIssues(){
445 return $this->issues;
449 *returns true or false if any issues were found
451 public function hasIssues(){
452 return !empty($this->issues);
456 *Ensures that a file has a valid extension
458 private function isValidExtension($file){
459 $file = strtolower($file);
461 $extPos = strrpos($file, '.');
462 //make sure they don't override the files.md5
463 if($extPos === false || $file == 'files.md5')return false;
464 $ext = substr($file, $extPos + 1);
465 return in_array($ext, $this->validExt);
470 *Scans a directory and calls on scan file for each file
472 public function scanDir($path){
473 static $startPath = '';
474 if(empty($startPath))$startPath = $path;
475 if(!is_dir($path))return false;
477 while($e = $d->read()){
478 $next = $path . '/' . $e;
480 if(substr($e, 0, 1) == '.')continue;
481 $this->scanDir($next);
483 $issues = $this->scanFile($next);
492 * Check if the file contents looks like PHP
493 * @param string $contents File contents
496 public function isPHPFile($contents)
498 if(stripos($contents, '<?php') !== false) return true;
499 for($tag=0;($tag = stripos($contents, '<?', $tag)) !== false;$tag++) {
500 if(strncasecmp(substr($contents, $tag, 13), '<?xml version', 13) == 0) {
501 // <?xml version is OK, skip it
505 // found <?, it's PHP
512 * 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
513 * $var() and ` are always prevented then whatever is in the blacklist.
514 * It will also ensure that all files are of valid extension types
517 public function scanFile($file){
519 if(!$this->isValidExtension($file)){
520 $issues[] = translate('ML_INVALID_EXT');
521 $this->issues['file'][$file] = $issues;
524 $contents = file_get_contents($file);
525 if(!$this->isPHPFile($contents)) return $issues;
526 $tokens = @token_get_all($contents);
527 $checkFunction = false;
530 foreach($tokens as $index=>$token){
531 if(is_string($token[0])){
534 $issues['backtick'] = translate('ML_INVALID_FUNCTION') . " '`'";
536 if($checkFunction)$issues[] = $possibleIssue;
539 $checkFunction = false;
542 $token['_msi'] = token_name($token[0]);
544 case T_WHITESPACE: continue;
546 if(in_array('eval', $this->blackList) && !in_array('eval', $this->blackListExempt))
547 $issues[]= translate('ML_INVALID_FUNCTION') . ' eval()';
550 $token[1] = strtolower($token[1]);
551 if($lastToken !== false && $lastToken[0] == T_NEW) {
552 if(!in_array($token[1], $this->classBlackList))break;
553 if(in_array($token[1], $this->classBlackListExempt))break;
554 } elseif ($token[0] == T_DOUBLE_COLON) {
555 if(!in_array($lastToken[1], $this->classBlackList))break;
556 if(in_array($lastToken[1], $this->classBlackListExempt))break;
558 //if nothing else fit, lets check the last token to see if this is a possible method call
559 if ($lastToken !== false &&
560 ($lastToken[0] == T_OBJECT_OPERATOR || $lastToken[0] == T_DOUBLE_COLON))
562 //this is a method call, check the black list
563 if(in_array($token[1], $this->methodsBlackList)){
564 $issues[]= translate('ML_INVALID_METHOD') . ' ' .$token[1]. '()';
570 if(!in_array($token[1], $this->blackList))break;
571 if(in_array($token[1], $this->blackListExempt))break;
575 $checkFunction = true;
576 $possibleIssue = translate('ML_INVALID_FUNCTION') . ' ' . $token[1] . '()';
580 $checkFunction = false;
584 if ($token[0] != T_WHITESPACE)
592 $this->issues['file'][$file] = $issues;
600 * checks files.md5 file to see if the file is from sugar
601 * ONLY WORKS ON FILES
603 public function sugarFileExists($path){
604 static $md5 = array();
605 if(empty($md5) && file_exists('files.md5'))
607 include('files.md5');
610 if(isset($md5['./' . $path]))return true;
617 *This function will scan the Manifest for disabled actions specified in $GLOBALS['sugar_config']['moduleInstaller']['disableActions']
618 *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
620 public function scanManifest($manifestPath){
622 if(!file_exists($manifestPath)){
623 $this->issues['manifest'][$manifestPath] = translate('ML_NO_MANIFEST');
626 $fileIssues = $this->scanFile($manifestPath);
627 //if the manifest contains malicious code do not open it
628 if(!empty($fileIssues)){
632 list($manifest, $installdefs) = MSLoadManifest($manifestPath);
633 $fileIssues = $this->checkConfig($manifestPath);
634 if(!empty($fileIssues)){
638 //scan for disabled actions
639 if(isset($this->config['disableActions'])){
640 foreach($this->config['disableActions'] as $action){
641 if(isset($installdefs[$this->manifestMap[$action]])){
642 $issues[] = translate('ML_INVALID_ACTION_IN_MANIFEST') . $this->manifestMap[$action];
647 //now lets scan for files that will override our files
648 if(empty($this->config['disableRestrictedCopy']) && isset($installdefs['copy'])){
649 foreach($installdefs['copy'] as $copy){
650 $from = str_replace('<basepath>', $this->pathToModule, $copy['from']);
652 if(substr_count($from, '..')){
653 $this->issues['copy'][$from] = translate('ML_PATH_MAY_NOT_CONTAIN').' ".." -' . $from;
655 if(substr_count($to, '..')){
656 $this->issues['copy'][$to] = translate('ML_PATH_MAY_NOT_CONTAIN'). ' ".." -' . $to;
658 while(substr_count($from, '//')){
659 $from = str_replace('//', '/', $from);
661 while(substr_count($to, '//')){
662 $to = str_replace('//', '/', $to);
664 $this->scanCopy($from, $to);
668 $this->issues['manifest'][$manifestPath] = $issues;
678 * Takes in where the file will is specified to be copied from and to
679 * and ensures that there is no official sugar file there. If the file exists it will check
680 * against the MD5 file list to see if Sugar Created the file
683 function scanCopy($from, $to){
684 //if the file doesn't exist for the $to then it is not overriding anything
685 if(!file_exists($to))return;
686 //if $to is a dir and $from is a file then make $to a full file path as well
687 if(is_dir($to) && is_file($from)){
688 if(substr($to,-1) === '/'){
689 $to = substr($to, 0 , strlen($to) - 1);
691 $to .= '/'. basename($from);
693 //if the $to is a file and it is found in sugarFileExists then don't allow overriding it
694 if(is_file($to) && $this->sugarFileExists($to)){
695 $this->issues['copy'][$from] = translate('ML_OVERRIDE_CORE_FILES') . '(' . $to . ')';
700 while($e = $d->read()){
701 if($e == '.' || $e == '..')continue;
702 $this->scanCopy($from .'/'. $e, $to .'/' . $e);
714 *Main external function that takes in a path to a package and then scans
715 *that package's manifest for disabled actions and then it scans the PHP files
716 *for restricted function calls
719 public function scanPackage($path){
720 $this->pathToModule = $path;
721 $this->scanManifest($path . '/manifest.php');
722 if(empty($this->config['disableFileScan'])){
723 $this->scanDir($path);
728 *This function will take all issues of the current instance and print them to the screen
730 public function displayIssues($package='Package'){
731 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').
732 '</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>.'.
733 '<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>';
736 foreach($this->issues as $type=>$issues){
737 echo '<div class="error"><h2>'. ucfirst($type) .' ' . translate('ML_ISSUES') . '</h2> </div>';
738 echo '<div id="details' . $type . '" >';
739 foreach($issues as $file=>$issue){
740 $file = str_replace($this->pathToModule . '/', '', $file);
741 echo '<div style="position:relative;left:10px"><b>' . $file . '</b></div><div style="position:relative;left:20px">';
742 if(is_array($issue)){
743 foreach($issue as $i){
754 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') . "\" />";
759 * Lock config settings
761 public function lockConfig()
763 if(empty($this->config_hash)) {
764 $this->config_hash = md5(serialize($GLOBALS['sugar_config']));
769 * Check if config was modified. Return
770 * @param string $file
771 * @return array Errors if something wrong, false if no problems
773 public function checkConfig($file)
775 $config_hash_after = md5(serialize($GLOBALS['sugar_config']));
776 if($config_hash_after != $this->config_hash) {
777 $this->issues['file'][$file] = array(translate('ML_CONFIG_OVERRIDE'));
778 return $this->issues;
787 * Outside of the class to isolate the context
788 * @param string $manifest_file
791 function MSLoadManifest($manifest_file)
793 include( $manifest_file );
794 return array($manifest, $installdefs);