Commit 6e39c38c authored by Ad Schellevis's avatar Ad Schellevis Committed by Franco Fichtner

replace csrf with phalcon's implementation

PR: https://github.com/opnsense/core/issues/918
(cherry picked from commit 21be9faf)
parent 3c679d25
...@@ -921,8 +921,7 @@ ...@@ -921,8 +921,7 @@
/usr/local/wizard/setup.xml /usr/local/wizard/setup.xml
/usr/local/www/carp_status.php /usr/local/www/carp_status.php
/usr/local/www/crash_reporter.php /usr/local/www/crash_reporter.php
/usr/local/www/csrf/csrf-magic.js /usr/local/www/csrf.inc
/usr/local/www/csrf/csrf-magic.php
/usr/local/www/diag_authentication.php /usr/local/www/diag_authentication.php
/usr/local/www/diag_backup.php /usr/local/www/diag_backup.php
/usr/local/www/diag_confbak.php /usr/local/www/diag_confbak.php
......
...@@ -919,7 +919,6 @@ function system_webgui_configure($verbose = false) ...@@ -919,7 +919,6 @@ function system_webgui_configure($verbose = false)
} }
chdir('/usr/local/www'); chdir('/usr/local/www');
@unlink('/usr/local/www/csrf/csrf-secret.php');
/* defaults */ /* defaults */
$portarg = "80"; $portarg = "80";
......
<?php
/*
Copyright (C) 2017 Deciso B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
class LegacyCSRF
{
private $securityToken = null;
private $securityTokenKey = null;
private $di = null;
private $security = null;
private $session = null;
private $is_html_output = false;
public function __construct()
{
$this->di = new \Phalcon\DI\FactoryDefault();
$this->security = new Phalcon\Security();
$this->security->setDi($this->di);
// register rewrite handler
ob_start(array($this,'csrfRewriteHandler'), 5242880);
}
private function Session()
{
if ($this->session == null) {
$this->session = new Phalcon\Session\Adapter\Files();
$this->session->start();
$secure = $config['system']['webgui']['protocol'] == 'https';
setcookie(session_name(), session_id(), null, '/', null, $secure, true);
$this->di->setShared('session', $this->session);
}
}
public function checkToken()
{
$result = false; // default, not valid
$this->Session();
// do not destroy token after successfull validation, some pages use ajax type requests
$this->securityTokenKey = $_SESSION['$PHALCON/CSRF/KEY$'];
$this->securityToken = !empty($_POST[$this->securityTokenKey]) ? $_POST[$this->securityTokenKey] : "";
if (empty($this->securityToken)) {
if (!empty($_SERVER['HTTP_X_CSRFTOKEN'])) {
$this->securityToken = $_SERVER['HTTP_X_CSRFTOKEN'];
$result = $this->security->checkToken(null, $this->securityToken, false);
}
} else {
$result = $this->security->checkToken($this->securityTokenKey, $this->securityToken, false);
}
// close session after validation
session_write_close();
return $result;
}
private function newToken()
{
$this->Session();
// only request new token when checkToken() hasn't saved one
if ($this->securityToken == null) {
$this->securityToken = $this->security->getToken();
$this->securityTokenKey = $this->security->getTokenKey();
}
return array('token'=>$this->securityToken, 'key' => $this->securityTokenKey);
}
public function csrfRewriteHandler($buffer)
{
// quick check if output looks like html, don't rewrite other document types
if (stripos($buffer, '<html') !== false) {
$this->is_html_output = true;
}
if ($this->is_html_output) {
$csrf = $this->newToken();
$inputtag = "<input type=\"hidden\" id=\"__opnsense_csrf\" name=\"{$csrf['key']}\" value=\"{$csrf['token']}\"\/>";
$buffer = preg_replace('#(<form[^>]*method\s*=\s*["\']post["\'][^>]*>)#i', '$1' . $inputtag, $buffer);
// csrf token for Ajax type requests
$script = "
<script type=\"text/javascript\">
$( document ).ready(function() {
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.setRequestHeader(\"X-CSRFToken\", \"{$csrf['token']}\" );
}
});
});
</script>
";
$buffer = str_ireplace('</head>', '</head>'.$script, $buffer);
}
return $buffer;
}
}
$LegacyCSRFObject = new LegacyCSRF();
if ($_SERVER['REQUEST_METHOD'] !== 'GET' && !$LegacyCSRFObject->checkToken()) {
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
echo "<html><head><title>CSRF check failed</title></head>
<body>
<p>CSRF check failed. Your form session may have expired, or you may not have
cookies enabled.</p>
</body></html>
";
die;
}
/**
* @file
*
* Rewrites XMLHttpRequest to automatically send CSRF token with it. In theory
* plays nice with other JavaScript libraries, needs testing though.
*/
// Here are the basic overloaded method definitions
// The wrapper must be set BEFORE onreadystatechange is written to, since
// a bug in ActiveXObject prevents us from properly testing for it.
CsrfMagic = function(real) {
// try to make it ourselves, if you didn't pass it
if (!real) try { real = new XMLHttpRequest; } 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;
// properties
var csrfMagic = this;
real.onreadystatechange = function() {
csrfMagic._updateProps();
return csrfMagic.onreadystatechange ? csrfMagic.onreadystatechange() : null;
};
csrfMagic._updateProps();
}
CsrfMagic.prototype = {
open: function(method, url, async, username, password) {
if (method == 'POST') this.csrf_isPost = true;
// deal with Opera bug, thanks jQuery
if (username) 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) {
if (username) return this.csrf.open(method, url, async, username, password);
else return this.csrf.open(method, url, async);
},
send: function(data) {
if (!this.csrf_isPost) return this.csrf_send(data);
prepend = csrfMagicName + '=' + csrfMagicToken + '&';
delete this.csrf_isPost;
return this.csrf_send(prepend + data);
},
csrf_send: function(data) {
return this.csrf.send(data);
},
setRequestHeader: function(header, value) {
return this.csrf_setRequestHeader(header, value);
},
csrf_setRequestHeader: function(header, value) {
return this.csrf.setRequestHeader(header, value);
},
abort: function() {
return this.csrf.abort();
},
getAllResponseHeaders: function() {
return this.csrf.getAllResponseHeaders();
},
getResponseHeader: function(header) {
return this.csrf.getResponseHeader(header);
} // ,
}
// proprietary
CsrfMagic.prototype._updateProps = function() {
this.readyState = this.csrf.readyState;
if (this.readyState == 4) {
this.responseText = this.csrf.responseText;
this.responseXML = this.csrf.responseXML;
this.status = this.csrf.status;
this.statusText = this.csrf.statusText;
}
}
CsrfMagic.process = function(base) {
var prepend = csrfMagicName + '=' + csrfMagicToken;
if (base) return prepend + '&' + base;
return prepend;
}
// callback function for when everything on the page has loaded
CsrfMagic.end = function() {
// This rewrites forms AGAIN, so in case buffering didn't work this
// certainly will.
forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
form = forms[i];
if (form.method.toUpperCase() !== 'POST') continue;
if (form.elements[csrfMagicName]) continue;
var input = document.createElement('input');
input.setAttribute('name', csrfMagicName);
input.setAttribute('value', csrfMagicToken);
input.setAttribute('type', 'hidden');
form.appendChild(input);
}
}
// Sets things up for Mozilla/Opera/nice browsers
// We very specifically match against Internet Explorer, since they haven't
// implemented prototypes correctly yet.
if (window.XMLHttpRequest && window.XMLHttpRequest.prototype && '\v' != 'v') {
var x = XMLHttpRequest.prototype;
var c = CsrfMagic.prototype;
// Save the original functions
x.csrf_open = x.open;
x.csrf_send = x.send;
x.csrf_setRequestHeader = x.setRequestHeader;
// Notice that CsrfMagic is itself an instantiatable object, but only
// open, send and setRequestHeader are necessary as decorators.
x.open = c.open;
x.send = c.send;
x.setRequestHeader = c.setRequestHeader;
} else {
// The only way we can do this is by modifying a library you have been
// using. We support YUI, script.aculo.us, prototype, MooTools,
// jQuery, Ext and Dojo.
if (window.jQuery) {
// jQuery didn't implement a new XMLHttpRequest function, so we have
// to do this the hard way.
jQuery.csrf_ajax = jQuery.ajax;
jQuery.ajax = function( s ) {
if (s.type && s.type.toUpperCase() == 'POST') {
s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
if ( s.data && s.processData && typeof s.data != "string" ) {
s.data = jQuery.param(s.data);
}
s.data = CsrfMagic.process(s.data);
}
return jQuery.csrf_ajax( s );
}
}
if (window.Prototype) {
// This works for script.aculo.us too
Ajax.csrf_getTransport = Ajax.getTransport;
Ajax.getTransport = function() {
return new CsrfMagic(Ajax.csrf_getTransport());
}
}
if (window.MooTools) {
Browser.csrf_Request = Browser.Request;
Browser.Request = function () {
return new CsrfMagic(Browser.csrf_Request());
}
}
if (window.YAHOO) {
// old YUI API
YAHOO.util.Connect.csrf_createXhrObject = YAHOO.util.Connect.createXhrObject;
YAHOO.util.Connect.createXhrObject = function (transaction) {
obj = YAHOO.util.Connect.csrf_createXhrObject(transaction);
obj.conn = new CsrfMagic(obj.conn);
return obj;
}
}
if (window.Ext) {
// Ext can use other js libraries as loaders, so it has to come last
// Ext's implementation is pretty identical to Yahoo's, but we duplicate
// it for comprehensiveness's sake.
Ext.lib.Ajax.csrf_createXhrObject = Ext.lib.Ajax.createXhrObject;
Ext.lib.Ajax.createXhrObject = function (transaction) {
obj = Ext.lib.Ajax.csrf_createXhrObject(transaction);
obj.conn = new CsrfMagic(obj.conn);
return obj;
}
}
if (window.dojo) {
// NOTE: this doesn't work with latest dojo
dojo.csrf__xhrObj = dojo._xhrObj;
dojo._xhrObj = function () {
return new CsrfMagic(dojo.csrf__xhrObj());
}
}
}
This diff is collapsed.
...@@ -33,20 +33,7 @@ require_once("util.inc"); ...@@ -33,20 +33,7 @@ require_once("util.inc");
require_once("config.inc"); require_once("config.inc");
/* CSRF BEGIN: CHECK MUST BE EXECUTED FIRST; NO EXCEPTIONS */ /* CSRF BEGIN: CHECK MUST BE EXECUTED FIRST; NO EXCEPTIONS */
require_once('csrf.inc');
function csrf_startup()
{
global $config;
csrf_conf('rewrite-js', '/csrf/csrf-magic.js');
$timeout_minutes = isset($config['system']['webgui']['session_timeout']) ? $config['system']['webgui']['session_timeout'] : 240;
csrf_conf('expires', $timeout_minutes * 60);
}
session_start();
require_once('csrf/csrf-magic.php');
session_write_close();
/* CSRF END: THANK YOU FOR YOUR COOPERATION */ /* CSRF END: THANK YOU FOR YOUR COOPERATION */
function get_current_theme() function get_current_theme()
......
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