CVE-2015-6568 (published 2017-04-14T16:59Z)

Wolf CMS before 0.8.3.1 allows unrestricted file rename and PHP Code Execution because admin/plugin/file_manager/browse/ (aka the filemanager) does not prevent a change of a file extension to ".php" after originally using the parameter "filename" for uploading a JPEG image. Exploitation requires a registered user who has access to upload functionality.

Severity: MEDIUM
CVSS v2 base score: 6.5 (AV:N/AC:L/Au:S/C:P/I:P/A:P)
CVSS v3 base score: 8.8, HIGH (CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-20
cwe_name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
extended_description: 
	   Input validation is a frequently-used technique
	   for checking potentially dangerous inputs in order to
	   ensure that the inputs are safe for processing within the
	   code, or when communicating with other components.  When
	   software does not validate input properly, an attacker is
	   able to craft the input in a form that is not expected by
	   the rest of the application. This will lead to parts of the
	   system receiving unintended input, which may result in
	   altered control flow, arbitrary control of a resource, or
	   arbitrary code execution.
	   Input validation is not the only technique for
	   processing input, however.  Other techniques attempt to
	   transform potentially-dangerous input into something safe, such
	   as filtering (CWE-790) - which attempts to remove dangerous
	   inputs - or encoding/escaping (CWE-116), which attempts to
	   ensure that the input is not misinterpreted when it is included
	   in output to another component. Other techniques exist as well
	   (see CWE-138 for more examples.)
	   Input validation can be applied to:
	   
	     raw data - strings, numbers, parameters, file contents, etc.
	     metadata - information about the raw data, such as headers or size
	   
	   Data can be simple or structured.  Structured data
	   can be composed of many nested layers, composed of
	   combinations of metadata and raw data, with other simple or
	   structured data.
	   Many properties of raw data or metadata may need
	   to be validated upon entry into the code, such
	   as:
	   
	     specified quantities such as size, length, frequency, price, rate, number of operations, time, etc.
	     implied or derived quantities, such as the actual size of a file instead of a specified size
	     indexes, offsets, or positions into more complex data structures
	     symbolic keys or other elements into hash tables, associative arrays, etc.
	     well-formedness, i.e. syntactic correctness - compliance with expected syntax 
	     lexical token correctness - compliance with rules for what is treated as a token
	     specified or derived type - the actual type of the input (or what the input appears to be)
	     consistency - between individual data elements, between raw data and metadata, between references, etc.
	     conformance to domain-specific rules, e.g. business logic 
	     equivalence - ensuring that equivalent inputs are treated the same
	     authenticity, ownership, or other attestations about the input, e.g. a cryptographic signature to prove the source of the data
	   
	   Implied or derived properties of data must often
	   be calculated or inferred by the code itself.  Errors in
	   deriving properties may be considered a contributing factor
	   to improper input validation.
	   
	   Note that "input validation" has very different
	   meanings to different people, or within different
	   classification schemes.  Caution must be used when
	   referencing this CWE entry or mapping to it.  For example,
	   some weaknesses might involve inadvertently giving control
	   to an attacker over an input when they should not be able
	   to provide an input at all, but sometimes this is referred
	   to as input validation.
	   Finally, it is important to emphasize that the
	   distinctions between input validation and output escaping
	   are often blurred, and developers must be careful to
	   understand the difference, including how input validation
	   is not always sufficient to prevent vulnerabilities,
	   especially when less stringent data types must be
	   supported, such as free-form text. Consider a SQL injection
	   scenario in which a person's last name is inserted into a
	   query. The name "O'Reilly" would likely pass the validation
	   step since it is a common last name in the English
	   language. However, this valid name cannot be directly
	   inserted into the database because it contains the "'"
	   apostrophe character, which would need to be escaped or
	   otherwise transformed. In this case, removing the
	   apostrophe might reduce the risk of SQL injection, but it
	   would produce incorrect behavior because the wrong name
	   would be recorded.
       
         

Fix information:
repo_url: https://github.com/wolfcms/wolfcms
commit_details: repo_url: https://github.com/wolfcms/wolfcms
author: Martijn
author_date: 2015-08-10 16:01:40+02:00
msg: Fix #619 and #625
repository: repo_url: https://github.com/wolfcms/wolfcms
repo_name: wolfcms/wolfcms
description: ARCHIVED - http://www.wolfcms.org
repo_language: PHP
owner: wolfcms
file_changes: filename: FileManagerController.php
change_type: ModificationType.MODIFY
diff: @@ -27,7 +27,7 @@
 if (!defined('IN_CMS')) { exit(); }
 
 /**
- * 
+ *
  */
 class FileManagerController extends PluginController {
 
@@ -55,6 +55,14 @@ class FileManagerController extends PluginController {
         $this->browse();
     }
 
+    static function htmlContextCleaner($input) {
+        $bad_chars = array("<", ">");
+        $safe_chars = array("&lt;", "&gt;");
+        $output = str_replace($bad_chars, $safe_chars, $input);
+
+        return stripslashes($output);
+    }
+
     public function browse() {
         $params = func_get_args();
 
@@ -94,7 +102,7 @@ class FileManagerController extends PluginController {
         $this->fullpath = preg_replace('/\/\//', '/', $this->fullpath);
 
         $this->display('file_manager/views/index', array(
-            'dir' => $this->path,
+            'dir' => htmlContextCleaner($this->path),
             //'files' => $this->_getListFiles()
             'files' => $this->_listFiles()
         ));
@@ -133,15 +141,15 @@ class FileManagerController extends PluginController {
 
         // We don't allow leading slashes
         $filename = preg_replace('/^\//', '', $filename);
-        
+
         // Check if file had URL_SUFFIX - if so, append it to filename
         $filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';
-        
+
         $file = FILES_DIR . '/' . $filename;
         if (!$this->_isImage($file) && file_exists($file)) {
             $content = file_get_contents($file);
         }
-        
+
         $this->display('file_manager/views/view', array(
             'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),
             'is_image' => $this->_isImage($file),
@@ -156,7 +164,7 @@ class FileManagerController extends PluginController {
         // security (remove all ..)
         $data['name'] = str_replace('..', '', $data['name']);
         $file = FILES_DIR . DS . $data['name'];
-        
+
         // CSRF checks
         if (isset($_POST['csrf_token'])) {
             $csrf_token = $_POST['csrf_token'];
@@ -169,7 +177,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('No CSRF token found!'));
             redirect(get_url('plugin/file_manager/view/'.$data['name']));
         }
-        
+
         if (file_exists($file)) {
             if (file_put_contents($file, $data['content']) !== false) {
                 Flash::set('success', __('File has been saved with success!'));
@@ -197,7 +205,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('You do not have sufficient permissions to create a file.'));
             redirect(get_url('plugin/file_manager/browse/'));
         }
-        
+
         // CSRF checks
         if (isset($_POST['csrf_token'])) {
             $csrf_token = $_POST['csrf_token'];
@@ -231,7 +239,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('You do not have sufficient permissions to create a directory.'));
             redirect(get_url('plugin/file_manager/browse/'));
         }
-        
+
         // CSRF checks
         if (isset($_POST['csrf_token'])) {
             $csrf_token = $_POST['csrf_token'];
@@ -269,7 +277,7 @@ class FileManagerController extends PluginController {
         $paths = func_get_args();
 
         $file = urldecode(join('/', $paths));
-        
+
         // CSRF checks
         if (isset($_GET['csrf_token'])) {
             $csrf_token = $_GET['csrf_token'];
@@ -304,7 +312,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('You do not have sufficient permissions to upload a file.'));
             redirect(get_url('plugin/file_manager/browse/'));
         }
-        
+
         // CSRF checks
         if (isset($_POST['csrf_token'])) {
             $csrf_token = $_POST['csrf_token'];
@@ -317,7 +325,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('No CSRF token found!'));
             redirect(get_url('plugin/file_manager/browse/'));
         }
-        
+
         $mask = Plugin::getSetting('umask', 'file_manager');
         umask(octdec($mask));
 
@@ -329,6 +337,12 @@ class FileManagerController extends PluginController {
         $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);
         $filename = preg_replace('/[^a-z0-9_\-\.]/i', '', $filename);
 
+        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
+        if (in_array($ext, ['php', 'php3', 'php4', 'inc'])) {
+            Flash::set('error', __('Not allowed to upload files with extension :ext', $ext));
+            redirect(get_url('plugin/file_manager/browse/'));
+        }
+
         if (isset($_FILES)) {
             $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);
 
@@ -356,7 +370,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('No CSRF token found!'));
             redirect(get_url('plugin/file_manager/browse/'));
         }
-        
+
         $data = $_POST['file'];
         $data['name'] = str_replace('..', '', $data['name']);
         $file = FILES_DIR . '/' . $data['name'];
@@ -378,7 +392,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('You do not have sufficient permissions to rename this file or directory.'));
             redirect(get_url('plugin/file_manager/browse/'));
         }
-        
+
         // CSRF checks
         if (isset($_POST['csrf_token'])) {
             $csrf_token = $_POST['csrf_token'];
@@ -404,6 +418,14 @@ class FileManagerController extends PluginController {
         $path = substr($data['current_name'], 0, strrpos($data['current_name'], '/'));
         $file = FILES_DIR . '/' . $data['current_name'];
 
+        // Check if trying to rename to php file (.php / .php3 etc)
+        $ext = strtolower(pathinfo($data['new_name'], PATHINFO_EXTENSION));
+
+        if (in_array($ext, ['php', 'php3', 'php4', 'inc'])) {
+            Flash::set('error', __('Not allowed to rename to :ext', $ext));
+            redirect(get_url('plugin/file_manager/browse/' . $path));
+        }
+
         // Check another file doesn't already exist with same name
         if (file_exists(FILES_DIR . '/' . $path . '/' . $data['new_name'])) {
             Flash::set('error', __('A file or directory with that name already exists!'));
@@ -442,7 +464,7 @@ class FileManagerController extends PluginController {
                 $name = $cur->getFilename();
                 if (Plugin::getSetting('show_hidden', 'file_manager') == '0' && $name[0] === '.')
                     continue;
-                
+
                 if (Plugin::getSetting('show_backups', 'file_manager') == '0' && $name[strlen($name)-1] === '~')
                     continue;
 
@@ -453,7 +475,7 @@ class FileManagerController extends PluginController {
                 $object->size = convert_size($cur->getSize());
                 $object->mtime = date('D, j M, Y', $cur->getMTime());
                 list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());
-                
+
                 // Find the file type
                 $object->type = $this->_getFileType($cur);
 
@@ -477,13 +499,13 @@ class FileManagerController extends PluginController {
                     return strnatcmp($a->name, $b->name);
                 }
             });
-            
+
             return $files;
         }
 
         return array();
     }
-    
+
     private function _getFileType($file) {
         $default = 'unknown';
 
@@ -659,7 +681,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('You do not have permission to access the requested page!'));
             redirect(get_url());
         }
-        
+
         $settings = Plugin::getAllSettings('file_manager');
 
         if (!$settings) {
@@ -678,7 +700,7 @@ class FileManagerController extends PluginController {
             Flash::set('error', __('You do not have permission to access the requested page!'));
             redirect(get_url());
         }
-        
+
         if (!isset($_POST['settings'])) {
             Flash::set('error', 'File Manager - ' . __('form was not posted.'));
             redirect(get_url('plugin/file_manager/settings'));

programming_language: PHP
filename: en-message.php
change_type: ModificationType.MODIFY
diff: @@ -41,6 +41,8 @@ return array(
     'Modified' => 'Modified',
     'Modify' => 'Modify',
     'No' => 'No',
+    'Not allowed to upload files with extension :ext' => 'Not allowed to upload files with extension :ext',
+    'Not allowed to rename to :ext' => 'Not allowed to rename to :ext',
     'Permission denied!' => 'Permission denied!',
     'Permissions' => 'Permissions',
     'Provides interface to manage files from the administration.' => 'Provides interface to manage files from the administration.',
@@ -72,4 +74,4 @@ return array(
     'unable to retrieve plugin settings.' => 'unable to retrieve plugin settings.',
     'unable to store plugin settings!' => 'unable to store plugin settings!',
     'uninstalled.' => 'uninstalled.'
-);
\ No newline at end of file
+);

programming_language: PHP
filename: index.php
change_type: ModificationType.MODIFY
diff: @@ -23,16 +23,25 @@
 /* Security measure */
 if (!defined('IN_CMS')) { exit(); }
 
+function htmlContextCleaner($input) {
+    $bad_chars = array("<", ">");
+    $safe_chars = array("&lt;", "&gt;");
+    $output = str_replace($bad_chars, $safe_chars, $input);
+
+    return stripslashes($output);
+}
+
   $out = '';
   $progres_path = '';
-  $paths = explode('/', $dir); 
+  $paths = explode('/', $dir);
   $nb_path = count($paths)-1; // -1 to didn't display current dir as a link
   foreach ($paths as $i => $path) {
     if ($i+1 == $nb_path) {
       $out .= $path;
     } else if ($path != '') {
+      $path = preg_replace('/.*:\/\/[^\/]+\//', '/', $path);
       $progres_path .= $path.'/';
-      $out .= '<a href="'.get_url('plugin/file_manager/browse/'.rtrim($progres_path, '/')).'">'.$path.'</a>/';
+      $out .= '<a href="'.get_url('plugin/file_manager/browse/'.rtrim($progres_path, '/')).'">'.htmlContextCleaner($path).'</a>/';
     }
   }
 ?>
@@ -74,11 +83,11 @@ if (!defined('IN_CMS')) { exit(); }
 
   <div class="popup" id="chmod-popup" style="display:none;">
     <h3><?php echo __('Change mode'); ?></h3>
-    <form action="<?php echo get_url('plugin/file_manager/chmod'); ?>" method="post"> 
+    <form action="<?php echo get_url('plugin/file_manager/chmod'); ?>" method="post">
       <div>
         <input id="csrf_token" name="csrf_token" type="hidden" value="<?php echo SecureToken::generateToken(BASE_URL.'plugin/file_manager/chmod'); ?>" />
         <input id="chmod_file_name" name="file[name]" type="hidden" value="" />
-        <input id="chmod_file_mode" maxlength="4" name="file[mode]" type="text" value="" /> 
+        <input id="chmod_file_mode" maxlength="4" name="file[mode]" type="text" value="" />
         <input id="chmod_file_button" name="commit" type="submit" value="<?php echo __('Change mode'); ?>" />
       </div>
       <p><a class="close-link" href="#" onclick="toggle_chmod_popup(); return false;"><?php echo __('Close'); ?></a></p>
@@ -86,11 +95,11 @@ if (!defined('IN_CMS')) { exit(); }
   </div>
   <div class="popup" id="rename-popup" style="display:none;">
       <h3><?php echo __('Rename'); ?></h3>
-      <form action="<?php echo get_url('plugin/file_manager/rename'); ?>" method="post"> 
+      <form action="<?php echo get_url('plugin/file_manager/rename'); ?>" method="post">
         <div>
           <input id="csrf_token" name="csrf_token" type="hidden" value="<?php echo SecureToken::generateToken(BASE_URL.'plugin/file_manager/rename'); ?>" />
           <input id="rename_file_current_name" name="file[current_name]" type="hidden" value="" />
-          <input id="rename_file_new_name" maxlength="50" name="file[new_name]" type="text" value="" /> 
+          <input id="rename_file_new_name" maxlength="50" name="file[new_name]" type="text" value="" />
           <input id="rename_file_button" name="commit" type="submit" value="<?php echo __('Rename'); ?>" />
         </div>
         <p><a class="close-link" href="#" onclick="toggle_rename_popup(); return false;"><?php echo __('Close'); ?></a></p>

programming_language: PHP
filename: view.php
change_type: ModificationType.MODIFY
diff: @@ -23,16 +23,26 @@
 /* Security measure */
 if (!defined('IN_CMS')) { exit(); }
 
+function htmlContextCleaner($input) {
+    $bad_chars = array("<", ">");
+    $safe_chars = array("&lt;", "&gt;");
+    $output = str_replace($bad_chars, $safe_chars, $input);
+
+    return stripslashes($output);
+}
+
+
   $out = '';
   $progres_path = '';
-  $paths = explode('/', $filename); 
+  $paths = explode('/', $filename);
   $nb_path = count($paths);
   foreach ($paths as $i => $path) {
     if ($i+1 == $nb_path) {
       $out .= $path;
     } else {
+      $path = preg_replace('/.*:\/\/[^\/]+\//', '/', $path);
       $progres_path .= $path.'/';
-      $out .= '<a href="'.get_url('plugin/file_manager/browse/'.rtrim($progres_path, '/')).'">'.$path.'</a>/';
+      $out .= '<a href="'.get_url('plugin/file_manager/browse/'.rtrim($progres_path, '/')).'">'.htmlContextCleaner($path).'</a>/';
     }
   }
 ?>

programming_language: PHP