Distinguish javascript and html context with regex php

56 Views Asked by At

I am trying to add global csrf protection in my php web application. I am using the library csrf-magic from packagist, which in turn uses ob_start to add a csrf token as a hidden input in every form and a js script to add csrf token in ajax calls:

<input name='csrf' type='hidden' value='...' />
<script type="text/javascript">...</script>

It uses regex to achieve that with patterns: #(<form[^>]*method\s*=\s*["\']post["\'][^>]*>)#i to add csrf token in forms and: /<\/body>/ to add the js script

The problem that appears, is when an html page is built dynamically by js. For example:

<script>
var html = '
<html>
    <head>
    </head>
    <body>
        <form action="testurl" method="post">
        </form>
    </body>
<html>
';
$("#testid").html(html);
</script>

In above case the output will be:

<script>
var html = '
<html>
    <head>
    </head>
    <body>
        <form action="testurl" method="post">
            <input name='csrf' type='hidden' value='...' />
        </form>
        <script type="text/javascript">...</script>
    </body>
<html>
';
$("#testid").html(html);
</script>

So in this case the single apostrophe in input must be escaped and so must the '/' in </script>. I think the solution would be to check if the form or body is in javascipt context and what apostrophes are used (single or double) to escape accordingly. Is it possible to achieve this by regex?

0

There are 0 best solutions below