Commit a4736cbf authored by Franco Fichtner's avatar Franco Fichtner

www: apply PSR2 style to a few files

JavaScript works like a charm, too.
parent 41e50c06
...@@ -31,13 +31,13 @@ require_once("guiconfig.inc"); ...@@ -31,13 +31,13 @@ require_once("guiconfig.inc");
require_once("pfsense-utils.inc"); require_once("pfsense-utils.inc");
require_once("interfaces.inc"); require_once("interfaces.inc");
function interfaces_carp_set_maintenancemode($carp_maintenancemode){ function interfaces_carp_set_maintenancemode($carp_maintenancemode)
{
global $config; global $config;
if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) { if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) {
unset($config["virtualip_carp_maintenancemode"]); unset($config["virtualip_carp_maintenancemode"]);
write_config("Leave CARP maintenance mode"); write_config("Leave CARP maintenance mode");
} else } elseif (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) {
if (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) {
$config["virtualip_carp_maintenancemode"] = true; $config["virtualip_carp_maintenancemode"] = true;
write_config("Enter CARP maintenance mode"); write_config("Enter CARP maintenance mode");
} }
...@@ -56,13 +56,13 @@ unset($carp_interface_count_cache); ...@@ -56,13 +56,13 @@ unset($carp_interface_count_cache);
unset($interface_ip_arr_cache); unset($interface_ip_arr_cache);
$status = get_carp_status(); $status = get_carp_status();
if($_POST['carp_maintenancemode'] <> "") { if ($_POST['carp_maintenancemode'] <> "") {
interfaces_carp_set_maintenancemode(!isset($config["virtualip_carp_maintenancemode"])); interfaces_carp_set_maintenancemode(!isset($config["virtualip_carp_maintenancemode"]));
} }
if($_POST['disablecarp'] <> "") { if ($_POST['disablecarp'] <> "") {
if($status == true) { if ($status == true) {
set_single_sysctl('net.inet.carp.allow', '0'); set_single_sysctl('net.inet.carp.allow', '0');
if(is_array($config['virtualip']['vip'])) { if (is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip']; $viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) { foreach ($viparr as $vip) {
switch ($vip['mode']) { switch ($vip['mode']) {
...@@ -76,7 +76,7 @@ if($_POST['disablecarp'] <> "") { ...@@ -76,7 +76,7 @@ if($_POST['disablecarp'] <> "") {
$savemsg = sprintf(gettext("%s IPs have been disabled. Please note that disabling does not survive a reboot."), $carp_counter); $savemsg = sprintf(gettext("%s IPs have been disabled. Please note that disabling does not survive a reboot."), $carp_counter);
} else { } else {
$savemsg = gettext("CARP has been enabled."); $savemsg = gettext("CARP has been enabled.");
if(is_array($config['virtualip']['vip'])) { if (is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip']; $viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) { foreach ($viparr as $vip) {
switch ($vip['mode']) { switch ($vip['mode']) {
...@@ -111,9 +111,13 @@ include("head.inc"); ...@@ -111,9 +111,13 @@ include("head.inc");
<div class="row"> <div class="row">
<section class="col-xs-12"> <section class="col-xs-12">
<?php if (isset($savemsg)) print_info_box($savemsg); ?> <?php if (isset($savemsg)) {
print_info_box($savemsg);
} ?>
<?PHP if ($carp_detected_problems) print_info_box(gettext("CARP has detected a problem and this unit has been demoted to BACKUP status.") . "<br />" . gettext("Check link status on all interfaces with configured CARP VIPs.")); ?> <?PHP if ($carp_detected_problems) {
print_info_box(gettext("CARP has detected a problem and this unit has been demoted to BACKUP status.") . "<br />" . gettext("Check link status on all interfaces with configured CARP VIPs."));
} ?>
<div class="content-box"> <div class="content-box">
...@@ -121,23 +125,23 @@ include("head.inc"); ...@@ -121,23 +125,23 @@ include("head.inc");
<form action="<?=$_SERVER['REQUEST_URI'];?>" method="post"> <form action="<?=$_SERVER['REQUEST_URI'];?>" method="post">
<?php <?php
$carpcount = 0; $carpcount = 0;
if(isset($config['virtualip']['vip'])) { if (isset($config['virtualip']['vip'])) {
foreach($config['virtualip']['vip'] as $carp) { foreach ($config['virtualip']['vip'] as $carp) {
if ($carp['mode'] == "carp") { if ($carp['mode'] == "carp") {
$carpcount++; $carpcount++;
break; break;
} }
} }
} }
if($carpcount > 0) { if ($carpcount > 0) {
if($status == false) { if ($status == false) {
$carp_enabled = false; $carp_enabled = false;
echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Enable CARP") . "\" />"; echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Enable CARP") . "\" />";
} else { } else {
$carp_enabled = true; $carp_enabled = true;
echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Temporarily Disable CARP") . "\" />"; echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Temporarily Disable CARP") . "\" />";
} }
if(isset($config["virtualip_carp_maintenancemode"])) { if (isset($config["virtualip_carp_maintenancemode"])) {
echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Leave Persistent CARP Maintenance Mode") . "\" />"; echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Leave Persistent CARP Maintenance Mode") . "\" />";
} else { } else {
echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Enter Persistent CARP Maintenance Mode") . "\" />"; echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Enter Persistent CARP Maintenance Mode") . "\" />";
...@@ -158,11 +162,11 @@ include("head.inc"); ...@@ -158,11 +162,11 @@ include("head.inc");
echo "</table></div></form><center><br />" . gettext("Could not locate any defined CARP interfaces."); echo "</table></div></form><center><br />" . gettext("Could not locate any defined CARP interfaces.");
} } elseif (is_array($config['virtualip']['vip'])) {
elseif(is_array($config['virtualip']['vip'])) { foreach ($config['virtualip']['vip'] as $carp) {
foreach($config['virtualip']['vip'] as $carp) { if ($carp['mode'] != "carp") {
if ($carp['mode'] != "carp")
continue; continue;
}
$ipaddress = $carp['subnet']; $ipaddress = $carp['subnet'];
$password = $carp['password']; $password = $carp['password'];
$netmask = $carp['subnet_bits']; $netmask = $carp['subnet_bits'];
...@@ -172,15 +176,15 @@ include("head.inc"); ...@@ -172,15 +176,15 @@ include("head.inc");
$status = get_carp_interface_status("{$carp['interface']}_vip{$carp['vhid']}"); $status = get_carp_interface_status("{$carp['interface']}_vip{$carp['vhid']}");
echo "<tr>"; echo "<tr>";
$align = "style=\"vertical-align:middle\""; $align = "style=\"vertical-align:middle\"";
if($carp_enabled == false) { if ($carp_enabled == false) {
$icon = "<span {$align} class=\"glyphicon glyphicon-remove text-danger\" alt=\"disabled\" ></span>"; $icon = "<span {$align} class=\"glyphicon glyphicon-remove text-danger\" alt=\"disabled\" ></span>";
$status = "DISABLED"; $status = "DISABLED";
} else { } else {
if($status == "MASTER") { if ($status == "MASTER") {
$icon = "<span {$align} class=\"glyphicon glyphicon-play text-success\" alt=\"master\" ></span>"; $icon = "<span {$align} class=\"glyphicon glyphicon-play text-success\" alt=\"master\" ></span>";
} else if($status == "BACKUP") { } elseif ($status == "BACKUP") {
$icon = "<span {$align} class=\"glyphicon glyphicon-play text-muted\" alt=\"backup\" ></span>"; $icon = "<span {$align} class=\"glyphicon glyphicon-play text-muted\" alt=\"backup\" ></span>";
} else if($status == "INIT") { } elseif ($status == "INIT") {
$icon = "<span {$align} class=\"glyphicon glyphicon-info-sign\" alt=\"init\" ></span>"; $icon = "<span {$align} class=\"glyphicon glyphicon-info-sign\" alt=\"init\" ></span>";
} }
} }
...@@ -199,7 +203,8 @@ include("head.inc"); ...@@ -199,7 +203,8 @@ include("head.inc");
<p class="vexpl"> <p class="vexpl">
<span class="red"><strong><?=gettext("Note"); ?>:</strong></span> <span class="red"><strong><?=gettext("Note"); ?>:</strong></span>
<br /> <br />
<?=gettext("You can configure high availability settings"); ?> <a href="system_hasync.php"><?=gettext("here"); ?></a>. <?=gettext("You can configure high availability settings");
?> <a href="system_hasync.php"><?=gettext("here"); ?></a>.
</p> </p>
<?php <?php
......
...@@ -38,7 +38,7 @@ function upload_crash_report($files, $agent) ...@@ -38,7 +38,7 @@ function upload_crash_report($files, $agent)
$post = array(); $post = array();
$counter = 0; $counter = 0;
foreach($files as $filename) { foreach ($files as $filename) {
if (is_link($filename) || $filename == '/var/crash/minfree.gz' || $filename == '/var/crash/bounds.gz') { if (is_link($filename) || $filename == '/var/crash/minfree.gz' || $filename == '/var/crash/bounds.gz') {
continue; continue;
} }
...@@ -55,7 +55,7 @@ function upload_crash_report($files, $agent) ...@@ -55,7 +55,7 @@ function upload_crash_report($files, $agent)
curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data;' ) ); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data;' ));
$response = curl_exec($ch); $response = curl_exec($ch);
curl_close($ch); curl_close($ch);
......
...@@ -8,16 +8,28 @@ ...@@ -8,16 +8,28 @@
// Here are the basic overloaded method definitions // Here are the basic overloaded method definitions
// The wrapper must be set BEFORE onreadystatechange is written to, since // The wrapper must be set BEFORE onreadystatechange is written to, since
// a bug in ActiveXObject prevents us from properly testing for it. // a bug in ActiveXObject prevents us from properly testing for it.
CsrfMagic = function(real) { CsrfMagic = function (real) {
// try to make it ourselves, if you didn't pass it // try to make it ourselves, if you didn't pass it
if (!real) try { real = new XMLHttpRequest; } catch (e) {;} if (!real) {
if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {;} try {
if (!real) try { real = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {;} real = new XMLHttpRequest; } } catch (e) {
if (!real) try { real = new ActiveXObject('Msxml2.XMLHTTP.4.0'); } catch (e) {;} ;}
if (!real) {
try {
real = new ActiveXObject('Msxml2.XMLHTTP'); } } catch (e) {
;}
if (!real) {
try {
real = new ActiveXObject('Microsoft.XMLHTTP'); } } catch (e) {
;}
if (!real) {
try {
real = new ActiveXObject('Msxml2.XMLHTTP.4.0'); } } catch (e) {
;}
this.csrf = real; this.csrf = real;
// properties // properties
var csrfMagic = this; var csrfMagic = this;
real.onreadystatechange = function() { real.onreadystatechange = function () {
csrfMagic._updateProps(); csrfMagic._updateProps();
return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null; return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null;
}; };
...@@ -26,19 +38,23 @@ CsrfMagic = function(real) { ...@@ -26,19 +38,23 @@ CsrfMagic = function(real) {
CsrfMagic.prototype = { CsrfMagic.prototype = {
open: function(method, url, async, username, password) { open: function (method, url, async, username, password) {
if (method == 'POST') this.csrf_isPost = true; if (method == 'POST') {
this.csrf_isPost = true; }
// deal with Opera bug, thanks jQuery // deal with Opera bug, thanks jQuery
if (username) return this.csrf_open(method, url, async, username, password); if (username) {
else return this.csrf_open(method, url, async); return this.csrf_open(method, url, async, username, password); } else {
return this.csrf_open(method, url, async); }
}, },
csrf_open: function(method, url, async, username, password) { csrf_open: function (method, url, async, username, password) {
if (username) return this.csrf.open(method, url, async, username, password); if (username) {
else return this.csrf.open(method, url, async); return this.csrf.open(method, url, async, username, password); } else {
return this.csrf.open(method, url, async); }
}, },
send: function(data) { send: function (data) {
if (!this.csrf_isPost) return this.csrf_send(data); if (!this.csrf_isPost) {
return this.csrf_send(data); }
prepend = csrfMagicName + '=' + csrfMagicToken + '&'; prepend = csrfMagicName + '=' + csrfMagicToken + '&';
if (this.csrf_purportedLength === undefined) { if (this.csrf_purportedLength === undefined) {
this.csrf_setRequestHeader("Content-length", this.csrf_purportedLength + prepend.length); this.csrf_setRequestHeader("Content-length", this.csrf_purportedLength + prepend.length);
...@@ -47,11 +63,11 @@ CsrfMagic.prototype = { ...@@ -47,11 +63,11 @@ CsrfMagic.prototype = {
delete this.csrf_isPost; delete this.csrf_isPost;
return this.csrf_send(prepend + data); return this.csrf_send(prepend + data);
}, },
csrf_send: function(data) { csrf_send: function (data) {
return this.csrf.send(data); return this.csrf.send(data);
}, },
setRequestHeader: function(header, value) { setRequestHeader: function (header, value) {
// We have to auto-set this at the end, since we don't know how long the // We have to auto-set this at the end, since we don't know how long the
// nonce is when added to the data. // nonce is when added to the data.
if (this.csrf_isPost && header == "Content-length") { if (this.csrf_isPost && header == "Content-length") {
...@@ -60,23 +76,23 @@ CsrfMagic.prototype = { ...@@ -60,23 +76,23 @@ CsrfMagic.prototype = {
} }
return this.csrf_setRequestHeader(header, value); return this.csrf_setRequestHeader(header, value);
}, },
csrf_setRequestHeader: function(header, value) { csrf_setRequestHeader: function (header, value) {
return this.csrf.setRequestHeader(header, value); return this.csrf.setRequestHeader(header, value);
}, },
abort: function() { abort: function () {
return this.csrf.abort(); return this.csrf.abort();
}, },
getAllResponseHeaders: function() { getAllResponseHeaders: function () {
return this.csrf.getAllResponseHeaders(); return this.csrf.getAllResponseHeaders();
}, },
getResponseHeader: function(header) { getResponseHeader: function (header) {
return this.csrf.getResponseHeader(header); return this.csrf.getResponseHeader(header);
} // , } // ,
} }
// proprietary // proprietary
CsrfMagic.prototype._updateProps = function() { CsrfMagic.prototype._updateProps = function () {
this.readyState = this.csrf.readyState; this.readyState = this.csrf.readyState;
if (this.readyState == 4) { if (this.readyState == 4) {
this.responseText = this.csrf.responseText; this.responseText = this.csrf.responseText;
...@@ -85,20 +101,23 @@ CsrfMagic.prototype._updateProps = function() { ...@@ -85,20 +101,23 @@ CsrfMagic.prototype._updateProps = function() {
this.statusText = this.csrf.statusText; this.statusText = this.csrf.statusText;
} }
} }
CsrfMagic.process = function(base) { CsrfMagic.process = function (base) {
var prepend = csrfMagicName + '=' + csrfMagicToken; var prepend = csrfMagicName + '=' + csrfMagicToken;
if (base) return prepend + '&' + base; if (base) {
return prepend + '&' + base; }
return prepend; return prepend;
} }
// callback function for when everything on the page has loaded // callback function for when everything on the page has loaded
CsrfMagic.end = function() { CsrfMagic.end = function () {
// This rewrites forms AGAIN, so in case buffering didn't work this // This rewrites forms AGAIN, so in case buffering didn't work this
// certainly will. // certainly will.
forms = document.getElementsByTagName('form'); forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) { for (var i = 0; i < forms.length; i++) {
form = forms[i]; form = forms[i];
if (form.method.toUpperCase() !== 'POST') continue; if (form.method.toUpperCase() !== 'POST') {
if (form.elements[csrfMagicName]) continue; continue; }
if (form.elements[csrfMagicName]) {
continue; }
var input = document.createElement('input'); var input = document.createElement('input');
input.setAttribute('name', csrfMagicName); input.setAttribute('name', csrfMagicName);
input.setAttribute('value', csrfMagicToken); input.setAttribute('value', csrfMagicToken);
...@@ -132,7 +151,7 @@ if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') { ...@@ -132,7 +151,7 @@ if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') {
// jQuery didn't implement a new XMLHttpRequest function, so we have // jQuery didn't implement a new XMLHttpRequest function, so we have
// to do this the hard way. // to do this the hard way.
jQuery.csrf_ajax = jQuery.ajax; jQuery.csrf_ajax = jQuery.ajax;
jQuery.ajax = function( s ) { jQuery.ajax = function ( s ) {
if (s.type && s.type.toUpperCase() == 'POST') { if (s.type && s.type.toUpperCase() == 'POST') {
s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s)); s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
if ( s.data && s.processData && typeof s.data != "string" ) { if ( s.data && s.processData && typeof s.data != "string" ) {
...@@ -140,13 +159,13 @@ if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') { ...@@ -140,13 +159,13 @@ if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') {
} }
s.data = CsrfMagic.process(s.data); s.data = CsrfMagic.process(s.data);
} }
return jQuery.csrf_ajax( s ); return jQuery.csrf_ajax(s);
} }
} }
if (window.Prototype) { if (window.Prototype) {
// This works for script.aculo.us too // This works for script.aculo.us too
Ajax.csrf_getTransport = Ajax.getTransport; Ajax.csrf_getTransport = Ajax.getTransport;
Ajax.getTransport = function() { Ajax.getTransport = function () {
return new CsrfMagic(Ajax.csrf_getTransport()); return new CsrfMagic(Ajax.csrf_getTransport());
} }
} }
......
...@@ -137,7 +137,8 @@ $GLOBALS['csrf']['version'] = '1.0.4'; ...@@ -137,7 +137,8 @@ $GLOBALS['csrf']['version'] = '1.0.4';
* Rewrites <form> on the fly to add CSRF tokens to them. This can also * Rewrites <form> on the fly to add CSRF tokens to them. This can also
* inject our JavaScript library. * inject our JavaScript library.
*/ */
function csrf_ob_handler($buffer, $flags) { function csrf_ob_handler($buffer, $flags)
{
// Even though the user told us to rewrite, we should do a quick heuristic // Even though the user told us to rewrite, we should do a quick heuristic
// to check if the page is *actually* HTML. We don't begin rewriting until // to check if the page is *actually* HTML. We don't begin rewriting until
// we hit the first <html tag. // we hit the first <html tag.
...@@ -181,23 +182,32 @@ function csrf_ob_handler($buffer, $flags) { ...@@ -181,23 +182,32 @@ function csrf_ob_handler($buffer, $flags) {
* @param bool $fatal Whether or not to fatally error out if there is a problem. * @param bool $fatal Whether or not to fatally error out if there is a problem.
* @return True if check passes or is not necessary, false if failure. * @return True if check passes or is not necessary, false if failure.
*/ */
function csrf_check($fatal = true) { function csrf_check($fatal = true)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') return true; {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return true;
}
csrf_start(); csrf_start();
$name = $GLOBALS['csrf']['input-name']; $name = $GLOBALS['csrf']['input-name'];
$ok = false; $ok = false;
$tokens = ''; $tokens = '';
do { do {
if (!isset($_POST[$name])) break; if (!isset($_POST[$name])) {
break;
}
// we don't regenerate a token and check it because some token creation // we don't regenerate a token and check it because some token creation
// schemes are volatile. // schemes are volatile.
$tokens = $_POST[$name]; $tokens = $_POST[$name];
if (!csrf_check_tokens($tokens)) break; if (!csrf_check_tokens($tokens)) {
break;
}
$ok = true; $ok = true;
} while (false); } while (false);
if ($fatal && !$ok) { if ($fatal && !$ok) {
$callback = $GLOBALS['csrf']['callback']; $callback = $GLOBALS['csrf']['callback'];
if (trim($tokens, 'A..Za..z0..9:;,') !== '') $tokens = 'hidden'; if (trim($tokens, 'A..Za..z0..9:;,') !== '') {
$tokens = 'hidden';
}
$callback($tokens); $callback($tokens);
exit; exit;
} }
...@@ -208,7 +218,8 @@ function csrf_check($fatal = true) { ...@@ -208,7 +218,8 @@ function csrf_check($fatal = true) {
* Retrieves a valid token(s) for a particular context. Tokens are separated * Retrieves a valid token(s) for a particular context. Tokens are separated
* by semicolons. * by semicolons.
*/ */
function csrf_get_tokens() { function csrf_get_tokens()
{
$has_cookies = !empty($_COOKIE); $has_cookies = !empty($_COOKIE);
// $ip implements a composite key, which is sent if the user hasn't sent // $ip implements a composite key, which is sent if the user hasn't sent
...@@ -224,15 +235,21 @@ function csrf_get_tokens() { ...@@ -224,15 +235,21 @@ function csrf_get_tokens() {
csrf_start(); csrf_start();
// These are "strong" algorithms that don't require per se a secret // These are "strong" algorithms that don't require per se a secret
if (session_id()) return 'sid:' . csrf_hash(session_id()) . $ip; if (session_id()) {
return 'sid:' . csrf_hash(session_id()) . $ip;
}
if ($GLOBALS['csrf']['cookie']) { if ($GLOBALS['csrf']['cookie']) {
$val = csrf_generate_secret(); $val = csrf_generate_secret();
setcookie($GLOBALS['csrf']['cookie'], $val); setcookie($GLOBALS['csrf']['cookie'], $val);
return 'cookie:' . csrf_hash($val) . $ip; return 'cookie:' . csrf_hash($val) . $ip;
} }
if ($GLOBALS['csrf']['key']) return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip; if ($GLOBALS['csrf']['key']) {
return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip;
}
// These further algorithms require a server-side secret // These further algorithms require a server-side secret
if (!$secret) return 'invalid'; if (!$secret) {
return 'invalid';
}
if ($GLOBALS['csrf']['user'] !== false) { if ($GLOBALS['csrf']['user'] !== false) {
return 'user:' . csrf_hash($GLOBALS['csrf']['user']); return 'user:' . csrf_hash($GLOBALS['csrf']['user']);
} }
...@@ -242,17 +259,21 @@ function csrf_get_tokens() { ...@@ -242,17 +259,21 @@ function csrf_get_tokens() {
return 'invalid'; return 'invalid';
} }
function csrf_flattenpost($data) { function csrf_flattenpost($data)
{
$ret = array(); $ret = array();
foreach($data as $n => $v) { foreach ($data as $n => $v) {
$ret = array_merge($ret, csrf_flattenpost2(1, $n, $v)); $ret = array_merge($ret, csrf_flattenpost2(1, $n, $v));
} }
return $ret; return $ret;
} }
function csrf_flattenpost2($level, $key, $data) { function csrf_flattenpost2($level, $key, $data)
if(!is_array($data)) return array($key => $data); {
if (!is_array($data)) {
return array($key => $data);
}
$ret = array(); $ret = array();
foreach($data as $n => $v) { foreach ($data as $n => $v) {
$nk = $level >= 1 ? $key."[$n]" : "[$n]"; $nk = $level >= 1 ? $key."[$n]" : "[$n]";
$ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v)); $ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v));
} }
...@@ -262,12 +283,15 @@ function csrf_flattenpost2($level, $key, $data) { ...@@ -262,12 +283,15 @@ function csrf_flattenpost2($level, $key, $data) {
/** /**
* @param $tokens is safe for HTML consumption * @param $tokens is safe for HTML consumption
*/ */
function csrf_callback($tokens) { function csrf_callback($tokens)
{
// (yes, $tokens is safe to echo without escaping) // (yes, $tokens is safe to echo without escaping)
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden'); header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
$data = ''; $data = '';
foreach (csrf_flattenpost($_POST) as $key => $value) { foreach (csrf_flattenpost($_POST) as $key => $value) {
if ($key == $GLOBALS['csrf']['input-name']) continue; if ($key == $GLOBALS['csrf']['input-name']) {
continue;
}
$data .= '<input type="hidden" name="'.htmlspecialchars($key).'" value="'.htmlspecialchars($value).'" />'; $data .= '<input type="hidden" name="'.htmlspecialchars($key).'" value="'.htmlspecialchars($value).'" />';
} }
echo "<html><head><title>CSRF check failed</title></head> echo "<html><head><title>CSRF check failed</title></head>
...@@ -283,10 +307,15 @@ function csrf_callback($tokens) { ...@@ -283,10 +307,15 @@ function csrf_callback($tokens) {
* Checks if a composite token is valid. Outward facing code should use this * Checks if a composite token is valid. Outward facing code should use this
* instead of csrf_check_token() * instead of csrf_check_token()
*/ */
function csrf_check_tokens($tokens) { function csrf_check_tokens($tokens)
if (is_string($tokens)) $tokens = explode(';', $tokens); {
if (is_string($tokens)) {
$tokens = explode(';', $tokens);
}
foreach ($tokens as $token) { foreach ($tokens as $token) {
if (csrf_check_token($token)) return true; if (csrf_check_token($token)) {
return true;
}
} }
return false; return false;
} }
...@@ -294,39 +323,64 @@ function csrf_check_tokens($tokens) { ...@@ -294,39 +323,64 @@ function csrf_check_tokens($tokens) {
/** /**
* Checks if a token is valid. * Checks if a token is valid.
*/ */
function csrf_check_token($token) { function csrf_check_token($token)
if (strpos($token, ':') === false) return false; {
if (strpos($token, ':') === false) {
return false;
}
list($type, $value) = explode(':', $token, 2); list($type, $value) = explode(':', $token, 2);
if (strpos($value, ',') === false) return false; if (strpos($value, ',') === false) {
return false;
}
list($x, $time) = explode(',', $token, 2); list($x, $time) = explode(',', $token, 2);
if ($GLOBALS['csrf']['expires']) { if ($GLOBALS['csrf']['expires']) {
if (time() > $time + $GLOBALS['csrf']['expires']) return false; if (time() > $time + $GLOBALS['csrf']['expires']) {
return false;
}
} }
switch ($type) { switch ($type) {
case 'sid': case 'sid':
return $value === csrf_hash(session_id(), $time); return $value === csrf_hash(session_id(), $time);
case 'cookie': case 'cookie':
$n = $GLOBALS['csrf']['cookie']; $n = $GLOBALS['csrf']['cookie'];
if (!$n) return false; if (!$n) {
if (!isset($_COOKIE[$n])) return false; return false;
}
if (!isset($_COOKIE[$n])) {
return false;
}
return $value === csrf_hash($_COOKIE[$n], $time); return $value === csrf_hash($_COOKIE[$n], $time);
case 'key': case 'key':
if (!$GLOBALS['csrf']['key']) return false; if (!$GLOBALS['csrf']['key']) {
return false;
}
return $value === csrf_hash($GLOBALS['csrf']['key'], $time); return $value === csrf_hash($GLOBALS['csrf']['key'], $time);
// We could disable these 'weaker' checks if 'key' was set, but // We could disable these 'weaker' checks if 'key' was set, but
// that doesn't make me feel good then about the cookie-based // that doesn't make me feel good then about the cookie-based
// implementation. // implementation.
case 'user': case 'user':
if (!csrf_get_secret()) return false; if (!csrf_get_secret()) {
if ($GLOBALS['csrf']['user'] === false) return false; return false;
}
if ($GLOBALS['csrf']['user'] === false) {
return false;
}
return $value === csrf_hash($GLOBALS['csrf']['user'], $time); return $value === csrf_hash($GLOBALS['csrf']['user'], $time);
case 'ip': case 'ip':
if (!csrf_get_secret()) return false; if (!csrf_get_secret()) {
return false;
}
// do not allow IP-based checks if the username is set, or if // do not allow IP-based checks if the username is set, or if
// the browser sent cookies // the browser sent cookies
if ($GLOBALS['csrf']['user'] !== false) return false; if ($GLOBALS['csrf']['user'] !== false) {
if (!empty($_COOKIE)) return false; return false;
if (!$GLOBALS['csrf']['allow-ip']) return false; }
if (!empty($_COOKIE)) {
return false;
}
if (!$GLOBALS['csrf']['allow-ip']) {
return false;
}
return $value === csrf_hash($_SERVER['IP_ADDRESS'], $time); return $value === csrf_hash($_SERVER['IP_ADDRESS'], $time);
} }
return false; return false;
...@@ -335,7 +389,8 @@ function csrf_check_token($token) { ...@@ -335,7 +389,8 @@ function csrf_check_token($token) {
/** /**
* Sets a configuration value. * Sets a configuration value.
*/ */
function csrf_conf($key, $val) { function csrf_conf($key, $val)
{
if (!isset($GLOBALS['csrf'][$key])) { if (!isset($GLOBALS['csrf'][$key])) {
trigger_error('No such configuration ' . $key, E_USER_WARNING); trigger_error('No such configuration ' . $key, E_USER_WARNING);
return; return;
...@@ -346,7 +401,8 @@ function csrf_conf($key, $val) { ...@@ -346,7 +401,8 @@ function csrf_conf($key, $val) {
/** /**
* Starts a session if we're allowed to. * Starts a session if we're allowed to.
*/ */
function csrf_start() { function csrf_start()
{
if ($GLOBALS['csrf']['auto-session'] && session_status() == PHP_SESSION_NONE) { if ($GLOBALS['csrf']['auto-session'] && session_status() == PHP_SESSION_NONE) {
session_start(); session_start();
} }
...@@ -355,8 +411,11 @@ function csrf_start() { ...@@ -355,8 +411,11 @@ function csrf_start() {
/** /**
* Retrieves the secret, and generates one if necessary. * Retrieves the secret, and generates one if necessary.
*/ */
function csrf_get_secret() { function csrf_get_secret()
if ($GLOBALS['csrf']['secret']) return $GLOBALS['csrf']['secret']; {
if ($GLOBALS['csrf']['secret']) {
return $GLOBALS['csrf']['secret'];
}
$dir = dirname(__FILE__); $dir = dirname(__FILE__);
$file = $dir . '/csrf-secret.php'; $file = $dir . '/csrf-secret.php';
$secret = ''; $secret = '';
...@@ -377,7 +436,8 @@ function csrf_get_secret() { ...@@ -377,7 +436,8 @@ function csrf_get_secret() {
/** /**
* Generates a random string as the hash of time, microtime, and mt_rand. * Generates a random string as the hash of time, microtime, and mt_rand.
*/ */
function csrf_generate_secret($len = 32) { function csrf_generate_secret($len = 32)
{
$r = ''; $r = '';
for ($i = 0; $i < 32; $i++) { for ($i = 0; $i < 32; $i++) {
$r .= chr(mt_rand(0, 255)); $r .= chr(mt_rand(0, 255));
...@@ -390,14 +450,23 @@ function csrf_generate_secret($len = 32) { ...@@ -390,14 +450,23 @@ function csrf_generate_secret($len = 32) {
* Generates a hash/expiry double. If time isn't set it will be calculated * Generates a hash/expiry double. If time isn't set it will be calculated
* from the current time. * from the current time.
*/ */
function csrf_hash($value, $time = null) { function csrf_hash($value, $time = null)
if (!$time) $time = time(); {
if (!$time) {
$time = time();
}
return sha1(csrf_get_secret() . $value . $time) . ',' . $time; return sha1(csrf_get_secret() . $value . $time) . ',' . $time;
} }
// Load user configuration // Load user configuration
if (function_exists('csrf_startup')) csrf_startup(); if (function_exists('csrf_startup')) {
csrf_startup();
}
// Initialize our handler // Initialize our handler
if ($GLOBALS['csrf']['rewrite']) ob_start('csrf_ob_handler'); if ($GLOBALS['csrf']['rewrite']) {
ob_start('csrf_ob_handler');
}
// Perform check // Perform check
if (!$GLOBALS['csrf']['defer']) csrf_check(); if (!$GLOBALS['csrf']['defer']) {
csrf_check();
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment