Is jQuery(userInput) "safe" for end-users? - javascript

I'm developing a little jQuery selector game. Essentially, you're given some HTML code, and you have to write the jQuery selector to select the highlighted item.
For example, say you have:
<body>
<p id="winner">Select this paragraph</p>
<p> But not this one </p>
</body>
And one of the correct selectors would be $('#winner')
I currently plan on grabbing the string within the "$(' ... ') " (where the ...'s are) and doing something like this:
var userInput = ...
var userSelectedItems = new Array();
userSelectedItems = $(userInput)
// Check if userSelectedItems == the array of elements supposed to be selected
// Change screen to green and allow users to press enter and continue to next challenge.
Now, I know that if you allow users to directly enter some PHP or something, all sorts of bad things can happen, but is there anything with essentially allowing users to enter/execute this kind of javascript command? If so, how do you propose I get around this situation. I'd really enjoy making this educational game, so any help is greatly appreciated. I can't really see any way it could be dangerous because it's all run on the client's computer right..? I don't know though, maybe I'm missing something
Thanks

Security problems may arise if you allow users to use other users' Javascript, however if the only person who is executing code is the person who is entering it, then you should be alright.

Anything on the client-side is always susceptible to changes done by the end-user.
However, if you aren't saving anything information to a database and there aren't any competitive conditions with regards to this game, I would not worry about any security issues that may arise. You can always sanitize client input within your own Javascript to ensure that non-technical users may not change game states during the process.

It's no different than Javascript, the only vulnerability would be if someone was able to inject some code into your app or database which in result displays the content served on your web server. As long as your app is protected against XSS and SQL Injections, you should be fine, it would be the same concept.

Related

What are some ways to make it harder for the client to manipulate the DOM?

I am going to be processing a lot of form data from the client using Ajax. Right now, my way of validating input is to add a 'validate' class to each form control that needs to be checked. When the user enters information (or submits the form) the script looks at the input of each control with that class and verifies its contents before moving to the next tab (or sending it to the server). The issue, of course, is that a user can easily remove the class and the item wouldn't be looked at.
While I will of course be validating the input on the server-side (client data can never be trusted!), a lot of the user-side content generation [new inputs, dynamic forms, removing/adding validate classes, etc.] depends on people not tinkering with the classes. While I know that the client can ultimately do whatever they want, what are some ways to make this process difficult for the client to manipulate?
So far I have thought about:
Running a script at the beginning of the page load that grabs all the HTML inputs with the 'validate' class and stores them in a variable. When the user submits the data or moves to the next tab, instead of looking at the elements with the class 'validate', I instead look to validate the data compared to the contents of the variable.
Adding data-validate HTML attributes to each input and doing the same thing as above (running a script and grabbing the inputs that need validation before the client has time to tinker with the settings)
Is there anything else that can be done? I am a little hesitant to use the above approaches because there may be new, dynamically generated form elements that need to be added/removed to the list; and this + grabbing the data at the beginning of the page load could cause a little unnecessary overhead.
"While I know that the client can ultimately do whatever they want..."
You just answered your question. If that's your starting point, why are you trying to make it harder? Is it worth my while to actually try to hack your site? If it is, I don't care that it's harder. Also, how hard can it be? Are you going to make it so hard to figure out the JavaScript that the next developer who looks at this code also won't be able to figure out what's going on?
Also, you're adding more code. Have you ever written code without bugs? I haven't. So, guaranteed, there are going to be bugs in this thing. So, in the off chance that 1 in a million users might try doing something bad, you'll end up stopping lots of legitimate users who get errors when they're using the site like they should.
Client side checking is ONLY meant to be nice to the end user, to give them immediate feedback. Period.
Might not be the answer you like, but it is the answer. :)
Edit: One last comment. Let's say you did make it REALLY hard. Would you then not do server side checking? Would you say to your boss, "Oh, we made it pretty hard to hack on the client side. They still can. We just made it hard. So no need to do server side checks." Of course not. So, if you're doing server side checks no matter what, you don't gain anything from trying to obfuscate on the client side.

Prevent user-entered scripts from running in webpage

In my application, there is a comment box. If someone enters a comment like
<script>alert("hello")</script>
then an alert appears when I load that page.
Is there anyway to prevent this?
There are several ways to address this, but since you haven't mentioned which back-end technology you are using, it is hard to give anything but rough answers.
Also, you haven't mentioned if you want to allow, or deny, the ability to enter regular HTML in the box.
Method 1:
Sanitize inputs on the way in. When you accept something at the server, look for the script tags and remove them.
This is actually far more difficult to get right then might be expected.
Method 2:
Escape the data on the way back down to the server. In PHP there is a function called
htmlentities which will turn all HTML into which renders as literally what was typed.
The words <script>alert("hello")</script> would appear on your page.
Method 3
White-list
This is far beyond the answer of a single post and really required knowing your back-end system, but it is possible to allow some HTML characters with disallowing others.
This is insanely difficult to get right and you really are best using a library package that has been very well tested.
You should treat user input as plain text rather than HTML. By correctly escaping HTML entities, you can render what looks like valid HTML text without having the browser try to execute it. This is good practice in general, for your client-side code as well as any user provided values passed to your back-end. Issues arising from this are broadly referred to as script injection or cross-site scripting.
Practically on the client-side this is pretty easy since you're using jQuery. When updating the DOM based on user input, rely on the text method in place of the html method. You can see a simple example of the difference in this jsFiddle.
The best way is replace <script> with other string.For example in C#use:
str.replace("<script>","O_o");
Other options has a lot of disadvantage.
1.Block javascript: It cause some validation disabled too.those validation that done in frontend.Also after retrive from database it works again.I mean attacker can inject script as input in forms and it saved in database.after you return records from database in another page it render as script!!!!
2.render as text. In some technologies it needs third-party packages that it is risk in itself.Maybe these packages has backdoor!!!
convert value into string ,it solved in my case
example
var anything

Make JS Code unreadable/heavy to "hack"

I want to write a little game where the users has to click on appearing elements/objects in a given time. In detail the objects appears in holes onto the ground and after x seconds the objects disappear. The gamer has y lifes and all clicks gets counted until he lost the game.
After that his highscore gets posted to a database (via form post or AJAX). Long story short how can I avoid the user faking his highscore before sending? The program language is JS.
I know its not possible to hide all the code and make it not hack-able. But I think it's enough if the code is so difficult that the user has to do a lot of work to understand where he has to intervent to send faked data.
Has anybody some ideas howto make the code as difficult as its possible?
Thanks in advance for any ideas :)
You should never really try to make your source code unreadable. It will make as great a headache for yourself than any obstruction to anyone modifying it.
That said, you could refactor all your variable names to complete gibberish and play with whitespace, but anyone seriously trying to understand your code could revert that in a decent text editor. To make it any more complex would take away from the efficiency of your program - otherwise you could fill it with useless calls to functions that don't do anything and strange incrementation of counters that the program does not depend on.
there are compressors that do exact the job you want! Some of them can be downloaded and used as offline tools, some are directly via web accessible:
http://javascriptcompressor.com
like jquery and others you can use your code to maintain the scripts and deliver a faster loadable packed version that is hardly readable
How about this:
Create two PHP pages, with one containing the game interface and the other containing the game's code. Program the first one so that it creates a one-time-use string that the tag will pass along as a parameter when it calls the JS code from the second one. Program the second one so it checks the validity of the string sent. If the string is valid, the script should output the JS code, then invalidate the string.
Then, when the user copies the URL of the script, pastes it into his browser, and hits "Return," all he sees is either a blank page or a "not authorized" message.

Is it possible to use JavaScript to break the HTML of a page?

I've been asked at work whether it is possible to write, on purpose or by accident, JavaScript that will remove specific characters from a HTML document and thus break the HTML. An example would be adding some JavaScript that removes the < symbol in the page. I've tried searching online and I know JavaScript can replace strings, but my knowledge of the language is negligible.
I've been asked to look into it as a way of hopefully addressing why a site I work on needs to have controls over who can add bespoke functionality to the page. I'm hoping it's not possible but would be grateful for the peace of mind!
Yes, and in fact you can do things far more insidious with javascript as well.
http://en.wikipedia.org/wiki/Cross-site_scripting
yes, thats possible. the easiest example is
var body = document.getElemetsByTagName('body')[0];
body.innerHTML = 'destroyed';
wich will remove the whole page and just write "destroyed" instead. to get back to your example: in the same way it's possible to replace <:
var body = document.getElemetsByTagName('body')[0];
body.innerHTML = body.innerHTML.replace('<','some other character');
such "extreme" cases are very unlikely to happen by accident, but it's absolutely possible (particularly for inexperienced javascript-developers) to break things on a site that usually shouldn't be affected by javascript.
note that this will only mess op the displayed page in the clients browser and doesn't change your html-file on the server in any way. just find and remove/fix the "bad" lines of code and everything is fine again.
Any client/browser can manipulate how the page is viewed at any time, for instance in chrome hit F12 and then you can write whatever you want in the html and you will see the changes immediately. But that's not to worry about...
The scary part is when JavaScript on the site communicates with the back-end server and supplies it with some input parameters that are not being sanitized on the server side before it is processed in some way. SQL Injection can also happen this way if the back-end utilizes a database which they almost always do, and so on...
A webpage can be manipulated in two ways, either its none-persistent or its persistent.
[none-persistent]: this way you can manipulate your access to a webpage but, this won't affect other users in it self, but you can do harm once your in.
[persistent]: this way the server side code will permanently be affected by the injected code, and most likely affect other users.
Key thing here is to always sanitize the input a back-end server used before it processes anything.
You could definitely write some javascript function to modify the contents of a file. If that file is your HTML page, then sure.
If you want to prevent this from happening, you can just set the permissions of that HTML file to be read-only, though.
you could:
Overwrite the page,
Mess with the innerHTML of the body tag (almost the same),
Insert illegal elements.
Yes. In the least, you could use it to write CSS that sets any element, class, ID... even the body to display:none;

JavaScript non-persistent security question

Despite my paranoia I've never really gotten around to understanding web security more, so my lack of knowledge is causing me a bit of confusion for this.
Example: Let's say you have 2 text boxes, both are for user input.
The user types in whatever they want into those two text boxes and clicks a button, the button then uses a bit of JavaScript and concatenates whatever is in those two text boxes and displays it out in a div.
My question is, in this case, since it's using JavaScript client side, do you need to really sanitize user input?
What if it outputted to a text box instead of a div? Or as an alert?
I understand that when it comes to forms/PHP you always want to sanitize input, but I'm not really familiar with JavaScript security precautions.
It's my understanding that since this is client-side, and no data is being saved by the server, that whatever the user does (tries to throw in some malicious code or whatnot) won't affect anyone but that user, correct?
No this is not a security issue. The reason why is because an attacker has to force a victim's the browser into making this action in order for it to be XSS.
However, if you grab input from something like document.location and then print it to the page using document.write() then this is DOM based XSS. But this is very a uncommon form of XSS.
You don't have to sanitize anything that is not going to the server.
If people want to do something to their instance of your page, the only one they can hurt is themselves. Look at everything you can do with an extension like GreaseMonkey ... we're talking a lot more than just concatenating strings and displaying them.

Categories