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"); ...@@ -31,23 +31,23 @@ 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; {
if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) { global $config;
unset($config["virtualip_carp_maintenancemode"]); if (isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == false) {
write_config("Leave CARP maintenance mode"); unset($config["virtualip_carp_maintenancemode"]);
} else write_config("Leave CARP maintenance mode");
if (!isset($config["virtualip_carp_maintenancemode"]) && $carp_maintenancemode == true) { } elseif (!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");
} }
$viparr = &$config['virtualip']['vip']; $viparr = &$config['virtualip']['vip'];
foreach ($viparr as $vip) { foreach ($viparr as $vip) {
if ($vip['mode'] == "carp") { if ($vip['mode'] == "carp") {
interface_carp_configure($vip); interface_carp_configure($vip);
} }
} }
} }
...@@ -56,40 +56,40 @@ unset($carp_interface_count_cache); ...@@ -56,40 +56,40 @@ 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']) {
case "carp": case "carp":
interface_vip_bring_down($vip); interface_vip_bring_down($vip);
sleep(1); sleep(1);
break; break;
} }
} }
} }
$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']) {
case "carp": case "carp":
interface_carp_configure($vip); interface_carp_configure($vip);
sleep(1); sleep(1);
break; break;
} }
} }
} }
interfaces_carp_setup(); interfaces_carp_setup();
set_single_sysctl('net.inet.carp.allow', '1'); set_single_sysctl('net.inet.carp.allow', '1');
} }
} }
$status = get_carp_status(); $status = get_carp_status();
...@@ -111,39 +111,43 @@ include("head.inc"); ...@@ -111,39 +111,43 @@ 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">
<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") . "\" />";
} }
} }
?> ?>
<div class="table-responsive"> <div class="table-responsive">
...@@ -154,43 +158,43 @@ include("head.inc"); ...@@ -154,43 +158,43 @@ include("head.inc");
<td class="listhdrr" align="center"><?=gettext("Status"); ?></td> <td class="listhdrr" align="center"><?=gettext("Status"); ?></td>
</tr> </tr>
<?php <?php
if ($carpcount == 0) { if ($carpcount == 0) {
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'];
$vhid = $carp['vhid']; $vhid = $carp['vhid'];
$advskew = $carp['advskew']; $advskew = $carp['advskew'];
$advbase = $carp['advbase']; $advbase = $carp['advbase'];
$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>";
} }
} }
echo "<td class=\"listlr\" align=\"center\">" . convert_friendly_interface_to_friendly_descr($carp['interface']) . "@{$vhid} &nbsp;</td>"; 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\">" . $ipaddress . "&nbsp;</td>";
echo "<td class=\"listlr\" align=\"center\">{$icon}&nbsp;&nbsp;" . $status . "&nbsp;</td>"; echo "<td class=\"listlr\" align=\"center\">{$icon}&nbsp;&nbsp;" . $status . "&nbsp;</td>";
echo "</tr>"; echo "</tr>";
} }
} }
?> ?>
</table> </table>
</div> </div>
...@@ -199,15 +203,16 @@ include("head.inc"); ...@@ -199,15 +203,16 @@ 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
echo "<br />" . gettext("pfSync nodes") . ":<br />"; echo "<br />" . gettext("pfSync nodes") . ":<br />";
echo "<pre>"; echo "<pre>";
system("/sbin/pfctl -vvss | /usr/bin/grep creator | /usr/bin/cut -d\" \" -f7 | /usr/bin/sort -u"); system("/sbin/pfctl -vvss | /usr/bin/grep creator | /usr/bin/cut -d\" \" -f7 | /usr/bin/sort -u");
echo "</pre>"; echo "</pre>";
?> ?>
</div> </div>
</div> </div>
......
...@@ -33,33 +33,33 @@ require_once("captiveportal.inc"); ...@@ -33,33 +33,33 @@ require_once("captiveportal.inc");
function upload_crash_report($files, $agent) function upload_crash_report($files, $agent)
{ {
global $g; global $g;
$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;
} }
$post["file{$counter}"] = curl_file_create($filename, "application/x-gzip", basename($filename)); $post["file{$counter}"] = curl_file_create($filename, "application/x-gzip", basename($filename));
$counter++; $counter++;
} }
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://crash.opnsense.org/'); curl_setopt($ch, CURLOPT_URL, 'https://crash.opnsense.org/');
curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, false); curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_USERAGENT, $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);
return !$response; return !$response;
} }
$pgtitle = array(gettext('System'), gettext('Crash Reporter')); $pgtitle = array(gettext('System'), gettext('Crash Reporter'));
...@@ -67,14 +67,14 @@ include('head.inc'); ...@@ -67,14 +67,14 @@ include('head.inc');
$last_version = '/usr/local/opnsense/version/opnsense.last'; $last_version = '/usr/local/opnsense/version/opnsense.last';
$crash_report_header = sprintf( $crash_report_header = sprintf(
"%s\n%s %s%s %s (%s)\nUUID %s\n", "%s\n%s %s%s %s (%s)\nUUID %s\n",
php_uname('v'), php_uname('v'),
$g['product_name'], $g['product_name'],
trim(file_get_contents('/usr/local/opnsense/version/opnsense')), trim(file_get_contents('/usr/local/opnsense/version/opnsense')),
file_exists($last_version) ? sprintf(' [%s]', trim(file_get_contents($last_version))) : '', file_exists($last_version) ? sprintf(' [%s]', trim(file_get_contents($last_version))) : '',
trim(shell_exec('/usr/local/bin/openssl version')), trim(shell_exec('/usr/local/bin/openssl version')),
php_uname('m'), php_uname('m'),
shell_exec('/sbin/sysctl -b kern.hostuuid') shell_exec('/sbin/sysctl -b kern.hostuuid')
); );
$pkgver = explode('-', trim(file_get_contents('/usr/local/opnsense/version/opnsense'))); $pkgver = explode('-', trim(file_get_contents('/usr/local/opnsense/version/opnsense')));
...@@ -83,53 +83,53 @@ $crash_reports = array(); ...@@ -83,53 +83,53 @@ $crash_reports = array();
$has_crashed = false; $has_crashed = false;
if (isset($_POST['Submit'])) { if (isset($_POST['Submit'])) {
if ($_POST['Submit'] == 'yes') { if ($_POST['Submit'] == 'yes') {
if (!is_dir('/var/crash')) { if (!is_dir('/var/crash')) {
mkdir('/var/crash', 0750, true); mkdir('/var/crash', 0750, true);
} }
$email = trim($_POST['Email']); $email = trim($_POST['Email']);
if (!empty($email)) { if (!empty($email)) {
$crash_report_header .= "Email {$email}\n"; $crash_report_header .= "Email {$email}\n";
} }
$desc = trim($_POST['Desc']); $desc = trim($_POST['Desc']);
if (!empty($desc)) { if (!empty($desc)) {
$crash_report_header .= "Description\n\n{$desc}"; $crash_report_header .= "Description\n\n{$desc}";
} }
file_put_contents('/var/crash/crashreport_header.txt', $crash_report_header); file_put_contents('/var/crash/crashreport_header.txt', $crash_report_header);
@rename('/tmp/PHP_errors.log', '/var/crash/PHP_errors.log'); @rename('/tmp/PHP_errors.log', '/var/crash/PHP_errors.log');
@copy('/var/run/dmesg.boot', '/var/crash/dmesg.boot'); @copy('/var/run/dmesg.boot', '/var/crash/dmesg.boot');
exec('/usr/bin/gzip /var/crash/*'); exec('/usr/bin/gzip /var/crash/*');
$files_to_upload = glob('/var/crash/*'); $files_to_upload = glob('/var/crash/*');
$resp = upload_crash_report($files_to_upload, $user_agent); $resp = upload_crash_report($files_to_upload, $user_agent);
array_map('unlink', $files_to_upload); array_map('unlink', $files_to_upload);
} elseif ($_POST['Submit'] == 'no') { } elseif ($_POST['Submit'] == 'no') {
array_map('unlink', glob('/var/crash/*')); array_map('unlink', glob('/var/crash/*'));
@unlink('/tmp/PHP_errors.log'); @unlink('/tmp/PHP_errors.log');
} elseif ($_POST['Submit'] == 'new') { } elseif ($_POST['Submit'] == 'new') {
/* force a crash report generation */ /* force a crash report generation */
$has_crashed = true; $has_crashed = true;
} }
} else { } else {
/* if there is no user activity probe for a crash report */ /* if there is no user activity probe for a crash report */
$has_crashed = get_crash_report(true) != ''; $has_crashed = get_crash_report(true) != '';
} }
if ($has_crashed) { if ($has_crashed) {
$crash_files = glob("/var/crash/*"); $crash_files = glob("/var/crash/*");
$crash_reports['System Information'] = trim($crash_report_header); $crash_reports['System Information'] = trim($crash_report_header);
$php_errors = @file_get_contents('/tmp/PHP_errors.log'); $php_errors = @file_get_contents('/tmp/PHP_errors.log');
if (!empty($php_errors)) { if (!empty($php_errors)) {
$crash_reports['PHP Errors'] = trim($php_errors); $crash_reports['PHP Errors'] = trim($php_errors);
} }
$dmesg_boot = @file_get_contents('/var/run/dmesg.boot'); $dmesg_boot = @file_get_contents('/var/run/dmesg.boot');
if (!empty($dmesg_boot)) { if (!empty($dmesg_boot)) {
$crash_reports['dmesg.boot'] = trim($dmesg_boot); $crash_reports['dmesg.boot'] = trim($dmesg_boot);
} }
foreach ($crash_files as $cf) { foreach ($crash_files as $cf) {
if (!is_link($cf) && $cf != '/var/crash/minfree' && $cf != '/var/crash/bounds' && filesize($cf) < 450000) { if (!is_link($cf) && $cf != '/var/crash/minfree' && $cf != '/var/crash/bounds' && filesize($cf) < 450000) {
$crash_reports[$cf] = trim(file_get_contents($cf)); $crash_reports[$cf] = trim(file_get_contents($cf));
} }
} }
} }
?> ?>
...@@ -149,29 +149,29 @@ if ($has_crashed) { ...@@ -149,29 +149,29 @@ if ($has_crashed) {
<?php <?php
if ($has_crashed) { if ($has_crashed) {
echo "<br/><button name=\"Submit\" type=\"submit\" class=\"btn btn-default pull-right\" value=\"no\">" . gettext('Dismiss this report') . "</button>"; 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 "<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><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 "<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 "<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><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 "<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>"; 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) { foreach ($crash_reports as $report => $content) {
echo "<p>{$report}:<br/><pre>{$content}</pre></p>"; echo "<p>{$report}:<br/><pre>{$content}</pre></p>";
} }
} else { } else {
$message = gettext('Luckily we have not detected a programming bug.'); $message = gettext('Luckily we have not detected a programming bug.');
if (isset($_POST['Submit'])) { if (isset($_POST['Submit'])) {
if ($_POST['Submit'] == 'yes') { if ($_POST['Submit'] == 'yes') {
$message = gettext('Thank you for submitting this crash report.'); $message = gettext('Thank you for submitting this crash report.');
} elseif ($_POST['Submit'] == 'no') { } elseif ($_POST['Submit'] == 'no') {
$message = gettext('Please consider submitting a crash report if the error persists.'); $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 '<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/>'; echo '<p><strong>' . $message . '</strong></p><br/>';
} }
?> ?>
......
...@@ -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.
...@@ -162,8 +163,8 @@ function csrf_ob_handler($buffer, $flags) { ...@@ -162,8 +163,8 @@ function csrf_ob_handler($buffer, $flags) {
$buffer = str_ireplace( $buffer = str_ireplace(
'</head>', '</head>',
'<script type="text/javascript">'. '<script type="text/javascript">'.
'var csrfMagicToken = "'.$tokens.'";'. 'var csrfMagicToken = "'.$tokens.'";'.
'var csrfMagicName = "'.$name.'";</script>'. 'var csrfMagicName = "'.$name.'";</script>'.
'<script src="'.$js.'" type="text/javascript"></script></head>', '<script src="'.$js.'" type="text/javascript"></script></head>',
$buffer $buffer
); );
...@@ -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