I've been reading about XSS and I made a simple form with a text and submit input, but when I execute <script>alert();</script> on it, nothing happens, the server gets that string and that's all.
What do I have to do for make it vulnerable?? (then I'll learn what I shouldn't do hehe)
Cheers.
Indeed just let the server output it so that the input string effectively get embedded in HTML source which get returned to the client.
PHP example:
<!doctype html>
<html lang="en">
<head><title>XSS test</title></head>
<body>
<form><input type="text" name="xss"><input type="submit"></form>
<p>Result: <?= $_GET['xss'] ?></p>
</body>
</html>
JSP example:
<!doctype html>
<html lang="en">
<head><title>XSS test</title></head>
<body>
<form><input type="text" name="xss"><input type="submit"></form>
<p>Result: ${param.xss}</p>
</body>
</html>
Alternatively you can redisplay the value in the input elements, that's also often seen:
<input type="text" name="xss" value="<?= $_GET['xss'] ?>">
resp.
<input type="text" name="xss" value="${param.xss}">
This way "weird" attack strings like "/><script>alert('xss')</script><br class=" will work because the server will render it after all as
<input type="text" name="xss" value=""/><script>alert('xss')</script><br class="">
XSS-prevention solutions are among others htmlspecialchars() and fn:escapeXml() for PHP and JSP respectively. Those will replace among others <, > and " by <, > and " so that enduser input doesn't end up to be literally embedded in HTML source but instead just got displayed as it was entered.
Have the server output the input back to the client.
You should "inject" the script. So if you have a text-input, you should put in the form:
" /> <script>alert();</script>
This way you first close the attribute of the existing HTML and then inject your own code. The idea is to escape out the quotes.
Three simple things:
If you're not outputting untrusted data to the page at some point there is no opportunity for XSS
All your untusted data (forms, querystrings, headers, etc) should be validated against a whitelist to ensure it's within an acceptable range
All your output to the screen should be endcoded with an appropriate library (ie Anti-XSS for .NET) onto the appropriate language (HTML, CSS, JS, etc).
More info with examples in OWASP Top 10 for .NET developers part 2: Cross-Site Scripting (XSS).
Google made a really awesome tutorial that covers XSS and other security vulnerabilities here. It can help you understand how these issues are exploited in real applications.
Related
I am a cybersecurity student trying to understand some basic HTML injections. I have been working on this code for a few days and can't understand what I am doing wrong. The code that I have currently does allow for injection, for example if I put <h1>test</h1> into the textbox, it will display test as a header. But if I try <script>alert(1)</script> it won't actually run the script. I have tried setting the value of the text box to "" or with the thought that I could close out that line by inputting the following into the textbox: "><script>alert(1)</script>
I've also tried to cancel out the remainder of the code by adding a comment to the end like this: <script>alert(1)</script><!--
I've tried a number of combinations of each with no luck. Now I actually need to be able to inject a script since I'm playing around with CSP and how that affects injection of scripts into the webpage. I currently DO NOT have a csp specified that would restrict the JavaScript from running. Some other things I've tried include using different browsers, changing browser security, and ensuring that JavaScript is enabled in the browser. Any help would be greatly appreciated!!
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>
That's because <script>s run at page load, and, when the label's content change, the scripts have ran already.
However, if you inject <script> tags to a different page (through the backend (XSS means Cross-Site Scripting)), it does work.
Alternatively, to make it work in a scenario, where the content injected after page load (like your case), you can use JS events (like onclick) to run your code:
<div onclick="alert(1)">Click me!</div>
Or, to execute it without user interaction, you could use an <iframe>'s onload event:
<iframe onload="alert(1)" style="display:none"></iframe>
to execute javascript from your form, you can try:
<iframe src=javascript:alert(1)>
or
<img src=x onerror=alert(1)>
Also worth noting:
script elements inserted using innerHTML do not execute when they
are inserted.
To manually execute JavaScript, you may do the following
without editing your HTML file, add this to the Input field on your Browser.
<iframe onload="alert(1)" style="display:none"></iframe>
More information on why this works here
More on how you can perform actions like this here: developer.mozilla.org
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>
This question already has answers here:
How to display raw HTML code on an HTML page
(30 answers)
Closed 8 years ago.
I'm writing a C++ Style Guide for my company in html/css/javascript. I'm quite irritated with html as it treats anything between < and > as html tag and thus processes them as well. As a result of which my code (which I put in the style guide) doesn't look as such. Here is an example:
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
and I want the browser to render it exactly like that, but it doesn't render so, e.g Chrome doesn't show <std::string> part, and IE 8.0 capitalize <std::string> as <STD::STRING> (and all such template codes).
I don't want any kind of interference by html engine. Is there any simple way to achieve what I want? Any polite way to tell the browser to not modify my code?
Note that replacing < with < and > with > would work, but it is cumbersome to write it everytime I write a template code. It also makes my code difficult to read in the source code of the html. So I'm looking for a simple solution.
The notion of a "polite way to to tell the browser to not modify (parse) my code" is precisely what XML's CDATA does. Nothing more, nothing less.
CDATA does not exist in HTML, so there is no way in HTML to treat <std:vector> as anything other than on opening tag for the (non-existent) std:vector element.
The normal way to do this is a server-side transformation. Now if you aren't generating your HTML server-side, and are instead writing it by hand, you can make your life just a dash easier with a client-side transformation like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
</head>
<body>
<pre><script type="text/coffeescript" >document.write "
std::vector<std::string> get_project_names();
".replace('<','<')
</script></pre>
</body>
</html>
Here I used CoffeeScript because of its multiline string capability which is coming in ES6 for regular JavaScript. It makes it easy to just drop in your code between the boilerplate lines.
Now I know full well even this solution is lacking! If your inserted code contains a " you're out of luck. And it doesn't escape ampersands.
Bottom line is that there is no CDATA, so no "simple" solution exists. A transformation, client-side or server-side, is required.
Have you tried markdown?
I've been dealing with this particular problem for years, and it's always been frustrating. I've always appreciated the simplicity and elegance of Markdown, so I did a little research to see if there was any way to use Markdown to build an HTML document.
Thing is, code samples sometimes involve HTML, yet HTML is the language we're using to write style guides and API documentation, so my thought was that if we wrote the API documentation and style guides in Markdown, we'd eliminate all of the conflicts between HTML and the syntax of other languages.
I found Strapdown.js, which is a library that allows you to create a Web page with pure Markdown. The library then compiles it to HTML and renders it on the page client side. We put together the API documentation for one of our products using this library, and we published it as a GitHub page.
Here's a small, concise example:
<!DOCTYPE html>
<html>
<title>JavaScript API</title>
<xmp theme="united" style="display:none;">
## Print the name
Print the user's name:
```javascript
function printName(name) {
alert(name);
}
```
</xmp>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>
</html>
Everything inside the <xmp> tags gets compiled to HTML.
Note: The XMP tag has been deprecated for some time as per the Mozilla HTML documentation on XMP. Thus, you may want to either hack the code to make it use PRE or CODE, or you may want to consider using the lower-level Marked library that was used to build Strapdown.js. I filed an issue with the Strapdown.js team.
For that you can use this
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
This would be encoded and you'll get the result that you want.
Here is the fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/
JavaScript code
The JavaScript method of doing this would be simple, you can convert the whole code to a String variable.
As this
var string = "content here";
Then apply this,
string.replace('<','<').replace('>','>');
Convert all the characters and then have then rendered by the Browser.
http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/1/
For my book I used http://markup.su/highlighter/ syntax highlighter. Paste the code into it, generate highlighted code, and paste the latter into the HTML document. Worked pretty well. Here's a fiddle with your code: http://jsfiddle.net/6GTs2/.
Here's your code highlighted for HTML:
<pre style="background:#000;color:#f8f8f8">std::vector<std::string> <span style="color:#89bdff">get_project_names</span>();
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> Printable>
<span style="color:#99cf50">void</span> <span style="color:#89bdff">print</span>(Printable const & item);
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> FwdIterable, <span style="color:#99cf50">typename</span> Predicate>
FwdIterable <span style="color:#89bdff">find_if</span>(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
Someone brought up an argument that having a textarea that accepts too many characters may be risky because people may put script in there.
In my entire existence, I've never heard of that possibility.
Could anyone shed some light as whether or not it is possible to have a script in a text form field and somehow have it executed?
Yes - this is how XSS works. Very simply- you can add script stuff to the dom and execute it that way. For instance, this would fire an alert:
$('#myDiv').html('<script type="text/javascript">alert("hello world");</script>');
Here is a fiddle
Any time you deal with use input, you're at risk of XSS vulnerabilities.
Let's say you have a simple HTML form like this:
<form action="submit.php" method="post">
<textarea name="insecuretext"></textarea>
</form>
And then on your server you have something like this:
<div class="usercontent">
<?php echo $_POST["insecuretext"]; ?>
</div>
For 99% of your users, this will work perfectly, but what if someone submitted this?
<script>somethingEvil();</script>
Your HTML would look like this:
<div class="usercontent">
<script>somethingEvil();</script>
</div>
And then anyone who looks at that page will be affected by the JavaScript.
A really easy solution is to sanitize your input by calling strip_tags()
<div class="usercontent">
<?php echo strip_tags($_POST["insecuretext"]); ?>
</div>
Now, unless your attacker is really clever, you're not vulnerable to XSS in this situation.
Another common situation is if you put insecure content as an attribute of an element. I saw an example of this on a forum a while back where the developers put the contents of the post in a data-content attribute for some reason.
<div class="forum_post" data-content="<?php echo $_POST["insecuretext"]; ?>"></div>
I was able to break this by submitting something like:
foo" onload="somethingEvil();"> <!--
Which printed out as <div class="forum_post" data-content="foo" onload="somethingEvil();"> <!-- ></div>
In this case, all that needed to be done was to convert my special characters to entities:
<div class="forum_post" data-content="<?php echo htmlentities($_POST["insecuretext"]); ?>"></div>
Which would look like this:
<div class="forum_post" data-content="foo" onload="somethingEvil();"> <!-- "></div>
So here's what you should take from this:
Don't trust your users under any circumstances
Never print unsanitized or unvalidated user input
Understand XSS techniques and how to stop them
Know when you could potentially be vulnerable and what you'll do if an attacker gets through your defenses
Understand that length isn't related to security at all. Unless you limit your input to like 3 characters, it could potentially be dangerous.
Is it alright to define and use custom tags? (that will not conflict with future html tags) - while replacing/rendering those by changing outerHTML??
I created a demo below and it seems to work fine
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div id="customtags">
<c-TextField name="Username" ></c-TextField> <br/>
<c-NameField name="name" id="c-NameField"></c-NameField> <br/>
<c-TextArea name="description" ></c-TextArea> <br/>
<blahblah c-t="d"></blahblah>
</div>
</body>
<script>
/* Code below to replace the cspa's with the actual html -- woaah it works well */
function ReplaceCustomTags() {
// cspa is a random term-- doesn;t mean anything really
var grs = $("*");
$.each(grs, function(index, value) {
var tg = value.tagName.toLowerCase();
if(tg.indexOf("c-")==0) {
console.log(index);
console.log(value);
var obj = $(value);
var newhtml;
if(tg=="c-textfield") {
newhtml= '<input type="text" value="'+obj.attr('name')+'"></input>';
} else if(tg=="c-namefield") {
newhtml= '<input type="text" value="FirstName"></input><input type="text" value="LastName"></input>';
} else if(tg=="c-textarea") {
newhtml= '<textarea cols="20" rows="3">Some description from model</textarea>';
}
obj.context.outerHTML = newhtml;
}
z = obj;
});
}
if(typeof(console)=='undefined' || console==null) { console={}; console.log=function(){}}
$(document).ready(ReplaceCustomTags);
</script>
</html>
Update to the question:
Let me explain a bit further on this. Please assume that JavaScript is enabled on the browser - i.e application is not supposed to run without javascript.
I have seen libraries that use custom attributes to define custom behavior in specified tags. For example Angular.js heavily uses custom attributes. (It also has examples on custom-tags). Although my question is not from a technical strategy perspective - I fail to understand why it would strategically cause problems in scalability/maintainability of the code.
Per me code like <ns:contact .....> is more readable than something like <div custom_type="contact" ....> . The only difference is that custom tags are ignored and not rendered, while the div type gets rendered by the browser
Angular.js does show a custom-tag example (pane/tab). In my example above I am using outerHTML to replace these custom tags - whilst I donot see such code in the libraries - Am I doing something shortsighted and wrong by using outerHTML to replace custom-tags?
I can't think of a reason why you'd want to do this.
What would you think if you had to work on a project written by someone else who ignored all common practices and conventions? What would happen if they were no longer at the company to find out why they did something a certain way?
The fact that you have to just go through with JavaScript to make it work at all should be a giant red flag. Unless you have a VERY good reason to, do yourself a favor and use the preexisting tags. Six months from now, are you going to remember why you did things that way?
It may well work, but it's probably not a good idea. Screen readers and search engines may have a hard/impossible time reading your page, since they may not interpret the JavaScript. While I can see the point, it's probably better to use this template to develop with, then "bake" it to HTML before putting it on the server.
I want to remove all things or content between <script>want to remove</script>
I have very small amount of knowledge about php & java script so please give me a complete codes I have no idea how to use php or JavaScript coding to remove content between <tags></tags>
I found this box and copy in my website they remove all tags but I not want this I want only remove content between tags.
Please any one modify this box or script to remove content between <tags></tags> or give me other script.
<script type="text/javascript">
// Strip HTML Tags (form) script- By JavaScriptKit.com (http://www.javascriptkit.com)
// For this and over 400+ free scripts, visit JavaScript Kit- http://www.javascriptkit.com/
// This notice must stay intact for use
function stripHTML(){
var re= /<\S[^><]*>/g
for (i=0; i<arguments.length; i++)
arguments[i].value=arguments[i].value.replace(re, "")
}
</script>
<form>
<textarea name="data1" style="width: 400px; height: 100px"></textarea><br />
<input type="button" value="Remove any HTML tags" onClick="stripHTML(this.form.data1)">
</form>
you could try:
document.getElementsByTagName('script')[0].innerHTML = '';
According to your code block you posted, it seems that you would like to strip script tags from the value of a form element (e.g. a textarea). Sanitizing user input on client side is generally considered to be a bad idea, because this kind of security measure can be easily bypassed. A better solution would be stripping the script tags from the posted data on the server side.
Here is an example in php:
$data = $_POST['fieldname'];
$outputData = strip_tags($data, array(/* here you can specify the allowed html tags, all others will be stripped */);
echo $output;