Merge pull request #356 from glaszig/security/always-verify-csrf-token

always verify csrf token for resource-modifying requests
This commit is contained in:
Bill Zimmerman 2019-08-07 21:53:39 +02:00 committed by GitHub
commit f6f85d1c11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 223 additions and 171 deletions

View File

@ -1,8 +1,10 @@
<?php
require('includes/csrf.php');
require_once '../../includes/config.php';
require_once RASPI_CONFIG.'/raspap.php';
session_start();
header('X-Frame-Options: DENY');
header("Content-Security-Policy: default-src 'none'; connect-src 'self'");
require_once '../../includes/authenticate.php';

View File

@ -1,4 +1,7 @@
<?php
require('includes/csrf.php');
if (filter_input(INPUT_GET, 'tu') == 'h') {
header('X-Content-Type-Options: nosniff');

View File

@ -1,9 +1,11 @@
<?php
session_start();
require('includes/csrf.php');
include_once('../../includes/config.php');
include_once('../../includes/functions.php');
if(isset($_POST['generate']) && isset($_POST['csrf_token']) && CSRFValidate()) {
if(isset($_POST['generate'])) {
$cnfNetworking = array_diff(scandir(RASPI_CONFIG_NETWORKING, 1),array('..','.','dhcpcd.conf'));
$cnfNetworking = array_combine($cnfNetworking,$cnfNetworking);
$strConfFile = "";

View File

@ -1,4 +1,7 @@
<?php
require('includes/csrf.php');
exec("ls /sys/class/net | grep -v lo", $interfaces);
echo json_encode($interfaces);
?>

View File

@ -1,10 +1,12 @@
<?php
session_start();
require('includes/csrf.php');
include_once('../../includes/config.php');
include_once('../../includes/functions.php');
if(isset($_POST['interface']) && isset($_POST['csrf_token']) && CSRFValidate()) {
if(isset($_POST['interface'])) {
$int = preg_replace('/[^a-z0-9]/', '', $_POST['interface']);
if(!file_exists(RASPI_CONFIG_NETWORKING.'/'.$int.'.ini')) {
touch(RASPI_CONFIG_NETWORKING.'/'.$int.'.ini');

View File

@ -1,8 +1,10 @@
<?php
session_start();
require('includes/csrf.php');
include_once('../../includes/functions.php');
if(isset($_POST['interface']) && isset($_POST['csrf_token']) && CSRFValidate()) {
if(isset($_POST['interface'])) {
$int = preg_replace('/[^a-z0-9]/','',$_POST['interface']);
exec('ip a s '.$int,$intOutput,$intResult);
$intOutput = array_map('htmlentities', $intOutput);

View File

@ -1,8 +1,10 @@
<?php
session_start();
require('includes/csrf.php');
include_once('../../includes/config.php');
include_once('../../includes/functions.php');
if(isset($_POST['interface']) && isset($_POST['csrf_token']) && CSRFValidate()) {
if(isset($_POST['interface'])) {
$int = $_POST['interface'];
$cfg = [];
$file = $int.".ini";

View File

@ -6,7 +6,6 @@ function DisplayAuthConfig($username, $password)
{
$status = new StatusMessages();
if (isset($_POST['UpdateAdminPassword'])) {
if (CSRFValidate()) {
if (password_verify($_POST['oldpass'], $password)) {
$new_username=trim($_POST['username']);
if ($_POST['newpass'] !== $_POST['newpassagain']) {
@ -32,9 +31,6 @@ function DisplayAuthConfig($username, $password)
} else {
$status->addMessage('Old password does not match', 'danger');
}
} else {
error_log('CSRF violation');
}
}
?>
<div class="row">
@ -44,7 +40,7 @@ function DisplayAuthConfig($username, $password)
<div class="panel-body">
<p><?php $status->showMessages(); ?></p>
<form role="form" action="?page=auth_conf" method="POST">
<?php CSRFToken() ?>
<?php echo CSRFTokenFieldTag() ?>
<div class="row">
<div class="form-group col-md-4">
<label for="username"><?php echo _("Username"); ?></label>

View File

@ -53,7 +53,7 @@ function DisplayWPAConfig()
if (isset($_POST['connect'])) {
$result = 0;
exec('sudo wpa_cli -i ' . RASPI_WPA_CTRL_INTERFACE . ' select_network '.strval($_POST['connect']));
} elseif (isset($_POST['client_settings']) && CSRFValidate()) {
} elseif (isset($_POST['client_settings'])) {
$tmp_networks = $networks;
if ($wpa_file = fopen('/tmp/wifidata', 'w')) {
fwrite($wpa_file, 'ctrl_interface=DIR=' . RASPI_WPA_CTRL_INTERFACE . ' GROUP=netdev' . PHP_EOL);
@ -182,7 +182,7 @@ function DisplayWPAConfig()
</div>
<form method="POST" action="?page=wpa_conf" name="wpa_conf_form">
<?php CSRFToken() ?>
<?php echo CSRFTokenFieldTag() ?>
<input type="hidden" name="client_settings" ?>
<script>
function showPassword(index) {

11
includes/csrf.php Normal file
View File

@ -0,0 +1,11 @@
<?php
include_once('includes/functions.php');
include_once('includes/session.php');
if (csrfValidateRequest() && !CSRFValidate()) {
handleInvalidCSRFToken();
}
ensureCSRFSessionToken();
header('X-CSRF-Token', $_SESSION['csrf_token']);

View File

@ -12,7 +12,6 @@ function DisplayDHCPConfig()
$status = new StatusMessages();
if (isset($_POST['savedhcpdsettings'])) {
if (CSRFValidate()) {
$errors = '';
define('IFNAMSIZ', 16);
if (!preg_match('/^[a-zA-Z0-9]+$/', $_POST['interface']) ||
@ -68,16 +67,12 @@ function DisplayDHCPConfig()
} else {
$status->addMessage('Dnsmasq configuration failed to be updated.', 'danger');
}
} else {
error_log('CSRF violation');
}
}
exec('pidof dnsmasq | wc -l', $dnsmasq);
$dnsmasq_state = ($dnsmasq[0] > 0);
if (isset($_POST['startdhcpd'])) {
if (CSRFValidate()) {
if ($dnsmasq_state) {
$status->addMessage('dnsmasq already running', 'info');
} else {
@ -89,11 +84,7 @@ function DisplayDHCPConfig()
$status->addMessage('Failed to start dnsmasq', 'danger');
}
}
} else {
error_log('CSRF violation');
}
} elseif (isset($_POST['stopdhcpd'])) {
if (CSRFValidate()) {
if ($dnsmasq_state) {
exec('sudo /etc/init.d/dnsmasq stop', $dnsmasq, $return);
if ($return == 0) {
@ -105,9 +96,6 @@ function DisplayDHCPConfig()
} else {
$status->addMessage('dnsmasq already stopped', 'info');
}
} else {
error_log('CSRF violation');
}
} else {
if ($dnsmasq_state) {
$status->addMessage('Dnsmasq is running', 'success');

View File

@ -54,17 +54,32 @@ function safefilerewrite($fileName, $dataToSave)
}
}
/**
* Saves a CSRF token in the session
*/
function ensureCSRFSessionToken()
{
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
/**
*
* Add CSRF Token to form
*
*/
function CSRFToken()
function CSRFTokenFieldTag()
{
?>
<input id="csrf_token" type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES);
; ?>" />
<?php
$token = htmlspecialchars($_SESSION['csrf_token']);
return '<input type="hidden" name="csrf_token" value="' . $token . '">';
}
/**
* Retuns a CSRF meta tag (for use with xhr, for example)
*/
function CSRFMetaTag()
{
$token = htmlspecialchars($_SESSION['csrf_token']);
return '<meta name="csrf_token" content="' . $token . '">';
}
/**
@ -74,7 +89,19 @@ function CSRFToken()
*/
function CSRFValidate()
{
if (hash_equals($_POST['csrf_token'], $_SESSION['csrf_token'])) {
$post_token = $_POST['csrf_token'];
$header_token = $_SERVER['HTTP_X_CSRF_TOKEN'];
if (empty($post_token) && empty($header_token)) {
return false;
}
$request_token = $post_token;
if (empty($post_token)) {
$request_token = $header_token;
}
if (hash_equals($_SESSION['csrf_token'], $request_token)) {
return true;
} else {
error_log('CSRF violation');
@ -82,6 +109,26 @@ function CSRFValidate()
}
}
/**
* Should the request be CSRF-validated?
*/
function csrfValidateRequest()
{
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
return in_array($request_method, [ "post", "put", "patch", "delete" ]);
}
/**
* Handle invalid CSRF
*/
function handleInvalidCSRFToken()
{
header('HTTP/1.1 500 Internal Server Error');
header('Content-Type: text/plain');
echo 'Invalid CSRF token';
exit;
}
/**
* Test whether array is associative
*/

View File

@ -22,13 +22,8 @@ function DisplayHostAPDConfig()
exec("ip -o link show | awk -F': ' '{print $2}'", $interfaces);
if (isset($_POST['SaveHostAPDSettings'])) {
if (CSRFValidate()) {
SaveHostAPDConfig($arrSecurity, $arrEncType, $arr80211Standard, $interfaces, $status);
} else {
error_log('CSRF violation');
}
} elseif (isset($_POST['StartHotspot'])) {
if (CSRFValidate()) {
$status->addMessage('Attempting to start hotspot', 'info');
if ($arrHostapdConf['WifiAPEnable'] == 1) {
exec('sudo /etc/raspap/hostapd/servicestart.sh --interface uap0 --seconds 3', $return);
@ -38,19 +33,12 @@ function DisplayHostAPDConfig()
foreach ($return as $line) {
$status->addMessage($line, 'info');
}
} else {
error_log('CSRF violation');
}
} elseif (isset($_POST['StopHotspot'])) {
if (CSRFValidate()) {
$status->addMessage('Attempting to stop hotspot', 'info');
exec('sudo /etc/init.d/hostapd stop', $return);
foreach ($return as $line) {
$status->addMessage($line, 'info');
}
} else {
error_log('CSRF violation');
}
}
exec('cat '. RASPI_HOSTAPD_CONFIG, $hostapdconfig);
@ -95,7 +83,7 @@ function DisplayHostAPDConfig()
<div class="tab-pane fade in active" id="basic">
<h4><?php echo _("Basic settings") ;?></h4>
<?php CSRFToken() ?>
<?php echo CSRFTokenFieldTag() ?>
<div class="row">
<div class="form-group col-md-4">
<label for="cbxinterface"><?php echo _("Interface") ;?></label>

View File

@ -16,8 +16,6 @@ function DisplayNetworkingConfig()
foreach ($interfaces as $interface) {
exec("ip a show $interface", $$interface);
}
CSRFToken();
?>
<div class="row">

5
includes/session.php Normal file
View File

@ -0,0 +1,5 @@
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}

View File

@ -63,14 +63,10 @@ function DisplaySystem()
$status = new StatusMessages();
if (isset($_POST['SaveLanguage'])) {
if (CSRFValidate()) {
if (isset($_POST['locale'])) {
$_SESSION['locale'] = $_POST['locale'];
$status->addMessage('Language setting saved', 'success');
}
} else {
error_log('CSRF violation');
}
}
// define locales
@ -204,7 +200,7 @@ if (isset($_POST['system_shutdown'])) {
<div role="tabpanel" class="tab-pane" id="language">
<h4><?php echo _("Language settings") ;?></h4>
<?php CSRFToken() ?>
<?php echo CSRFTokenFieldTag() ?>
<div class="row">
<div class="form-group col-md-4">
<label for="code"><?php echo _("Select a language"); ?></label>

View File

@ -18,7 +18,7 @@
* @see http://sirlagz.net/2013/02/08/raspap-webgui/
*/
session_start();
require('includes/csrf.php');
include_once('includes/config.php');
include_once(RASPI_CONFIG.'/raspap.php');
@ -39,15 +39,6 @@ include_once('includes/about.php');
$output = $return = 0;
$page = $_GET['page'];
if (empty($_SESSION['csrf_token'])) {
if (function_exists('mcrypt_create_iv')) {
$_SESSION['csrf_token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} else {
$_SESSION['csrf_token'] = bin2hex(openssl_random_pseudo_bytes(32));
}
}
$csrf_token = $_SESSION['csrf_token'];
if (!isset($_COOKIE['theme'])) {
$theme = "custom.css";
} else {
@ -60,6 +51,7 @@ $theme_url = 'dist/css/'.htmlspecialchars($theme, ENT_QUOTES);
<html lang="en">
<head>
<meta charset="utf-8">
<?php echo CSRFMetaTag() ?>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">

View File

@ -19,7 +19,7 @@ function createNetmaskAddr(bitCount) {
}
function loadSummary(strInterface) {
$.post('/ajax/networking/get_ip_summary.php',{interface:strInterface,csrf_token:csrf},function(data){
$.post('/ajax/networking/get_ip_summary.php',{interface:strInterface},function(data){
jsonData = JSON.parse(data);
console.log(jsonData);
if(jsonData['return'] == 0) {
@ -50,7 +50,7 @@ function setupTabs() {
}
function loadCurrentSettings(strInterface) {
$.post('/ajax/networking/get_int_config.php',{interface:strInterface,csrf_token:csrf},function(data){
$.post('/ajax/networking/get_int_config.php',{interface:strInterface},function(data){
jsonData = JSON.parse(data);
$.each(jsonData['output'],function(i,v) {
var int = v['interface'];
@ -102,7 +102,6 @@ function saveNetworkSettings(int) {
}
});
arrFormData['interface'] = int;
arrFormData['csrf_token'] = csrf;
$.post('/ajax/networking/save_int_config.php',arrFormData,function(data){
//console.log(data);
var jsonData = JSON.parse(data);
@ -113,7 +112,6 @@ function saveNetworkSettings(int) {
function applyNetworkSettings() {
var int = $(this).data('int');
arrFormData = {};
arrFormData['csrf_token'] = csrf;
arrFormData['generate'] = '';
$.post('/ajax/networking/gen_int_config.php',arrFormData,function(data){
console.log(data);
@ -162,8 +160,22 @@ function setupBtns() {
});
}
$().ready(function(){
csrf = $('#csrf_token').val();
function setCSRFTokenHeader(event, xhr, settings) {
var csrfToken = $('meta[name=csrf_token]').attr('content');
if (/^(POST|PATCH|PUT|DELETE)$/i.test(settings.type)) {
xhr.setRequestHeader("X-CSRF-Token", csrfToken);
}
}
function updateCSRFTokens(event, xhr, settings) {
var newToken = xhr.getResponseHeader("X-CSRF-Token");
if (newToken) {
$('meta[name=csrf_token]').attr('content', newToken);
$('[name=csrf_token]:input').attr('value', newToken);
}
}
function contentLoaded() {
pageCurrent = window.location.href.split("?")[1].split("=")[1];
pageCurrent = pageCurrent.replace("#","");
$('#side-menu').metisMenu();
@ -174,6 +186,9 @@ $().ready(function(){
setupBtns();
break;
}
});
}
$(document)
.ajaxSend(setCSRFTokenHeader)
.ajaxComplete(updateCSRFTokens)
.ready(contentLoaded);