Commit d0266bc7 authored by Franco Fichtner's avatar Franco Fichtner

www: apply PSR2 style to a few files

JavaScript works like a charm, too.
parent 4734cb7b
......@@ -31,23 +31,23 @@ require_once("guiconfig.inc");
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
function interfaces_carp_set_maintenancemode($carp_maintenancemode){
global $config;
if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) {
unset($config["virtualip_carp_maintenancemode"]);
write_config("Leave CARP maintenance mode");
} else
if (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) {
$config["virtualip_carp_maintenancemode"] = true;
write_config("Enter CARP maintenance mode");
}
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
if ($vip['mode'] == "carp") {
interface_carp_configure($vip);
}
}
function interfaces_carp_set_maintenancemode($carp_maintenancemode)
{
global $config;
if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) {
unset($config["virtualip_carp_maintenancemode"]);
write_config("Leave CARP maintenance mode");
} elseif (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) {
$config["virtualip_carp_maintenancemode"] = true;
write_config("Enter CARP maintenance mode");
}
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
if ($vip['mode'] == "carp") {
interface_carp_configure($vip);
}
}
}
......@@ -56,40 +56,40 @@ unset($carp_interface_count_cache);
unset($interface_ip_arr_cache);
$status = get_carp_status();
if($_POST['carp_maintenancemode'] <> "") {
interfaces_carp_set_maintenancemode(!isset($config["virtualip_carp_maintenancemode"]));
if ($_POST['carp_maintenancemode'] <> "") {
interfaces_carp_set_maintenancemode(!isset($config["virtualip_carp_maintenancemode"]));
}
if($_POST['disablecarp'] <> "") {
if($status == true) {
set_single_sysctl('net.inet.carp.allow', '0');
if(is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
switch ($vip['mode']) {
case "carp":
interface_vip_bring_down($vip);
sleep(1);
break;
}
}
}
$savemsg = sprintf(gettext("%s IPs have been disabled. Please note that disabling does not survive a reboot."), $carp_counter);
} else {
$savemsg = gettext("CARP has been enabled.");
if(is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
switch ($vip['mode']) {
case "carp":
interface_carp_configure($vip);
sleep(1);
break;
}
}
}
interfaces_carp_setup();
set_single_sysctl('net.inet.carp.allow', '1');
}
if ($_POST['disablecarp'] <> "") {
if ($status == true) {
set_single_sysctl('net.inet.carp.allow', '0');
if (is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
switch ($vip['mode']) {
case "carp":
interface_vip_bring_down($vip);
sleep(1);
break;
}
}
}
$savemsg = sprintf(gettext("%s IPs have been disabled. Please note that disabling does not survive a reboot."), $carp_counter);
} else {
$savemsg = gettext("CARP has been enabled.");
if (is_array($config['virtualip']['vip'])) {
$viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) {
switch ($vip['mode']) {
case "carp":
interface_carp_configure($vip);
sleep(1);
break;
}
}
}
interfaces_carp_setup();
set_single_sysctl('net.inet.carp.allow', '1');
}
}
$status = get_carp_status();
......@@ -111,39 +111,43 @@ include("head.inc");
<div class="row">
<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">
<form action="<?=$_SERVER['REQUEST_URI'];?>" method="post">
<?php
$carpcount = 0;
if(isset($config['virtualip']['vip'])) {
foreach($config['virtualip']['vip'] as $carp) {
if ($carp['mode'] == "carp") {
$carpcount++;
break;
}
}
}
if($carpcount > 0) {
if($status == false) {
$carp_enabled = false;
echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Enable CARP") . "\" />";
} else {
$carp_enabled = true;
echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Temporarily Disable CARP") . "\" />";
}
if(isset($config["virtualip_carp_maintenancemode"])) {
echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Leave Persistent CARP Maintenance Mode") . "\" />";
} else {
echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Enter Persistent CARP Maintenance Mode") . "\" />";
}
}
?>
$carpcount = 0;
if (isset($config['virtualip']['vip'])) {
foreach ($config['virtualip']['vip'] as $carp) {
if ($carp['mode'] == "carp") {
$carpcount++;
break;
}
}
}
if ($carpcount > 0) {
if ($status == false) {
$carp_enabled = false;
echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Enable CARP") . "\" />";
} else {
$carp_enabled = true;
echo "<input type=\"submit\" name=\"disablecarp\" id=\"disablecarp\" value=\"" . gettext("Temporarily Disable CARP") . "\" />";
}
if (isset($config["virtualip_carp_maintenancemode"])) {
echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Leave Persistent CARP Maintenance Mode") . "\" />";
} else {
echo "<input type=\"submit\" name=\"carp_maintenancemode\" id=\"carp_maintenancemode\" value=\"" . gettext("Enter Persistent CARP Maintenance Mode") . "\" />";
}
}
?>
<div class="table-responsive">
......@@ -154,43 +158,43 @@ include("head.inc");
<td class="listhdrr" align="center"><?=gettext("Status"); ?></td>
</tr>
<?php
if ($carpcount == 0) {
echo "</table></div></form><center><br />" . gettext("Could not locate any defined CARP interfaces.");
}
elseif(is_array($config['virtualip']['vip'])) {
foreach($config['virtualip']['vip'] as $carp) {
if ($carp['mode'] != "carp")
continue;
$ipaddress = $carp['subnet'];
$password = $carp['password'];
$netmask = $carp['subnet_bits'];
$vhid = $carp['vhid'];
$advskew = $carp['advskew'];
$advbase = $carp['advbase'];
$status = get_carp_interface_status("{$carp['interface']}_vip{$carp['vhid']}");
echo "<tr>";
$align = "style=\"vertical-align:middle\"";
if($carp_enabled == false) {
$icon = "<span {$align} class=\"glyphicon glyphicon-remove text-danger\" alt=\"disabled\" ></span>";
$status = "DISABLED";
} else {
if($status == "MASTER") {
$icon = "<span {$align} class=\"glyphicon glyphicon-play text-success\" alt=\"master\" ></span>";
} else if($status == "BACKUP") {
$icon = "<span {$align} class=\"glyphicon glyphicon-play text-muted\" alt=\"backup\" ></span>";
} else if($status == "INIT") {
$icon = "<span {$align} class=\"glyphicon glyphicon-info-sign\" alt=\"init\" ></span>";
}
}
echo "<td class=\"listlr\" align=\"center\">" . convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$vhid} &nbsp;</td>";
echo "<td class=\"listlr\" align=\"center\">" . $ipaddress . "&nbsp;</td>";
echo "<td class=\"listlr\" align=\"center\">{$icon}&nbsp;&nbsp;" . $status . "&nbsp;</td>";
echo "</tr>";
}
}
?>
if ($carpcount == 0) {
echo "</table></div></form><center><br />" . gettext("Could not locate any defined CARP interfaces.");
} elseif (is_array($config['virtualip']['vip'])) {
foreach ($config['virtualip']['vip'] as $carp) {
if ($carp['mode'] != "carp") {
continue;
}
$ipaddress = $carp['subnet'];
$password = $carp['password'];
$netmask = $carp['subnet_bits'];
$vhid = $carp['vhid'];
$advskew = $carp['advskew'];
$advbase = $carp['advbase'];
$status = get_carp_interface_status("{$carp['interface']}_vip{$carp['vhid']}");
echo "<tr>";
$align = "style=\"vertical-align:middle\"";
if ($carp_enabled == false) {
$icon = "<span {$align} class=\"glyphicon glyphicon-remove text-danger\" alt=\"disabled\" ></span>";
$status = "DISABLED";
} else {
if ($status == "MASTER") {
$icon = "<span {$align} class=\"glyphicon glyphicon-play text-success\" alt=\"master\" ></span>";
} elseif ($status == "BACKUP") {
$icon = "<span {$align} class=\"glyphicon glyphicon-play text-muted\" alt=\"backup\" ></span>";
} elseif ($status == "INIT") {
$icon = "<span {$align} class=\"glyphicon glyphicon-info-sign\" alt=\"init\" ></span>";
}
}
echo "<td class=\"listlr\" align=\"center\">" . convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$vhid} &nbsp;</td>";
echo "<td class=\"listlr\" align=\"center\">" . $ipaddress . "&nbsp;</td>";
echo "<td class=\"listlr\" align=\"center\">{$icon}&nbsp;&nbsp;" . $status . "&nbsp;</td>";
echo "</tr>";
}
}
?>
</table>
</div>
......@@ -199,15 +203,16 @@ include("head.inc");
<p class="vexpl">
<span class="red"><strong><?=gettext("Note"); ?>:</strong></span>
<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>
<?php
echo "<br />" . gettext("pfSync nodes") . ":<br />";
echo "<pre>";
system("/sbin/pfctl -vvss | /usr/bin/grep creator | /usr/bin/cut -d\" \" -f7 | /usr/bin/sort -u");
echo "</pre>";
?>
echo "<br />" . gettext("pfSync nodes") . ":<br />";
echo "<pre>";
system("/sbin/pfctl -vvss | /usr/bin/grep creator | /usr/bin/cut -d\" \" -f7 | /usr/bin/sort -u");
echo "</pre>";
?>
</div>
</div>
......
......@@ -33,33 +33,33 @@ require_once("captiveportal.inc");
function upload_crash_report($files, $agent)
{
global $g;
$post = array();
$counter = 0;
foreach($files as $filename) {
if (is_link($filename) || $filename == '/var/crash/minfree.gz' || $filename == '/var/crash/bounds.gz') {
continue;
}
$post["file{$counter}"] = curl_file_create($filename, "application/x-gzip", basename($filename));
$counter++;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://crash.opnsense.org/');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data;' ) );
$response = curl_exec($ch);
curl_close($ch);
return !$response;
global $g;
$post = array();
$counter = 0;
foreach ($files as $filename) {
if (is_link($filename) || $filename == '/var/crash/minfree.gz' || $filename == '/var/crash/bounds.gz') {
continue;
}
$post["file{$counter}"] = curl_file_create($filename, "application/x-gzip", basename($filename));
$counter++;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://crash.opnsense.org/');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data;' ));
$response = curl_exec($ch);
curl_close($ch);
return !$response;
}
$pgtitle = array(gettext('System'), gettext('Crash Reporter'));
......@@ -67,14 +67,14 @@ include('head.inc');
$last_version = '/usr/local/opnsense/version/opnsense.last';
$crash_report_header = sprintf(
"%s\n%s %s%s %s (%s)\nUUID %s\n",
php_uname('v'),
$g['product_name'],
trim(file_get_contents('/usr/local/opnsense/version/opnsense')),
file_exists($last_version) ? sprintf(' [%s]', trim(file_get_contents($last_version))) : '',
trim(shell_exec('/usr/local/bin/openssl version')),
php_uname('m'),
shell_exec('/sbin/sysctl -b kern.hostuuid')
"%s\n%s %s%s %s (%s)\nUUID %s\n",
php_uname('v'),
$g['product_name'],
trim(file_get_contents('/usr/local/opnsense/version/opnsense')),
file_exists($last_version) ? sprintf(' [%s]', trim(file_get_contents($last_version))) : '',
trim(shell_exec('/usr/local/bin/openssl version')),
php_uname('m'),
shell_exec('/sbin/sysctl -b kern.hostuuid')
);
$pkgver = explode('-', trim(file_get_contents('/usr/local/opnsense/version/opnsense')));
......@@ -83,53 +83,53 @@ $crash_reports = array();
$has_crashed = false;
if (isset($_POST['Submit'])) {
if ($_POST['Submit'] == 'yes') {
if (!is_dir('/var/crash')) {
mkdir('/var/crash', 0750, true);
}
$email = trim($_POST['Email']);
if (!empty($email)) {
$crash_report_header .= "Email {$email}\n";
}
$desc = trim($_POST['Desc']);
if (!empty($desc)) {
$crash_report_header .= "Description\n\n{$desc}";
}
file_put_contents('/var/crash/crashreport_header.txt', $crash_report_header);
@rename('/tmp/PHP_errors.log', '/var/crash/PHP_errors.log');
@copy('/var/run/dmesg.boot', '/var/crash/dmesg.boot');
exec('/usr/bin/gzip /var/crash/*');
$files_to_upload = glob('/var/crash/*');
$resp = upload_crash_report($files_to_upload, $user_agent);
array_map('unlink', $files_to_upload);
} elseif ($_POST['Submit'] == 'no') {
array_map('unlink', glob('/var/crash/*'));
@unlink('/tmp/PHP_errors.log');
} elseif ($_POST['Submit'] == 'new') {
/* force a crash report generation */
$has_crashed = true;
}
if ($_POST['Submit'] == 'yes') {
if (!is_dir('/var/crash')) {
mkdir('/var/crash', 0750, true);
}
$email = trim($_POST['Email']);
if (!empty($email)) {
$crash_report_header .= "Email {$email}\n";
}
$desc = trim($_POST['Desc']);
if (!empty($desc)) {
$crash_report_header .= "Description\n\n{$desc}";
}
file_put_contents('/var/crash/crashreport_header.txt', $crash_report_header);
@rename('/tmp/PHP_errors.log', '/var/crash/PHP_errors.log');
@copy('/var/run/dmesg.boot', '/var/crash/dmesg.boot');
exec('/usr/bin/gzip /var/crash/*');
$files_to_upload = glob('/var/crash/*');
$resp = upload_crash_report($files_to_upload, $user_agent);
array_map('unlink', $files_to_upload);
} elseif ($_POST['Submit'] == 'no') {
array_map('unlink', glob('/var/crash/*'));
@unlink('/tmp/PHP_errors.log');
} elseif ($_POST['Submit'] == 'new') {
/* force a crash report generation */
$has_crashed = true;
}
} else {
/* if there is no user activity probe for a crash report */
$has_crashed = get_crash_report(true) != '';
/* if there is no user activity probe for a crash report */
$has_crashed = get_crash_report(true) != '';
}
if ($has_crashed) {
$crash_files = glob("/var/crash/*");
$crash_reports['System Information'] = trim($crash_report_header);
$php_errors = @file_get_contents('/tmp/PHP_errors.log');
if (!empty($php_errors)) {
$crash_reports['PHP Errors'] = trim($php_errors);
}
$dmesg_boot = @file_get_contents('/var/run/dmesg.boot');
if (!empty($dmesg_boot)) {
$crash_reports['dmesg.boot'] = trim($dmesg_boot);
}
foreach ($crash_files as $cf) {
if (!is_link($cf) && $cf != '/var/crash/minfree' && $cf != '/var/crash/bounds' && filesize($cf) < 450000) {
$crash_reports[$cf] = trim(file_get_contents($cf));
}
}
$crash_files = glob("/var/crash/*");
$crash_reports['System Information'] = trim($crash_report_header);
$php_errors = @file_get_contents('/tmp/PHP_errors.log');
if (!empty($php_errors)) {
$crash_reports['PHP Errors'] = trim($php_errors);
}
$dmesg_boot = @file_get_contents('/var/run/dmesg.boot');
if (!empty($dmesg_boot)) {
$crash_reports['dmesg.boot'] = trim($dmesg_boot);
}
foreach ($crash_files as $cf) {
if (!is_link($cf) && $cf != '/var/crash/minfree' && $cf != '/var/crash/bounds' && filesize($cf) < 450000) {
$crash_reports[$cf] = trim(file_get_contents($cf));
}
}
}
?>
......@@ -149,29 +149,29 @@ if ($has_crashed) {
<?php
if ($has_crashed) {
echo "<br/><button name=\"Submit\" type=\"submit\" class=\"btn btn-default pull-right\" value=\"no\">" . gettext('Dismiss this report') . "</button>";
echo "<button name=\"Submit\" type=\"submit\" class=\"btn btn-primary pull-right\" style=\"margin-right: 8px;\" value=\"yes\">" . gettext('Submit this report') . "</button>";
echo "<p><strong>" . gettext("Unfortunately we have detected at least one programming bug.") . "</strong></p>";
echo "<p>" . gettext("Would you like to submit this crash report to the developers?") . "</p>";
echo "<hr><p>" . gettext("You can help us further by optionally adding your contact information and a problem description.") . "</p>";
echo "<p><input type=\"text\" placeholder=\"your@email.com\" name=\"Email\"></p>";
echo "<p><textarea rows=\"5\" placeholder=\"A short problem description or steps to reproduce.\" name=\"Desc\"></textarea></p>";
echo "<hr><p>" . gettext("Please double-check the following contents to ensure you are comfortable submitting the following information.") . "</p>";
foreach ($crash_reports as $report => $content) {
echo "<p>{$report}:<br/><pre>{$content}</pre></p>";
}
echo "<br/><button name=\"Submit\" type=\"submit\" class=\"btn btn-default pull-right\" value=\"no\">" . gettext('Dismiss this report') . "</button>";
echo "<button name=\"Submit\" type=\"submit\" class=\"btn btn-primary pull-right\" style=\"margin-right: 8px;\" value=\"yes\">" . gettext('Submit this report') . "</button>";
echo "<p><strong>" . gettext("Unfortunately we have detected at least one programming bug.") . "</strong></p>";
echo "<p>" . gettext("Would you like to submit this crash report to the developers?") . "</p>";
echo "<hr><p>" . gettext("You can help us further by optionally adding your contact information and a problem description.") . "</p>";
echo "<p><input type=\"text\" placeholder=\"your@email.com\" name=\"Email\"></p>";
echo "<p><textarea rows=\"5\" placeholder=\"A short problem description or steps to reproduce.\" name=\"Desc\"></textarea></p>";
echo "<hr><p>" . gettext("Please double-check the following contents to ensure you are comfortable submitting the following information.") . "</p>";
foreach ($crash_reports as $report => $content) {
echo "<p>{$report}:<br/><pre>{$content}</pre></p>";
}
} else {
$message = gettext('Luckily we have not detected a programming bug.');
if (isset($_POST['Submit'])) {
if ($_POST['Submit'] == 'yes') {
$message = gettext('Thank you for submitting this crash report.');
} elseif ($_POST['Submit'] == 'no') {
$message = gettext('Please consider submitting a crash report if the error persists.');
}
}
echo '<br/><button name="Submit" type="submit" class="btn btn-primary pull-right" value="new">' . gettext('Report an issue') . '</button>';
echo '<p><strong>' . $message . '</strong></p><br/>';
$message = gettext('Luckily we have not detected a programming bug.');
if (isset($_POST['Submit'])) {
if ($_POST['Submit'] == 'yes') {
$message = gettext('Thank you for submitting this crash report.');
} elseif ($_POST['Submit'] == 'no') {
$message = gettext('Please consider submitting a crash report if the error persists.');
}
}
echo '<br/><button name="Submit" type="submit" class="btn btn-primary pull-right" value="new">' . gettext('Report an issue') . '</button>';
echo '<p><strong>' . $message . '</strong></p><br/>';
}
?>
......
......@@ -137,7 +137,8 @@ $GLOBALS['csrf']['version'] = '1.0.4';
* Rewrites <form> on the fly to add CSRF tokens to them. This can also
* 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
// to check if the page is *actually* HTML. We don't begin rewriting until
// we hit the first <html tag.
......@@ -162,8 +163,8 @@ function csrf_ob_handler($buffer, $flags) {
$buffer = str_ireplace(
'</head>',
'<script type="text/javascript">'.
'var csrfMagicToken = "'.$tokens.'";'.
'var csrfMagicName = "'.$name.'";</script>'.
'var csrfMagicToken = "'.$tokens.'";'.
'var csrfMagicName = "'.$name.'";</script>'.
'<script src="'.$js.'" type="text/javascript"></script></head>',
$buffer
);
......@@ -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.
* @return True if check passes or is not necessary, false if failure.
*/
function csrf_check($fatal = true) {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') return true;
function csrf_check($fatal = true)
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return true;
}
csrf_start();
$name = $GLOBALS['csrf']['input-name'];
$ok = false;
$tokens = '';
do {
if (!isset($_POST[$name])) break;
if (!isset($_POST[$name])) {
break;
}
// we don't regenerate a token and check it because some token creation
// schemes are volatile.
$tokens = $_POST[$name];
if (!csrf_check_tokens($tokens)) break;
if (!csrf_check_tokens($tokens)) {
break;
}
$ok = true;
} while (false);
if ($fatal && !$ok) {
$callback = $GLOBALS['csrf']['callback'];
if (trim($tokens, 'A..Za..z0..9:;,') !== '') $tokens = 'hidden';
if (trim($tokens, 'A..Za..z0..9:;,') !== '') {
$tokens = 'hidden';
}
$callback($tokens);
exit;
}
......@@ -208,7 +218,8 @@ function csrf_check($fatal = true) {
* Retrieves a valid token(s) for a particular context. Tokens are separated
* by semicolons.
*/
function csrf_get_tokens() {
function csrf_get_tokens()
{
$has_cookies = !empty($_COOKIE);
// $ip implements a composite key, which is sent if the user hasn't sent
......@@ -224,15 +235,21 @@ function csrf_get_tokens() {
csrf_start();
// 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']) {
$val = csrf_generate_secret();
setcookie($GLOBALS['csrf']['cookie'], $val);
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
if (!$secret) return 'invalid';
if (!$secret) {
return 'invalid';
}
if ($GLOBALS['csrf']['user'] !== false) {
return 'user:' . csrf_hash($GLOBALS['csrf']['user']);
}
......@@ -242,17 +259,21 @@ function csrf_get_tokens() {
return 'invalid';
}
function csrf_flattenpost($data) {
function csrf_flattenpost($data)
{
$ret = array();
foreach($data as $n => $v) {
foreach ($data as $n => $v) {
$ret = array_merge($ret, csrf_flattenpost2(1, $n, $v));
}
return $ret;
}
function csrf_flattenpost2($level, $key, $data) {
if(!is_array($data)) return array($key => $data);
function csrf_flattenpost2($level, $key, $data)
{
if (!is_array($data)) {
return array($key => $data);
}
$ret = array();
foreach($data as $n => $v) {
foreach ($data as $n => $v) {
$nk = $level >= 1 ? $key."[$n]" : "[$n]";
$ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v));
}
......@@ -262,12 +283,15 @@ function csrf_flattenpost2($level, $key, $data) {
/**
* @param $tokens is safe for HTML consumption
*/
function csrf_callback($tokens) {
function csrf_callback($tokens)
{
// (yes, $tokens is safe to echo without escaping)
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
$data = '';
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).'" />';
}
echo "<html><head><title>CSRF check failed</title></head>
......@@ -283,10 +307,15 @@ function csrf_callback($tokens) {
* Checks if a composite token is valid. Outward facing code should use this
* instead of csrf_check_token()
*/
function csrf_check_tokens($tokens) {
if (is_string($tokens)) $tokens = explode(';', $tokens);
function csrf_check_tokens($tokens)
{
if (is_string($tokens)) {
$tokens = explode(';', $tokens);
}
foreach ($tokens as $token) {
if (csrf_check_token($token)) return true;
if (csrf_check_token($token)) {
return true;
}
}
return false;
}
......@@ -294,39 +323,64 @@ function csrf_check_tokens($tokens) {
/**
* Checks if a token is valid.
*/
function csrf_check_token($token) {
if (strpos($token, ':') === false) return false;
function csrf_check_token($token)
{
if (strpos($token, ':') === false) {
return false;
}
list($type, $value) = explode(':', $token, 2);
if (strpos($value, ',') === false) return false;
if (strpos($value, ',') === false) {
return false;
}
list($x, $time) = explode(',', $token, 2);
if ($GLOBALS['csrf']['expires']) {
if (time() > $time + $GLOBALS['csrf']['expires']) return false;
if (time() > $time + $GLOBALS['csrf']['expires']) {
return false;
}
}
switch ($type) {
case 'sid':
return $value === csrf_hash(session_id(), $time);
case 'cookie':
$n = $GLOBALS['csrf']['cookie'];
if (!$n) return false;
if (!isset($_COOKIE[$n])) return false;
if (!$n) {
return false;
}
if (!isset($_COOKIE[$n])) {
return false;
}
return $value === csrf_hash($_COOKIE[$n], $time);
case 'key':
if (!$GLOBALS['csrf']['key']) return false;
if (!$GLOBALS['csrf']['key']) {
return false;
}
return $value === csrf_hash($GLOBALS['csrf']['key'], $time);
// We could disable these 'weaker' checks if 'key' was set, but
// that doesn't make me feel good then about the cookie-based
// implementation.
case 'user':
if (!csrf_get_secret()) return false;
if ($GLOBALS['csrf']['user'] === false) return false;
if (!csrf_get_secret()) {
return false;
}
if ($GLOBALS['csrf']['user'] === false) {
return false;
}
return $value === csrf_hash($GLOBALS['csrf']['user'], $time);
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
// the browser sent cookies
if ($GLOBALS['csrf']['user'] !== false) return false;
if (!empty($_COOKIE)) return false;
if (!$GLOBALS['csrf']['allow-ip']) return false;
if ($GLOBALS['csrf']['user'] !== false) {
return false;
}
if (!empty($_COOKIE)) {
return false;
}
if (!$GLOBALS['csrf']['allow-ip']) {
return false;
}
return $value === csrf_hash($_SERVER['IP_ADDRESS'], $time);
}
return false;
......@@ -335,7 +389,8 @@ function csrf_check_token($token) {
/**
* Sets a configuration value.
*/
function csrf_conf($key, $val) {
function csrf_conf($key, $val)
{
if (!isset($GLOBALS['csrf'][$key])) {
trigger_error('No such configuration ' . $key, E_USER_WARNING);
return;
......@@ -346,7 +401,8 @@ function csrf_conf($key, $val) {
/**
* Starts a session if we're allowed to.
*/
function csrf_start() {
function csrf_start()
{
if ($GLOBALS['csrf']['auto-session'] && session_status() == PHP_SESSION_NONE) {
session_start();
}
......@@ -355,8 +411,11 @@ function csrf_start() {
/**
* Retrieves the secret, and generates one if necessary.
*/
function csrf_get_secret() {
if ($GLOBALS['csrf']['secret']) return $GLOBALS['csrf']['secret'];
function csrf_get_secret()
{
if ($GLOBALS['csrf']['secret']) {
return $GLOBALS['csrf']['secret'];
}
$dir = dirname(__FILE__);
$file = $dir . '/csrf-secret.php';
$secret = '';
......@@ -377,7 +436,8 @@ function csrf_get_secret() {
/**
* 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 = '';
for ($i = 0; $i < 32; $i++) {
$r .= chr(mt_rand(0, 255));
......@@ -390,14 +450,23 @@ function csrf_generate_secret($len = 32) {
* Generates a hash/expiry double. If time isn't set it will be calculated
* from the current time.
*/
function csrf_hash($value, $time = null) {
if (!$time) $time = time();
function csrf_hash($value, $time = null)
{
if (!$time) {
$time = time();
}
return sha1(csrf_get_secret() . $value . $time) . ',' . $time;
}
// Load user configuration
if (function_exists('csrf_startup')) csrf_startup();
if (function_exists('csrf_startup')) {
csrf_startup();
}
// Initialize our handler
if ($GLOBALS['csrf']['rewrite']) ob_start('csrf_ob_handler');
if ($GLOBALS['csrf']['rewrite']) {
ob_start('csrf_ob_handler');
}
// 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