Difference between revisions of "Extension:SimpleSecurity"

From Organic Design wiki
m
Line 25: Line 25:
 
$wgSecurityMagicGroup    = "ifgroup";                          # the name for doing a group-based conditional
 
$wgSecurityMagicGroup    = "ifgroup";                          # the name for doing a group-based conditional
 
$wgSecurityLogActions    = array('edit', 'download');          # Actions that should be logged
 
$wgSecurityLogActions    = array('edit', 'download');          # Actions that should be logged
$wgSecurityUseDBHook    = false;                             # Add the DatabaseFetchHook to validate database access
+
$wgSecurityUseDBHook    = true;                               # Add the DatabaseFetchHook to validate database access
 
$wgSecurityAllowUser    = false;                              # Allow restrictions based on user not just group
 
$wgSecurityAllowUser    = false;                              # Allow restrictions based on user not just group
 +
 +
# Extra actions to allow control over in protection form
 +
$wgSecurityExtraActions  = array(
 +
'read'    => 'Read',
 +
'source'  => 'Source',
 +
'history' => 'History'
 +
);
 +
 +
# Extra groups available in protection form
 +
$wgSecurityExtraGroups  = array();
  
 
array_unshift($wgExtensionFunctions, 'wfSetupSimpleSecurity'); # Put SimpleSecurity's setup function before all others
 
array_unshift($wgExtensionFunctions, 'wfSetupSimpleSecurity'); # Put SimpleSecurity's setup function before all others
Line 32: Line 42:
 
$wgHooks['LanguageGetMagic'][] = 'wfSimpleSecurityLanguageGetMagic';
 
$wgHooks['LanguageGetMagic'][] = 'wfSimpleSecurityLanguageGetMagic';
 
$wgExtensionCredits['parserhook'][] = array(
 
$wgExtensionCredits['parserhook'][] = array(
'name'        => "Simple Security",
+
'name'        => "SimpleSecurity4",
 
'author'      => '[http://www.organicdesign.co.nz/User:Nad User:Nad]',
 
'author'      => '[http://www.organicdesign.co.nz/User:Nad User:Nad]',
 
'description' => 'Extends the MediaWiki article protection to allow restricting viewing of article content',
 
'description' => 'Extends the MediaWiki article protection to allow restricting viewing of article content',
Line 45: Line 55:
 
*/
 
*/
 
function __construct() {
 
function __construct() {
global $wgParser, $wgHooks, $wgLogTypes, $wgLogNames, $wgLogHeaders, $wgLogActions,
+
global $wgParser, $wgHooks, $wgLogTypes, $wgLogNames, $wgLogHeaders, $wgLogActions, $wgMessageCache,
$wgSecurityMagicIf, $wgSecurityMagicGroup;
+
$wgSecurityMagicIf, $wgSecurityMagicGroup, $wgSecurityExtraActions, $wgSecurityExtraGroups,
 +
$wgRestrictionTypes, $wgRestrictionLevels;
  
 
# Add our parser-hooks
 
# Add our parser-hooks
$wgParser->setFunctionHook($wgSecurityMagicIf, array($this,'ifUserCan'));
+
$wgParser->setFunctionHook($wgSecurityMagicIf, array($this, 'ifUserCan'));
$wgParser->setFunctionHook($wgSecurityMagicGroup, array($this,'ifGroup'));
+
$wgParser->setFunctionHook($wgSecurityMagicGroup, array($this, 'ifGroup'));
 +
$wgHooks['UserGetRights'][] = $this;
  
 
# Add a new log type
 
# Add a new log type
Line 57: Line 69:
 
$wgLogHeaders['security']      = 'securitylogpagetext';
 
$wgLogHeaders['security']      = 'securitylogpagetext';
 
$wgLogActions['security/deny'] = 'securitylogentry';
 
$wgLogActions['security/deny'] = 'securitylogentry';
 +
 +
# Extend protection form groups, actions and messages
 +
$wgMessageCache->addMessages(array( 'protect-unchain' => "Modify actions individually" ));
 +
foreach ($wgSecurityExtraActions as $k => $v) {
 +
if (empty($v)) $v = ucfirst($k);
 +
$wgRestrictionTypes[] = $k;
 +
$wgMessageCache->addMessages(array( "restriction-$k" => $v ));
 +
}
 +
foreach ($wgSecurityExtraGroups as $k => $v) {
 +
if (empty($v)) $v = ucfirst($k);
 +
$wgRestrictionLevels[] = $k;
 +
$wgMessageCache->addMessages(array( "protect-level-$k" => $v ));
 +
}
 
}
 
}
  
Line 63: Line 88:
 
*/
 
*/
 
public function ifUserCan(&$parser, $action, $title, $then, $else = '') {
 
public function ifUserCan(&$parser, $action, $title, $then, $else = '') {
return $this->validateTitle($action, $title) ? $then : $else;
+
return $title->userCan($action) ? $then : $else;
 
}
 
}
  
Line 75: Line 100:
 
return count($intersection) > 0 ? $then : $else;
 
return count($intersection) > 0 ? $then : $else;
 
}
 
}
 +
 +
    # User::getRights returns a list of rights (allowed actions) based on the current users group membership
 +
    # Title::getRestrictions returns a list of groups who can perform a particular action
 +
    # So getRights should filter out any title-based restriction's actions which require groups that the user is not a member of
 +
public function onUserGetRights(&$user, &$rights) {
 +
global $wgSecurityExtraActions, $wgTitle;
 +
if (is_object($wgTitle)) {
 +
foreach ($wgSecurityExtraActions as $action => $name) {
 +
print_r($wgTitle->getRestrictions($action));
 +
print_r($user->getEffectiveGroups());
 +
if (count(array_intersect($wgTitle->getRestrictions($action), $user->getEffectiveGroups())) < 1) {
 +
if ($i = array_search($action, $rights)) unset($rights[$i]);
 +
}
 +
}
 +
}
 +
return true;
 +
}
 +
 +
# Update a rights-list based on passed user and permissions array
 +
# - pre-existing rights in the list can be removed since each permission has group, action and allow
 +
static function mergeRights(&$user, &$rights, &$permissions, $comment = false) {
 +
$groups = $this->getEffectiveGroups();
 +
foreach ($groups as $group)
 +
if (isset($permissions[$group]))
 +
foreach ($permissions[$group] as $action => $allow) {
 +
# Add or remove a right from the list
 +
if ($allow && !in_array($action, $rights)) $rights[] = $action;
 +
elseif (!$allow && in_array($action, $rights)) array_splice($rights, array_search($action, $rights), 1);
 +
$this->info[] = array($group, $action, $allow, $comment);
 +
}
 +
}
  
 
/**
 
/**
Line 80: Line 136:
 
* - this does not get called if already processing directives
 
* - this does not get called if already processing directives
 
*/
 
*/
private function validateDatabaseRow(&$row) {
+
public function validateDatabaseRow(&$row) {
 
# TODO
 
# TODO
 
}
 
}
Line 96: Line 152:
 
  */
 
  */
 
function wfSimpleSecurityAddDatabaseHooks() {
 
function wfSimpleSecurityAddDatabaseHooks() {
global $wgLoadBalancer,$wgDBtype;
+
global $wgLoadBalancer, $wgDBtype;
  
 
# This ensures that $wgLoadBalancer is not a stub object when we subclass it
 
# This ensures that $wgLoadBalancer is not a stub object when we subclass it
Line 112: Line 168:
 
global $wgSimpleSecurity;
 
global $wgSimpleSecurity;
 
$count = false;
 
$count = false;
if (!$wgSimpleSecurity->processDirectives)
+
$patched = preg_replace_callback("/(?<=SELECT ).+?(?= FROM)/", "wfSimpleSecurityPatchSQL", $sql, 1, $count);
$patched = preg_replace_callback("/(?<=SELECT ).+?(?= FROM)/", "wfSimpleSecurityPatchSQL", $sql, 1, $count);
+
return parent::query($count ? $patched : $sql, $fname, $tempIgnore);
return parent::query($count ? $patched : $sql,$fname,$tempIgnore);
 
 
}
 
}
  
Line 120: Line 175:
 
global $wgSimpleSecurity;
 
global $wgSimpleSecurity;
 
$row = parent::fetchObject($res);
 
$row = parent::fetchObject($res);
if (!$wgSimpleSecurity->processDirectives) $wgSimpleSecurity->validateDatabaseRow($row);
+
$wgSimpleSecurity->validateDatabaseRow($row);
 
return $row;
 
return $row;
 
}
 
}

Revision as of 05:19, 9 July 2008

<?php /**

* Simple Security extensionTemplate:Php
Info.svg These are the MediaWiki extensions we're using and/or developing. Please refer to the information on the mediawiki.org wiki for installation and usage details. Extensions here which have no corresponding mediawiki article are either not ready for use or have been superseded. You can also browse our extension code in our local Subversion repository or our GitHub mirror.
* - Extends the MediaWiki article protection to allow restricting viewing of article content
* - Also adds #ifusercan and #ifgroup parser functions for rendering restriction-based content
*
* See http://www.mediawiki.org/Extension:Simple_Security for installation and usage details
* See http://www.organicdesign.co.nz/Extension_talk:SimpleSecurity4.php for development notes and disucssion
* Version 4.0.0 started 2007-10-11
* Version 4.1.0 started 2008-06-12 (development funded for a slimmed down functional version)
* 
* @package MediaWiki
* @subpackage Extensions
* @author Aran Dunkley User:Nad
* @copyright © 2007 Aran Dunkley
* @licence GNU General Public Licence 2.0 or later
*/

if (!defined('MEDIAWIKI')) die('Not an entry point.');

define('SIMPLESECURITY_VERSION', '4.1.0, 2008-06-12');

  1. Global security settings

$wgSecurityMagicIf = "ifusercan"; # the name for doing a permission-based conditional $wgSecurityMagicGroup = "ifgroup"; # the name for doing a group-based conditional $wgSecurityLogActions = array('edit', 'download'); # Actions that should be logged $wgSecurityUseDBHook = true; # Add the DatabaseFetchHook to validate database access $wgSecurityAllowUser = false; # Allow restrictions based on user not just group

  1. Extra actions to allow control over in protection form

$wgSecurityExtraActions = array( 'read' => 'Read', 'source' => 'Source', 'history' => 'History' );

  1. Extra groups available in protection form

$wgSecurityExtraGroups = array();

array_unshift($wgExtensionFunctions, 'wfSetupSimpleSecurity'); # Put SimpleSecurity's setup function before all others

$wgHooks['LanguageGetMagic'][] = 'wfSimpleSecurityLanguageGetMagic'; $wgExtensionCredits['parserhook'][] = array( 'name' => "SimpleSecurity4", 'author' => 'User:Nad', 'description' => 'Extends the MediaWiki article protection to allow restricting viewing of article content', 'url' => 'http://www.mediawiki.org/wiki/Extension:Simple_Security', 'version' => SIMPLESECURITY_VERSION );

class SimpleSecurity {

/** * Constructor */ function __construct() { global $wgParser, $wgHooks, $wgLogTypes, $wgLogNames, $wgLogHeaders, $wgLogActions, $wgMessageCache, $wgSecurityMagicIf, $wgSecurityMagicGroup, $wgSecurityExtraActions, $wgSecurityExtraGroups, $wgRestrictionTypes, $wgRestrictionLevels;

# Add our parser-hooks $wgParser->setFunctionHook($wgSecurityMagicIf, array($this, 'ifUserCan')); $wgParser->setFunctionHook($wgSecurityMagicGroup, array($this, 'ifGroup')); $wgHooks['UserGetRights'][] = $this;

# Add a new log type $wgLogTypes[] = 'security'; $wgLogNames ['security'] = 'securitylogpage'; $wgLogHeaders['security'] = 'securitylogpagetext'; $wgLogActions['security/deny'] = 'securitylogentry';

# Extend protection form groups, actions and messages $wgMessageCache->addMessages(array( 'protect-unchain' => "Modify actions individually" )); foreach ($wgSecurityExtraActions as $k => $v) { if (empty($v)) $v = ucfirst($k); $wgRestrictionTypes[] = $k; $wgMessageCache->addMessages(array( "restriction-$k" => $v )); } foreach ($wgSecurityExtraGroups as $k => $v) { if (empty($v)) $v = ucfirst($k); $wgRestrictionLevels[] = $k; $wgMessageCache->addMessages(array( "protect-level-$k" => $v )); } }

/** * Process the ifUserCan conditional security directive */ public function ifUserCan(&$parser, $action, $title, $then, $else = ) { return $title->userCan($action) ? $then : $else; }

/** * Process the ifGroup conditional security directive * - evaluates to true if current uset belongs to any of the comma-separated users and/or groups in the first parameter */ public function ifGroup(&$parser, $groups, $then, $else = ) { global $wgUser; $intersection = array_intersect(array_map('strtolower', split(',', $groups)), $wgUser->getEffectiveGroups()); return count($intersection) > 0 ? $then : $else; }

   # User::getRights returns a list of rights (allowed actions) based on the current users group membership
   # Title::getRestrictions returns a list of groups who can perform a particular action
   # So getRights should filter out any title-based restriction's actions which require groups that the user is not a member of

public function onUserGetRights(&$user, &$rights) { global $wgSecurityExtraActions, $wgTitle; if (is_object($wgTitle)) { foreach ($wgSecurityExtraActions as $action => $name) { print_r($wgTitle->getRestrictions($action)); print_r($user->getEffectiveGroups()); if (count(array_intersect($wgTitle->getRestrictions($action), $user->getEffectiveGroups())) < 1) { if ($i = array_search($action, $rights)) unset($rights[$i]); } } } return true; }

# Update a rights-list based on passed user and permissions array # - pre-existing rights in the list can be removed since each permission has group, action and allow static function mergeRights(&$user, &$rights, &$permissions, $comment = false) { $groups = $this->getEffectiveGroups(); foreach ($groups as $group) if (isset($permissions[$group])) foreach ($permissions[$group] as $action => $allow) { # Add or remove a right from the list if ($allow && !in_array($action, $rights)) $rights[] = $action; elseif (!$allow && in_array($action, $rights)) array_splice($rights, array_search($action, $rights), 1); $this->info[] = array($group, $action, $allow, $comment); } }

/** * Validate the passed database row and replace any invalid content * - this does not get called if already processing directives */ public function validateDatabaseRow(&$row) { # TODO }

/** * Needed in some versions to prevent Special:Version from breaking */ public function __toString() { return __CLASS__; } }

/**

* Hooks into Database::query and Database::fetchObject via the LoadBalancer class
*/

function wfSimpleSecurityAddDatabaseHooks() { global $wgLoadBalancer, $wgDBtype;

# This ensures that $wgLoadBalancer is not a stub object when we subclass it # todo: this should be able to work in the case of it being a stub object wfGetDB();

# Create a replica of the Database class # - query method is overriden to ensure that old_id field is returned for all queries which read old_text field # - fetchObject method is overridden to validate row content based on old_id # - the changes to this class are only active for SELECT statements and while not processing security directives $type = ucfirst($wgDBtype); eval("class Database{$type}2 extends Database{$type}".' {

public function query($sql, $fname = "", $tempIgnore = false) { global $wgSimpleSecurity; $count = false; $patched = preg_replace_callback("/(?<=SELECT ).+?(?= FROM)/", "wfSimpleSecurityPatchSQL", $sql, 1, $count); return parent::query($count ? $patched : $sql, $fname, $tempIgnore); }

function fetchObject(&$res) { global $wgSimpleSecurity; $row = parent::fetchObject($res); $wgSimpleSecurity->validateDatabaseRow($row); return $row; }

}');

# Create a replica of the LoadBalancer class which uses the new Database subclass for its connection objects class LoadBalancer2 extends LoadBalancer { function reallyOpenConnection(&$server) { $server['type'] .= '2'; $db =& parent::reallyOpenConnection($server); return $db; } }

# Replace the $wgLoadBalancer object with an identical instance of the new LoadBalancer2 class $wgLoadBalancer->closeAll(); # Close any open connections as they will be of the original Database class $oldLoadBalancer = $wgLoadBalancer; $wgLoadBalancer = new LoadBalancer2($oldLoadBalancer->mServers); foreach (array_keys(get_class_vars('LoadBalancer')) as $k) $wgLoadBalancer->$k = $oldLoadBalancer->$k;

}

/**

* Patches SQL queries to ensure that the old_id field is present in all requests for the old_text field so permissions can be validated
*/

function wfSimpleSecurityPatchSQL($match) { if (!preg_match("/old_text/", $match[0])) return $match[0]; $fields = str_replace(" ", "", $match[0]); return ($fields == "*" || preg_match("/old_id/", $fields)) ? $fields : "$fields,old_id"; }

/**

* Called from $wgExtensionFunctions array when initialising extensions
*/

function wfSetupSimpleSecurity() { global $wgSimpleSecurity, $wgLanguageCode, $wgMessageCache, $wgSecurityMagic, $wgSecurityUseDBHook;

# Hooks into Database::query and Database::fetchObject via the LoadBalancer class if ($wgSecurityUseDBHook) wfSimpleSecurityAddDatabaseHooks();

# Instantiate the SimpleSecurity singleton now that the environment is prepared $wgSimpleSecurity = new SimpleSecurity();

# Add the messages used by the specialpage if ($wgLanguageCode == 'en') { $wgMessageCache->addMessages(array( 'security' => "Security log", 'securitylogpage' => "Security log", 'securitylogpagetext' => "This is a log of actions blocked by the SimpleSecurity extension.", 'securitylogentry' => "", 'securityinfotoggle' => "This article exhibits security restrictions. Click this icon for more detail.", 'securityreaddeny' => "!!Permission denied!!", 'securitysyntaxerror' => "{{#$wgSecurityMagic:Error: Both action and group must be specified!}}", 'securitylogdeny' => "Attempt to $1 $2 was denied." )); } }

/**

* Register magic words
*/

function wfSimpleSecurityLanguageGetMagic(&$magicWords, $langCode = 0) { global $wgSecurityMagicIf,$wgSecurityMagicGroup; $magicWords[$wgSecurityMagicIf] = array($langCode, $wgSecurityMagicIf); $magicWords[$wgSecurityMagicGroup] = array($langCode, $wgSecurityMagicGroup); return true; }