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(){
403 if(!empty($GLOBALS['sugar_config']['moduleInstaller'])) {
404 $this->config = $GLOBALS['sugar_config']['moduleInstaller'];
407 if(!empty($this->config['blackListExempt'])){
408 $this->blackListExempt = array_merge($this->blackListExempt, $this->config['blackListExempt']);
410 if(!empty($this->config['blackList'])){
411 $this->blackList = array_merge($this->blackList, $this->config['blackList']);
413 if(!empty($this->config['classBlackListExempt'])){
414 $this->classBlackListExempt = array_merge($this->classBlackListExempt, $this->config['classBlackListExempt']);
416 if(!empty($this->config['classBlackList'])){
417 $this->classBlackList = array_merge($this->classBlackList, $this->config['classBlackList']);
419 if(!empty($this->config['validExt'])){
420 $this->validExt = array_merge($this->validExt, $this->config['validExt']);
425 private $issues = array();
426 private $pathToModule = '';
429 *returns a list of issues
431 public function getIssues(){
432 return $this->issues;
436 *returns true or false if any issues were found
438 public function hasIssues(){
439 return !empty($this->issues);
443 *Ensures that a file has a valid extension
445 private function isValidExtension($file){
446 $file = strtolower($file);
448 $extPos = strrpos($file, '.');
449 //make sure they don't override the files.md5
450 if($extPos === false || $file == 'files.md5')return false;
451 $ext = substr($file, $extPos + 1);
452 return in_array($ext, $this->validExt);
457 *Scans a directory and calls on scan file for each file
459 public function scanDir($path){
460 static $startPath = '';
461 if(empty($startPath))$startPath = $path;
462 if(!is_dir($path))return false;
464 while($e = $d->read()){
465 $next = $path . '/' . $e;
467 if(substr($e, 0, 1) == '.')continue;
468 $this->scanDir($next);
470 $issues = $this->scanFile($next);
479 * Check if the file contents looks like PHP
480 * @param string $contents File contents
483 public function isPHPFile($contents)
485 if(stripos($contents, '<?php') !== false) return true;
486 for($tag=0;($tag = stripos($contents, '<?', $tag)) !== false;$tag++) {
487 if(strncasecmp(substr($contents, $tag, 13), '<?xml version', 13) == 0) {
488 // <?xml version is OK, skip it
492 // found <?, it's PHP
499 * 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
500 * $var() and ` are always prevented then whatever is in the blacklist.
501 * It will also ensure that all files are of valid extension types
504 public function scanFile($file){
506 if(!$this->isValidExtension($file)){
507 $issues[] = translate('ML_INVALID_EXT');
508 $this->issues['file'][$file] = $issues;
511 $contents = file_get_contents($file);
512 if(!$this->isPHPFile($contents)) return $issues;
513 $tokens = @token_get_all($contents);
514 $checkFunction = false;
517 foreach($tokens as $index=>$token){
518 if(is_string($token[0])){
521 $issues['backtick'] = translate('ML_INVALID_FUNCTION') . " '`'";
523 if($checkFunction)$issues[] = $possibleIssue;
526 $checkFunction = false;
529 $token['_msi'] = token_name($token[0]);
531 case T_WHITESPACE: continue;
533 if(in_array('eval', $this->blackList) && !in_array('eval', $this->blackListExempt))
534 $issues[]= translate('ML_INVALID_FUNCTION') . ' eval()';
537 $token[1] = strtolower($token[1]);
538 if($lastToken !== false && $lastToken[0] == T_NEW) {
539 if(!in_array($token[1], $this->classBlackList))break;
540 if(in_array($token[1], $this->classBlackListExempt))break;
541 } elseif ($token[0] == T_DOUBLE_COLON) {
542 if(!in_array($lastToken[1], $this->classBlackList))break;
543 if(in_array($lastToken[1], $this->classBlackListExempt))break;
545 //if nothing else fit, lets check the last token to see if this is a possible method call
546 if ($lastToken !== false &&
547 ($lastToken[0] == T_OBJECT_OPERATOR || $lastToken[0] == T_DOUBLE_COLON))
549 //this is a method call, check the black list
550 if(in_array($token[1], $this->methodsBlackList)){
551 $issues[]= translate('ML_INVALID_METHOD') . ' ' .$token[1]. '()';
557 if(!in_array($token[1], $this->blackList))break;
558 if(in_array($token[1], $this->blackListExempt))break;
562 $checkFunction = true;
563 $possibleIssue = translate('ML_INVALID_FUNCTION') . ' ' . $token[1] . '()';
567 $checkFunction = false;
571 if ($token[0] != T_WHITESPACE)
579 $this->issues['file'][$file] = $issues;
587 * checks files.md5 file to see if the file is from sugar
588 * ONLY WORKS ON FILES
590 public function sugarFileExists($path){
591 static $md5 = array();
592 if(empty($md5) && file_exists('files.md5'))
594 include('files.md5');
597 if(isset($md5['./' . $path]))return true;
604 *This function will scan the Manifest for disabled actions specified in $GLOBALS['sugar_config']['moduleInstaller']['disableActions']
605 *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
607 public function scanManifest($manifestPath){
609 if(!file_exists($manifestPath)){
610 $this->issues['manifest'][$manifestPath] = translate('ML_NO_MANIFEST');
613 $fileIssues = $this->scanFile($manifestPath);
614 //if the manifest contains malicious code do not open it
615 if(!empty($fileIssues)){
619 list($manifest, $installdefs) = MSLoadManifest($manifestPath);
620 $fileIssues = $this->checkConfig($manifestPath);
621 if(!empty($fileIssues)){
625 //scan for disabled actions
626 if(isset($this->config['disableActions'])){
627 foreach($this->config['disableActions'] as $action){
628 if(isset($installdefs[$this->manifestMap[$action]])){
629 $issues[] = translate('ML_INVALID_ACTION_IN_MANIFEST') . $this->manifestMap[$action];
634 //now lets scan for files that will override our files
635 if(empty($this->config['disableRestrictedCopy']) && isset($installdefs['copy'])){
636 foreach($installdefs['copy'] as $copy){
637 $from = str_replace('<basepath>', $this->pathToModule, $copy['from']);
639 if(substr_count($from, '..')){
640 $this->issues['copy'][$from] = translate('ML_PATH_MAY_NOT_CONTAIN').' ".." -' . $from;
642 if(substr_count($to, '..')){
643 $this->issues['copy'][$to] = translate('ML_PATH_MAY_NOT_CONTAIN'). ' ".." -' . $to;
645 while(substr_count($from, '//')){
646 $from = str_replace('//', '/', $from);
648 while(substr_count($to, '//')){
649 $to = str_replace('//', '/', $to);
651 $this->scanCopy($from, $to);
655 $this->issues['manifest'][$manifestPath] = $issues;
665 * Takes in where the file will is specified to be copied from and to
666 * and ensures that there is no official sugar file there. If the file exists it will check
667 * against the MD5 file list to see if Sugar Created the file
670 function scanCopy($from, $to){
671 //if the file doesn't exist for the $to then it is not overriding anything
672 if(!file_exists($to))return;
673 //if $to is a dir and $from is a file then make $to a full file path as well
674 if(is_dir($to) && is_file($from)){
675 if(substr($to,-1) === '/'){
676 $to = substr($to, 0 , strlen($to) - 1);
678 $to .= '/'. basename($from);
680 //if the $to is a file and it is found in sugarFileExists then don't allow overriding it
681 if(is_file($to) && $this->sugarFileExists($to)){
682 $this->issues['copy'][$from] = translate('ML_OVERRIDE_CORE_FILES') . '(' . $to . ')';
687 while($e = $d->read()){
688 if($e == '.' || $e == '..')continue;
689 $this->scanCopy($from .'/'. $e, $to .'/' . $e);
701 *Main external function that takes in a path to a package and then scans
702 *that package's manifest for disabled actions and then it scans the PHP files
703 *for restricted function calls
706 public function scanPackage($path){
707 $this->pathToModule = $path;
708 $this->scanManifest($path . '/manifest.php');
709 if(empty($this->config['disableFileScan'])){
710 $this->scanDir($path);
715 *This function will take all issues of the current instance and print them to the screen
717 public function displayIssues($package='Package'){
718 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').
719 '</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>.'.
720 '<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>';
723 foreach($this->issues as $type=>$issues){
724 echo '<div class="error"><h2>'. ucfirst($type) .' ' . translate('ML_ISSUES') . '</h2> </div>';
725 echo '<div id="details' . $type . '" >';
726 foreach($issues as $file=>$issue){
727 $file = str_replace($this->pathToModule . '/', '', $file);
728 echo '<div style="position:relative;left:10px"><b>' . $file . '</b></div><div style="position:relative;left:20px">';
729 if(is_array($issue)){
730 foreach($issue as $i){
741 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') . "\" />";
746 * Lock config settings
748 public function lockConfig()
750 if(empty($this->config_hash)) {
751 $this->config_hash = md5(serialize($GLOBALS['sugar_config']));
756 * Check if config was modified. Return
757 * @param string $file
758 * @return array Errors if something wrong, false if no problems
760 public function checkConfig($file)
762 $config_hash_after = md5(serialize($GLOBALS['sugar_config']));
763 if($config_hash_after != $this->config_hash) {
764 $this->issues['file'][$file] = array(translate('ML_CONFIG_OVERRIDE'));
765 return $this->issues;
774 * Outside of the class to isolate the context
775 * @param string $manifest_file
778 function MSLoadManifest($manifest_file)
780 include( $manifest_file );
781 return array($manifest, $installdefs);