diff --git a/distros/ubuntu1604/zoneminder.links b/distros/ubuntu1604/zoneminder.links
index 4299f392a..14a8aee91 100644
--- a/distros/ubuntu1604/zoneminder.links
+++ b/distros/ubuntu1604/zoneminder.links
@@ -1,3 +1,4 @@
/var/cache/zoneminder/events /usr/share/zoneminder/www/events
/var/cache/zoneminder/images /usr/share/zoneminder/www/images
/var/cache/zoneminder/temp /usr/share/zoneminder/www/temp
+/var/tmp /usr/share/zoneminder/www/api/app/tmp
diff --git a/distros/ubuntu1604/zoneminder.tmpfile b/distros/ubuntu1604/zoneminder.tmpfile
index d307c6640..a7333ec19 100644
--- a/distros/ubuntu1604/zoneminder.tmpfile
+++ b/distros/ubuntu1604/zoneminder.tmpfile
@@ -1,2 +1,6 @@
-d /var/run/zm 0755 www-data www-data
-d /tmp/zm 0755 www-data www-data
+d /var/run/zm 0755 www-data www-data
+d /tmp/zm 0755 www-data www-data
+d /var/tmp/zm 0755 www-data www-data
+d /var/tmp/cache 0755 www-data www-data
+d /var/tmp/cache/models 0755 www-data www-data
+d /var/tmp/cache/persistent 0755 www-data www-data
diff --git a/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in b/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in
index 4dd136657..d6ff8b2d9 100644
--- a/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in
+++ b/scripts/ZoneMinder/lib/ZoneMinder/ConfigData.pm.in
@@ -354,6 +354,26 @@ our @options = (
type => $types{boolean},
category => 'system',
},
+ {
+ name => 'ZM_ENABLE_CSRF_MAGIC',
+ default => 'no',
+ description => 'Enable csrf-magic library',
+ help => q`
+ CSRF stands for Cross-Site Request Forgery which, under specific
+ circumstances, can allow an attacker to perform any task your
+ ZoneMinder user account has permission to perform. To accomplish
+ this, the attacker must write a very specific web page and get
+ you to navigate to it, while you are logged into the ZoneMinder
+ web console at the same time. Enabling ZM_ENABLE_CSRF_MAGIC will
+ help mitigate these kinds of attackes. Be warned this feature
+ is experimental and may cause problems, particularly with the API.
+ If you find a false positive and can document how to reproduce it,
+ then please report it. This feature defaults to OFF currently due to
+ its experimental nature.
+ `,
+ type => $types{boolean},
+ category => 'system',
+ },
{
name => 'ZM_OPT_USE_API',
default => 'yes',
diff --git a/web/includes/actions.php b/web/includes/actions.php
index 1f0e0ec47..eef058840 100644
--- a/web/includes/actions.php
+++ b/web/includes/actions.php
@@ -133,37 +133,50 @@ if ( !empty($action) ) {
$filterName = $_REQUEST['newFilterName'];
}
if ( $filterName ) {
- $sql = "REPLACE INTO Filters SET Name = ".dbEscape($filterName).",";
+ # Replace will teplace any filter with the same Id
+ # Since we aren't specifying the Id , this is effectively an insert
+ $sql = 'REPLACE INTO Filters SET Name = '.dbEscape($filterName).',';
} else {
$sql = 'UPDATE Filters SET';
- $endSql = "where Id = ".$_REQUEST['Id'];
+ $endSql = 'WHERE Id = '.$_REQUEST['Id'];
}
+
+ # endSql is only set if ! filterName... so... woulnd't this always be true
if ( !empty($filterName) || $endSql ) {
$_REQUEST['filter']['sort_field'] = validStr($_REQUEST['sort_field']);
$_REQUEST['filter']['sort_asc'] = validStr($_REQUEST['sort_asc']);
$_REQUEST['filter']['limit'] = validInt($_REQUEST['limit']);
- $sql .= " Query = ".dbEscape(jsonEncode($_REQUEST['filter']));
+ $sql .= ' Query = '.dbEscape(jsonEncode($_REQUEST['filter']));
if ( !empty($_REQUEST['AutoArchive']) )
- $sql .= ", AutoArchive = ".dbEscape($_REQUEST['AutoArchive']);
+ $sql .= ', AutoArchive = '.dbEscape($_REQUEST['AutoArchive']);
if ( !empty($_REQUEST['AutoVideo']) )
- $sql .= ", AutoVideo = ".dbEscape($_REQUEST['AutoVideo']);
+ $sql .= ', AutoVideo = '.dbEscape($_REQUEST['AutoVideo']);
if ( !empty($_REQUEST['AutoUpload']) )
- $sql .= ", AutoUpload = ".dbEscape($_REQUEST['AutoUpload']);
+ $sql .= ', AutoUpload = '.dbEscape($_REQUEST['AutoUpload']);
if ( !empty($_REQUEST['AutoEmail']) )
- $sql .= ", AutoEmail = ".dbEscape($_REQUEST['AutoEmail']);
+ $sql .= ', AutoEmail = '.dbEscape($_REQUEST['AutoEmail']);
if ( !empty($_REQUEST['AutoMessage']) )
- $sql .= ", AutoMessage = ".dbEscape($_REQUEST['AutoMessage']);
+ $sql .= ', AutoMessage = '.dbEscape($_REQUEST['AutoMessage']);
if ( !empty($_REQUEST['AutoExecute']) && !empty($_REQUEST['AutoExecuteCmd']) )
- $sql .= ", AutoExecute = ".dbEscape($_REQUEST['AutoExecute']).", AutoExecuteCmd = ".dbEscape($_REQUEST['AutoExecuteCmd']);
+ $sql .= ', AutoExecute = '.dbEscape($_REQUEST['AutoExecute']).", AutoExecuteCmd = ".dbEscape($_REQUEST['AutoExecuteCmd']);
if ( !empty($_REQUEST['AutoDelete']) )
- $sql .= ", AutoDelete = ".dbEscape($_REQUEST['AutoDelete']);
+ $sql .= ', AutoDelete = '.dbEscape($_REQUEST['AutoDelete']);
if ( !empty($_REQUEST['background']) )
- $sql .= ", Background = ".dbEscape($_REQUEST['background']);
+ $sql .= ', Background = '.dbEscape($_REQUEST['background']);
if ( !empty($_REQUEST['concurrent']) )
- $sql .= ", Concurrent = ".dbEscape($_REQUEST['concurrent']);
+ $sql .= ', Concurrent = '.dbEscape($_REQUEST['concurrent']);
$sql .= $endSql;
dbQuery( $sql );
- $refreshParent = true;
+ if ( $filterName ) {
+ $filter = dbFetchOne( 'SELECT * FROM Filters WHERE Name=?', NULL, array($filterName) );
+ if ( $filter ) {
+ # This won't work yet because refreshparent refreshes the old filter. Need to do a redirect instead of a refresh.
+ $_REQUEST['Id'] = $filter['Id'];
+ } else {
+ Error("No new Id despite new name");
+ }
+ }
+ $refreshParent = '/index.php?view=filter&Id='.$_REQUEST['Id'];
}
} // end if canedit events
} // end if action == filter
@@ -512,7 +525,7 @@ if ( !empty($action) ) {
dbQuery( "update TriggersX10 set ".implode( ", ", $x10Changes )." where MonitorId=?", array($mid) );
} elseif ( !$user['MonitorIds'] ) {
if ( !$x10Monitor ) {
- dbQuery( "insert into TriggersX10 set MonitorId = ?".implode( ", ", $x10Changes ), array( $mid ) );
+ dbQuery( "insert into TriggersX10 set MonitorId = ?, ".implode( ", ", $x10Changes ), array( $mid ) );
} else {
dbQuery( "delete from TriggersX10 where MonitorId = ?", array($mid) );
}
diff --git a/web/includes/csrf/LICENSE.txt b/web/includes/csrf/LICENSE.txt
new file mode 100644
index 000000000..37b07717d
--- /dev/null
+++ b/web/includes/csrf/LICENSE.txt
@@ -0,0 +1,9 @@
+Copyright (c) 2008-2013, Edward Z. Yang
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ 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 BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
diff --git a/web/includes/csrf/NEWS.txt b/web/includes/csrf/NEWS.txt
new file mode 100644
index 000000000..66d52f6da
--- /dev/null
+++ b/web/includes/csrf/NEWS.txt
@@ -0,0 +1,69 @@
+
+ [[ news ]]
+
+1.0.4 released 2013-07-17
+
+ [SECURITY FIXES]
+
+ - When secret key was not explicitly set, it was not being used
+ by the csrf_hash() function. Thanks sparticvs for reporting.
+
+ [FEATURES]
+
+ - The default 'CSRF check failed' page now offers a handy 'Try
+ again' button, which resubmits the form.
+
+ [BUG FIXES]
+
+ - The fix for 1.0.3 inadvertantly turned off XMLHttpRequest
+ overloading for all browsers; it has now been fixed to only
+ apply to IE.
+
+1.0.3 released 2012-01-31
+
+ [BUG FIXES]
+
+ - Internet Explorer 8 adds support for XMLHttpRequest.prototype,
+ but this support is broken for method overloading. We
+ explicitly disable JavaScript overloading for Internet Explorer.
+ Thanks Kelly Lu for reporting.
+
+ - A global declaration was omitted, resulting in a variable
+ not being properly introduced in PHP 5.3. Thanks Whitney Beck for
+ reporting.
+
+1.0.2 released 2009-03-08
+
+ [SECURITY FIXES]
+
+ - Due to a typo, csrf-magic accidentally treated the secret key
+ as always present. This means that there was a possible CSRF
+ attack against users without any cookies. No attacks in the
+ wild were known at the time of this release. Thanks Jakub
+ Vrána for reporting.
+
+1.0.1 released 2008-11-02
+
+ [NEW FEATURES]
+
+ - Support for composite tokens; this also fixes a bug with using
+ IP-based tokens for users with cookies disabled.
+
+ - Native support cookie tokens; use csrf_conf('cookie', $name) to
+ specify the name of a cookie that the CSRF token should be
+ placed in. This is useful if you have a Squid cache, and need
+ to configure it to ignore this token.
+
+ - Tips/tricks section in README.txt.
+
+ - There is now a two hour expiration time on all tokens. This
+ can be modified using csrf_conf('expires', $seconds).
+
+ - ClickJacking protection using an iframe breaker. Disable with
+ csrf_conf('frame-breaker', false).
+
+ [BUG FIXES]
+
+ - CsrfMagic.send() incorrectly submitted GET requests twice,
+ once without the magic token and once with the token. Reported
+ by Kelly Lu .
diff --git a/web/includes/csrf/README.txt b/web/includes/csrf/README.txt
new file mode 100644
index 000000000..98d225dba
--- /dev/null
+++ b/web/includes/csrf/README.txt
@@ -0,0 +1,160 @@
+
+ [[ csrf-magic ]]
+
+Add the following line to the top of all web-accessible PHP pages. If you have
+a common file included by everything, put it there.
+
+ include_once '/path/to/csrf-magic.php';
+
+Do it, test it, then forget about it. csrf-magic is protecting you if nothing
+bad happens. Read on if you run into problems.
+
+
+ TABLE OF CONTENTS
+ + ------------------- +
+ 1. TIPS AND TRICKS
+ 2. AJAX
+ 3. CONFIGURE
+ 4. THANKS
+ 5. FOOTNOTES
+ + ------------------- +
+
+
+1. TIPS AND TRICKS
+
+ * If your JavaScript and AJAX is persistently getting errors, check the
+ AJAX section below on how to fix.
+
+ * The CSS overlay protection makes it impossible to display your website
+ in frame/iframe elements. You can disable it with
+ csrf_conf('frame-breaker', false) in your csrf_startup() function.
+
+ * csrf-magic will start a session. To disable, use csrf_conf('auto-session',
+ false) in your csrf_startup() function.
+
+ * The default error message is a little user unfriendly. Write your own
+ function which outputs an error message and set csrf_conf('callback',
+ 'myCallbackFunction') in your csrf_startup() function.
+
+ * Make sure csrf_conf('secret', 'ABCDEFG') has something random in it. If
+ the directory csrf-magic.php is in is writable, csrf-magic will generate
+ a secret key for you in the csrf-secret.php file.
+
+ * Remember you can use auto_prepend to include csrf-magic.php on all your
+ pages. You may want to create a stub file which you can include that
+ includes csrf-magic.php as well as performs configuration.
+
+ * The default expiration time for tokens is two hours. If you expect your
+ users to need longer to fill out forms, be sure to enable double
+ submission when the token is invalid.
+
+
+2. AJAX
+
+csrf-magic has the ability to dynamically rewrite AJAX requests which use
+XMLHttpRequest. However, due to the invasiveness of this procedure, it is
+not enabled by default. You can enable it by adding this code before you
+include csrf-magic.php.
+
+ function csrf_startup() {
+ csrf_conf('rewrite-js', '/web/path/to/csrf-magic.js');
+ }
+ // include_once '/path/to/csrf-magic.php';
+
+(Be sure to place csrf-magic.js somewhere web accessible).
+
+The default method CSRF Magic uses to rewrite AJAX requests will
+only work for browsers with support for XmlHttpRequest.prototype (this excludes
+all versions of Internet Explorer). See this page for more information:
+http://stackoverflow.com/questions/664315/internet-explorer-8-prototypes-and-xmlhttprequest
+
+However, csrf-magic.js will
+automatically detect and play nice with the following JavaScript frameworks:
+
+ * jQuery
+ * Prototype
+ * MooTools
+ * Ext
+ * Dojo
+
+(Note 2013-07-16: It has been a long time since this manual support has
+been updated, and some JavaScript libraries have placed their copies of XHR
+in local variables in closures, which makes it difficult for us to monkey-patch
+it in automatically.)
+
+To rewrite your own JavaScript library to use csrf-magic.js, you should modify
+your function that generates XMLHttpRequest to have this at the end:
+
+ return new CsrfMagic(xhrObject);
+
+With whatever xhrObject may be. If you have literal instances of XMLHttpRequest
+in your code, find and replace ''new XMLHttpRequest'' with ''new CsrfMagic''
+(CsrfMagic will automatically instantiate an XMLHttpRequest object in a
+cross-platform manner as necessary).
+
+If you don't want csrf-magic monkeying around with your XMLHttpRequest object,
+you can manually rewrite your AJAX code to include the variable. The important
+information is stored in the global variables csrfMagicName and csrfMagicToken.
+CsrfMagic.process may also be of interest, as it takes one parameter, a
+querystring, and prepends the CSRF token to the value.
+
+
+3. CONFIGURE
+
+csrf-magic has some configuration options that you can set inside the
+csrf_startup() function. They are described in csrf-magic.php, and you can
+set them using the convenience function csrf_conf($name, $value).
+
+For example, this is a recommended configuration:
+
+ /**
+ * This is a function that gets called if a csrf check fails. csrf-magic will
+ * then exit afterwards.
+ */
+ function my_csrf_callback() {
+ echo "You're doing bad things young man!";
+ }
+
+ function csrf_startup() {
+
+ // While csrf-magic has a handy little heuristic for determining whether
+ // or not the content in the buffer is HTML or not, you should really
+ // give it a nudge and turn rewriting *off* when the content is
+ // not HTML. Implementation details will vary.
+ if (isset($_POST['ajax'])) csrf_conf('rewrite', false);
+
+ // This is a secret value that must be set in order to enable username
+ // and IP based checks. Don't show this to anyone. A secret id will
+ // automatically be generated for you if the directory csrf-magic.php
+ // is placed in is writable.
+ csrf_conf('secret', 'ABCDEFG123456');
+
+ // This enables JavaScript rewriting and will ensure your AJAX calls
+ // don't stop working.
+ csrf_conf('rewrite-js', '/csrf-magic.js');
+
+ // This makes csrf-magic call my_csrf_callback() before exiting when
+ // there is a bad csrf token. This lets me customize the error page.
+ csrf_conf('callback', 'my_csrf_callback');
+
+ // While this is enabled by default to boost backwards compatibility,
+ // for security purposes it should ideally be off. Some users can be
+ // NATted or have dialup addresses which rotate frequently. Cookies
+ // are much more reliable.
+ csrf_conf('allow-ip', false);
+
+ }
+
+ // Finally, include the library
+ include_once '/path/to/csrf-magic.php';
+
+Configuration gets stored in the $GLOBALS['csrf'] array.
+
+
+4. THANKS
+
+My thanks to Chris Shiflett, for unintentionally inspiring the idea, as well
+as telling me the original variant of the Bob and Mallory story,
+and the Django CSRF Middleware authors, who thought up of this before me.
+Gareth Heyes suggested using the frame-breaker option to protect against
+CSS overlay attacks.
diff --git a/web/includes/csrf/csrf-magic.js b/web/includes/csrf/csrf-magic.js
new file mode 100644
index 000000000..0989c1065
--- /dev/null
+++ b/web/includes/csrf/csrf-magic.js
@@ -0,0 +1,191 @@
+/**
+ * @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 + '&';
+ // XXX: Removed to eliminate 'Refused to set unsafe header "Content-length" ' errors in modern browsers
+ // if (this.csrf_purportedLength === undefined) {
+ // this.csrf_setRequestHeader("Content-length", this.csrf_purportedLength + prepend.length);
+ // delete this.csrf_purportedLength;
+ // }
+ delete this.csrf_isPost;
+ return this.csrf_send(prepend + data);
+ },
+ csrf_send: function(data) {
+ return this.csrf.send(data);
+ },
+
+ setRequestHeader: function(header, value) {
+ // We have to auto-set this at the end, since we don't know how long the
+ // nonce is when added to the data.
+ if (this.csrf_isPost && header == "Content-length") {
+ this.csrf_purportedLength = value;
+ return;
+ }
+ 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) {
+ if(typeof base == 'object') {
+ base[csrfMagicName] = csrfMagicToken;
+ return 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());
+ }
+ }
+}
diff --git a/web/includes/csrf/csrf-magic.php b/web/includes/csrf/csrf-magic.php
new file mode 100644
index 000000000..153417f4e
--- /dev/null
+++ b/web/includes/csrf/csrf-magic.php
@@ -0,0 +1,405 @@
+
+ */
+$GLOBALS['csrf']['input-name'] = '__csrf_magic';
+
+/**
+ * Set this to false if your site must work inside of frame/iframe elements,
+ * but do so at your own risk: this configuration protects you against CSS
+ * overlay attacks that defeat tokens.
+ */
+$GLOBALS['csrf']['frame-breaker'] = true;
+
+/**
+ * Whether or not CSRF Magic should be allowed to start a new session in order
+ * to determine the key.
+ */
+$GLOBALS['csrf']['auto-session'] = true;
+
+/**
+ * Whether or not csrf-magic should produce XHTML style tags.
+ */
+$GLOBALS['csrf']['xhtml'] = true;
+
+// FUNCTIONS:
+
+// Don't edit this!
+$GLOBALS['csrf']['version'] = '1.0.4';
+
+/**
+ * Rewrites
+
CSRF check failed. Your form session may have expired, or you may not have
+ cookies enabled.
+
+
Debug: $tokens
', $script . '', $buffer, $count);
+ if (!$count) {
+ $buffer .= $script;
+ }
+ }
+ return $buffer;
+}
+
+/**
+ * Checks if this is a post request, and if it is, checks if the nonce is valid.
+ * @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;
+ csrf_start();
+ $name = $GLOBALS['csrf']['input-name'];
+ $ok = false;
+ $tokens = '';
+ do {
+ 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;
+ $ok = true;
+ } while (false);
+ if ($fatal && !$ok) {
+ $callback = $GLOBALS['csrf']['callback'];
+ if (trim($tokens, 'A..Za..z0..9:;,') !== '') $tokens = 'hidden';
+ $callback($tokens);
+ exit;
+ }
+ return $ok;
+}
+
+/**
+ * Retrieves a valid token(s) for a particular context. Tokens are separated
+ * by semicolons.
+ */
+function csrf_get_tokens() {
+ $has_cookies = !empty($_COOKIE);
+
+ // $ip implements a composite key, which is sent if the user hasn't sent
+ // any cookies. It may or may not be used, depending on whether or not
+ // the cookies "stick"
+ $secret = csrf_get_secret();
+ if (!$has_cookies && $secret) {
+ // :TODO: Harden this against proxy-spoofing attacks
+ $IP_ADDRESS = (isset($_SERVER['IP_ADDRESS']) ? $_SERVER['IP_ADDRESS'] : $_SERVER['REMOTE_ADDR']);
+ $ip = ';ip:' . csrf_hash($IP_ADDRESS);
+ } else {
+ $ip = '';
+ }
+ 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 ($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;
+ // These further algorithms require a server-side secret
+ if (!$secret) return 'invalid';
+ if ($GLOBALS['csrf']['user'] !== false) {
+ return 'user:' . csrf_hash($GLOBALS['csrf']['user']);
+ }
+ if ($GLOBALS['csrf']['allow-ip']) {
+ return ltrim($ip, ';');
+ }
+ return 'invalid';
+}
+
+function csrf_flattenpost($data) {
+ $ret = array();
+ 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);
+ $ret = array();
+ foreach($data as $n => $v) {
+ $nk = $level >= 1 ? $key."[$n]" : "[$n]";
+ $ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v));
+ }
+ return $ret;
+}
+
+/**
+ * @param $tokens is safe for HTML consumption
+ */
+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;
+ $data .= '';
+ }
+ echo "