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(
130 'realpath_cache_get',
131 'realpath_cache_size',
171 'call_user_func_array',
175 //mutliple files per function call
180 'move_uploaded_file',
183 'create_cache_directory',
185 'write_array_to_file',
186 'write_encoded_file',
187 'create_custom_directory',
192 'sugar_file_put_contents',
197 // Functions that have callbacks can circumvent our security measures.
198 // List retrieved through PHP's XML documentation, and running the
199 // following script in the reference directory:
201 // grep -R callable . | grep -v \.svn | grep methodparam | cut -d: -f1 | sort -u | cut -d"." -f2 | sed 's/\-/\_/g' | cut -d"/" -f4
206 // PHP internal - arrays
210 'array_intersect_uassoc',
211 'array_intersect_ukey',
215 'array_udiff_uassoc',
217 'array_uintersect_assoc',
218 'array_uintersect_uassoc',
220 'array_walk_recursive',
226 // EIO functions that accept callbacks.
260 'eio_sync_file_range',
268 // PHP internal - error functions
270 'set_exception_handler',
272 // Forms Data Format functions
275 // PHP internal - function handling
276 'call_user_func_array',
278 'forward_static_call_array',
279 'forward_static_call',
280 'register_shutdown_function',
281 'register_tick_function',
285 'setcompletecallback',
287 'setexceptioncallback',
290 'setwarningcallback',
291 'setworkloadcallback',
294 // Firebird/InterBase
295 'ibase_set_event_handler',
298 'ldap_set_rebind_proc',
301 'libxml_set_external_entity_loader',
303 // Mailparse functions
304 'mailparse_msg_extract_part_file',
305 'mailparse_msg_extract_part',
306 'mailparse_msg_extract_whole_part_file',
308 // Memcache(d) functions
317 'set_local_infile_handler',
319 // PHP internal - network functions
320 'header_register_callback',
323 'newt_entry_set_filter',
324 'newt_set_suspend_callback',
328 'timestampnoncehandler',
331 // PHP internal - output control
334 // PHP internal - PCNTL
337 // PHP internal - PCRE
338 'preg_replace_callback',
341 'sqlitecreateaggregate',
342 'sqlitecreatefunction',
343 'sqlite_create_aggregate',
344 'sqlite_create_function',
350 'readline_callback_handler_install',
351 'readline_completion_function',
353 // PHP internal - session handling
354 'session_set_save_handler',
356 // PHP internal - SPL
359 'spl_autoload_register',
362 'sybase_set_message_handler',
364 // PHP internal - variable handling
368 'xml_set_character_data_handler',
369 'xml_set_default_handler',
370 'xml_set_element_handler',
371 'xml_set_end_namespace_decl_handler',
372 'xml_set_external_entity_ref_handler',
373 'xml_set_notation_decl_handler',
374 'xml_set_processing_instruction_handler',
375 'xml_set_start_namespace_decl_handler',
376 'xml_set_unparsed_entity_decl_handler',
379 public function printToWiki(){
380 echo "'''Default Extensions'''<br>";
381 foreach($this->validExt as $b){
382 echo '#' . $b . '<br>';
385 echo "'''Default Black Listed Functions'''<br>";
386 foreach($this->blackList as $b){
387 echo '#' . $b . '<br>';
393 public function __construct(){
394 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['blackListExempt'])){
395 $this->blackListExempt = array_merge($this->blackListExempt, $GLOBALS['sugar_config']['moduleInstaller']['blackListExempt']);
397 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['blackList'])){
398 $this->blackList = array_merge($this->blackList, $GLOBALS['sugar_config']['moduleInstaller']['blackList']);
400 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['classBlackListExempt'])){
401 $this->classBlackListExempt = array_merge($this->classBlackListExempt, $GLOBALS['sugar_config']['moduleInstaller']['classBlackListExempt']);
403 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['classBlackList'])){
404 $this->classBlackList = array_merge($this->classBlackList, $GLOBALS['sugar_config']['moduleInstaller']['classBlackList']);
406 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['validExt'])){
407 $this->validExt = array_merge($this->validExt, $GLOBALS['sugar_config']['moduleInstaller']['validExt']);
412 private $issues = array();
413 private $pathToModule = '';
416 *returns a list of issues
418 public function getIssues(){
419 return $this->issues;
423 *returns true or false if any issues were found
425 public function hasIssues(){
426 return !empty($this->issues);
430 *Ensures that a file has a valid extension
432 private function isValidExtension($file){
433 $file = strtolower($file);
435 $extPos = strrpos($file, '.');
436 //make sure they don't override the files.md5
437 if($extPos === false || $file == 'files.md5')return false;
438 $ext = substr($file, $extPos + 1);
439 return in_array($ext, $this->validExt);
444 *Scans a directory and calls on scan file for each file
446 public function scanDir($path){
447 static $startPath = '';
448 if(empty($startPath))$startPath = $path;
449 if(!is_dir($path))return false;
451 while($e = $d->read()){
452 $next = $path . '/' . $e;
454 if(substr($e, 0, 1) == '.')continue;
455 $this->scanDir($next);
457 $issues = $this->scanFile($next);
466 * Check if the file contents looks like PHP
467 * @param string $contents File contents
470 public function isPHPFile($contents)
472 if(stripos($contents, '<?php') !== false) return true;
473 for($tag=0;($tag = stripos($contents, '<?', $tag)) !== false;$tag++) {
474 if(strncasecmp(substr($contents, $tag, 13), '<?xml version', 13) == 0) {
475 // <?xml version is OK, skip it
479 // found <?, it's PHP
486 * 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
487 * $var() and ` are always prevented then whatever is in the blacklist.
488 * It will also ensure that all files are of valid extension types
491 public function scanFile($file){
493 if(!$this->isValidExtension($file)){
494 $issues[] = translate('ML_INVALID_EXT');
495 $this->issues['file'][$file] = $issues;
498 $contents = file_get_contents($file);
499 if(!$this->isPHPFile($contents)) return $issues;
500 $tokens = @token_get_all($contents);
501 $checkFunction = false;
504 foreach($tokens as $index=>$token){
505 if(is_string($token[0])){
508 $issues['backtick'] = translate('ML_INVALID_FUNCTION') . " '`'";
510 if($checkFunction)$issues[] = $possibleIssue;
513 $checkFunction = false;
516 $token['_msi'] = token_name($token[0]);
518 case T_WHITESPACE: continue;
520 if(in_array('eval', $this->blackList) && !in_array('eval', $this->blackListExempt))
521 $issues[]= translate('ML_INVALID_FUNCTION') . ' eval()';
524 $token[1] = strtolower($token[1]);
525 if($lastToken !== false && $lastToken[0] == T_NEW) {
526 if(!in_array($token[1], $this->classBlackList))break;
527 if(in_array($token[1], $this->classBlackListExempt))break;
528 } elseif ($token[0] == T_DOUBLE_COLON) {
529 if(!in_array($lastToken[1], $this->classBlackList))break;
530 if(in_array($lastToken[1], $this->classBlackListExempt))break;
532 if(!in_array($token[1], $this->blackList))break;
533 if(in_array($token[1], $this->blackListExempt))break;
535 if ($lastToken !== false &&
536 ($lastToken[0] == T_OBJECT_OPERATOR || $lastToken[0] == T_DOUBLE_COLON))
542 $checkFunction = true;
543 $possibleIssue = translate('ML_INVALID_FUNCTION') . ' ' . $token[1] . '()';
547 $checkFunction = false;
551 if ($token[0] != T_WHITESPACE)
559 $this->issues['file'][$file] = $issues;
567 * checks files.md5 file to see if the file is from sugar
568 * ONLY WORKS ON FILES
570 public function sugarFileExists($path){
571 static $md5 = array();
572 if(empty($md5) && file_exists('files.md5'))
574 include('files.md5');
577 if(isset($md5['./' . $path]))return true;
584 *This function will scan the Manifest for disabled actions specified in $GLOBALS['sugar_config']['moduleInstaller']['disableActions']
585 *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
587 public function scanManifest($manifestPath){
589 if(!file_exists($manifestPath)){
590 $this->issues['manifest'][$manifestPath] = translate('ML_NO_MANIFEST');
593 $fileIssues = $this->scanFile($manifestPath);
594 //if the manifest contains malicious code do not open it
595 if(!empty($fileIssues)){
598 include($manifestPath);
601 //scan for disabled actions
602 if(isset($GLOBALS['sugar_config']['moduleInstaller']['disableActions'])){
603 foreach($GLOBALS['sugar_config']['moduleInstaller']['disableActions'] as $action){
604 if(isset($installdefs[$this->manifestMap[$action]])){
605 $issues[] = translate('ML_INVALID_ACTION_IN_MANIFEST') . $this->manifestMap[$action];
610 //now lets scan for files that will override our files
611 if(empty($GLOBALS['sugar_config']['moduleInstaller']['disableRestrictedCopy']) && isset($installdefs['copy'])){
612 foreach($installdefs['copy'] as $copy){
613 $from = str_replace('<basepath>', $this->pathToModule, $copy['from']);
615 if(substr_count($from, '..')){
616 $this->issues['copy'][$from] = translate('ML_PATH_MAY_NOT_CONTAIN').' ".." -' . $from;
618 if(substr_count($to, '..')){
619 $this->issues['copy'][$to] = translate('ML_PATH_MAY_NOT_CONTAIN'). ' ".." -' . $to;
621 while(substr_count($from, '//')){
622 $from = str_replace('//', '/', $from);
624 while(substr_count($to, '//')){
625 $to = str_replace('//', '/', $to);
627 $this->scanCopy($from, $to);
631 $this->issues['manifest'][$manifestPath] = $issues;
641 * Takes in where the file will is specified to be copied from and to
642 * and ensures that there is no official sugar file there. If the file exists it will check
643 * against the MD5 file list to see if Sugar Created the file
646 function scanCopy($from, $to){
647 //if the file doesn't exist for the $to then it is not overriding anything
648 if(!file_exists($to))return;
649 //if $to is a dir and $from is a file then make $to a full file path as well
650 if(is_dir($to) && is_file($from)){
651 if(substr($to,-1) === '/'){
652 $to = substr($to, 0 , strlen($to) - 1);
654 $to .= '/'. basename($from);
656 //if the $to is a file and it is found in sugarFileExists then don't allow overriding it
657 if(is_file($to) && $this->sugarFileExists($to)){
658 $this->issues['copy'][$from] = translate('ML_OVERRIDE_CORE_FILES') . '(' . $to . ')';
663 while($e = $d->read()){
664 if($e == '.' || $e == '..')continue;
665 $this->scanCopy($from .'/'. $e, $to .'/' . $e);
677 *Main external function that takes in a path to a package and then scans
678 *that package's manifest for disabled actions and then it scans the PHP files
679 *for restricted function calls
682 public function scanPackage($path){
683 $this->pathToModule = $path;
684 $this->scanManifest($path . '/manifest.php');
685 if(empty($GLOBALS['sugar_config']['moduleInstaller']['disableFileScan'])){
686 $this->scanDir($path);
691 *This function will take all issues of the current instance and print them to the screen
693 public function displayIssues($package='Package'){
694 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').
695 '</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>.'.
696 '<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>';
699 foreach($this->issues as $type=>$issues){
700 echo '<div class="error"><h2>'. ucfirst($type) .' ' . translate('ML_ISSUES') . '</h2> </div>';
701 echo '<div id="details' . $type . '" >';
702 foreach($issues as $file=>$issue){
703 $file = str_replace($this->pathToModule . '/', '', $file);
704 echo '<div style="position:relative;left:10px"><b>' . $file . '</b></div><div style="position:relative;left:20px">';
705 if(is_array($issue)){
706 foreach($issue as $i){
717 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') . "\" />";