Coder Social home page Coder Social logo

csrf-magic's Introduction

                            [[  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.

csrf-magic's People

Contributors

ezyang avatar neweracracker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

csrf-magic's Issues

Real CSRF protector

Hello. Im here regarding your curious project name but is not compatible with big or general apps.

You should consider to write this utility with OOP, instead of working in a global scope.
Also should need to take into account that session handler is not always the php out of the box.

Regards!

No file upload with v1.0.4

After upgrading from 1.0.1 to 1.0.4, file uploads are no longer possible. It seems the JS scrambles the form data somehow. On the server side, $ _ REQUEST and $ _ POST are just empty.

After replacing the JS with the old version, uploads are working again.

defer option?

Hi,

What does the defer option do please? If its set to true do we need to manually call csrf_check() ?

Thanks

Problem with jquery-file-upload and csrf-magic

I am having a problem combining csrf-magic and jquery-file-upload by blueimp. When trying to send the files (i.e. send the upload form), the csrf-magic.js prepends the data with it's token. Result is an invalid post:

__csrf_magic=sid:d0a151fd235a4f1302269149a01afe55a45db3de,1432143876&[object FormData]

The server side script now gets nothing as the query string is invalid.

Any ideas?

Add a license

Would be great to have a license so that I could use this in a project!

Sometimes, csrf magic interferes with my json request.

About half the time I find "junk" in my request payload. Naturally, the site I am communicating with complains. {"message": "Unsupported JSON format : Could not create a JSON event when trying to serialize"}

__csrf_magic=sid:1abf8...,1485208109&{"sessionId": "johnsSession", ... "productId": "berli18"}

The other half of the time, the payload is not affected. I get a 200 back.

{"sessionId": "johnsSession", ... "productId": "berli18"}

Is there some technique to leave particular requests out of the special magic? I think you add something to XMLHttpRequest's prototype. Perhaps I should new the original object. Is that available somewhere?

Question: How to use existing session (if this is the problem...)

I am having problems using an existing session.

There is an existing App (CMS) using CSRF-Magic in the Backend. After clicking on a form button that is calling an external PHP script, I keep getting "CSRF check failed", though the form has the magic token set. The output of the called PHP script is suppressed. I played around with auto-session and key settings, but did not manage it. Any hints?

Parsing site implemented with csrf-magic

Hello guys,

So i was trying to parse a website which uses csrf-magic. I am not trying to do a cross site request. Just parsing. I was using python requests. But soon i realised that the tokens are dynamic and change with every request.

Can anyone please point me in the right direction ??
I know its not an issue.
Any help is appreciated.

csrf_get_tokens() ip address

I always change

$ip = ';ip:' . csrf_hash($_SERVER['IP_ADDRESS']);

to

$ip = ';ip:' . csrf_hash($_SERVER['REMOTE_ADDRESS']);

which gives the client's IP. In my Apache server environment, IP_ADDRESS is never set.

How to use the key and user type features?

Reading through the source code

csrf-magic/csrf-magic.php

Lines 306 to 324 in 7d3527a

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;
return $value === csrf_hash($_COOKIE[$n], $time);
case 'key':
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;
return $value === csrf_hash($GLOBALS['csrf']['user'], $time);
case 'ip':
I was wondering how to use the key or user feature. Could you provide an example of how to create a static secret to put into a form?

Background is having an automatic login into a form-based authentication that has csrf protection.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.