javascript security: prevent user from calling function from console? [duplicate] - javascript

I allow my users to favorite an update or a forum topic.
So when a user tries to favorite one of these i will send via Ajax 2 things, the item_id(update or topic) as id(ex. 1321313213) and its type("update" or "topic") as string.
However lets say someones tries to favorite an update with the id untouched but the type is changed to "topic"(via firebug or whatever else)...
This should not procceed since this combination is not correct... how can i assure that the item_id being sent is an update or a topic since this ID might co-exist in both tables???
Current solution:
Create a hidden input element and add as value 5 random characters (a-zA-Z0-9) and md5 type name(update or topic)
like:
$random_str = $this->my_model->generateRandomString(5);
<input type="hidden" value="<?php echo $random_str.md5("update"); ?>" id="type" />
so when i try to validate the data to check if it is an update or topic i split the type on the first 5 characters and later and check if the later characters are md5 hashed are update or topic and continue validation
I would like some help in case this can be altered as well...

Your server side script (PHP) must always assume it's getting bogus data. Never rely solely on javascript to handle any sanitization / verification.
If your javascript can determine if the job should be "update" or "topic", I'm sure your PHP can do that as well. Probably using a few more DB queries or some such, but that's the price you've got to pay.

Your are looking at the problem from the wrong perspective. Especially from You server side (PHP) code.
Your server gets data. It gets data which is something like that: user (from session), id and type. Your server needs to ask a question: is it valid data? If it is -- save it to DB; If it is not -- do not save it to DB. It is that simple.
You can look from this perspective: Your client side code is just one way to communicate with Your server. Another way is using web browser + firebug. It is perfectly valid usage of Your server side application. And Your PHP code should not care how request reaches it.
So if Your current code does not allow You in Your PHP code feel comfortable and freely decide if is it update or topic creation than Your need to change Your server side code (and perhaps DB schema) as well.
Your current solution is not good, because if I know how to use firebug I would probably find out that "9d9b68ac2b1de18d3712096354b3c3a5" means "topic" and "3ac340832f29c11538fbe2d6f75e8bcc" means "update".
I think Your are trying to invent Your own CSRF protection. So go on Internet and read about it.

Related

Quiz application in .NET MVC/JS/JQUERY, how to prevent cheating?

I'm making a quiz application, where 4 users join a lobby (finished), and then the leader starts the quiz.
When the quiz is started, questions get randomly selected. Users can answer them, and click submit. Each question is timed, meaning user only has 10 seconds to answer the question.
This is all done through AJAX, since I want the website to be real-time. How exactly would I prevent cheating? User could manually edit the JS file, etc.
I was thinking of getting the exact time when the question gets loaded + the answer time. And if it's not in the span of 10 seconds, he's cheating. Would that work, or is there a better and easier way to do this?
Thank you.
Edit
I thought AntiForgeryToken was right solution to solve your problem. I read a lot of articles to make sure my old answer is correct.
1- Hiding or Encrypting the javascript source code
2- How to Disable HTML view source or Encrypt Html elements programatically?
3- How To Prove That Client Side Javascript Is Secure?
4- ASP.NET MVC - does AntiForgeryToken prevent the user from changing posted form values?
I came to the conclusion:
AntiForgeryToken prevents a malicious site to trick a user to a form that looks the same as the original and post it to the original site. It does not prevent the scenario you are describing.
There's really no way to do this completely client-side. If the person has a valid auth cookie, they can craft any sort of request they want regardless of the code on the page and send it to your server.
You can use HtmlHelper.AntiForgeryToken with salt value.
To use these helpers to protect a particular form, put an Html.AntiForgeryToken() into the BeginForm, e.g.,
#using (Html.BeginForm("Users", "SubmitQuiz"))
{
#Html.AntiForgeryToken()
<!-- rest of form goes here -->
}
This will output something like the following:
<form action="/Users/SubmitQuiz" method="post">
<input name="__RequestVerificationToken" type="hidden" value="saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs" />
<!-- rest of form goes here -->
</form>
Next, to validate an incoming form post, add the [ValidateAntiForgeryToken] filter to your target action method. For example,
[ValidateAntiForgeryToken]
public ViewResult SubmitQuiz()
{
// ... etc
}
Salt is just an arbitrary string. A different salt value means a
different anti-forgery token will be generated. This means that even
if an attacker manages to get hold of a valid token somehow, they
can’t reuse it in other parts of the application where a different
salt value is required.
You can create different salts for different users like this.
Edit
AntiForgeryToken() prevents tampering with the code using inspection tools like this:
In Client side
1- A new random anti-XSRF token will be generated.
2- An anti-XSRF field token is generated using the security token from step (1).
In Server side (Validating the tokens)
1- The incoming session token and field token are read and the anti-XSRF token extracted from each. The anti-XSRF tokens must be identical per step (2 client side) in the generation routine.
2- If validation succeeds, the request is allowed to proceed. If validation fails, the framework will throw an HttpAntiForgeryException.
For more information this, Please see this article.
Conclusion: Since there's no way to prevent anything on the client side, the only solution that actually sounds okay is having server check everything.
A GET request, which requests the question and logs the time. After that, a JS timer which automatically submits the question if the countdown is finished. The user can also manually submit the answer (obviously). POST of the answer, and the server logs the time of it, compares it to the initial time of the GET request. If it's longer than 10 seconds, it throws and error, and the answer is not counted.
Thank you everyone.

Is it possible to write ColdFusion statement within Javascript? [duplicate]

Can I use ColdFusion tags in JavaScript? For example:
<script language="javascript" type="text/javascript">
function validateUser() {
var userName = document.getElementById("username");
<CFQUERY DATASOURCE="mydatasourcename" NAME="getUser">
select USER_ID,COUNT(*) from user u
where u.firstname=userName;
</CFQUERY>
<cfif getUser.recordCount EQ 0>
<!--- Show eroor message --->
<cfelse>
<!--- Assign userId to hidden field --->
document.getElementById("userid").value=#USER_ID#
</cfif>
}
</script>
<input type='textbox' name='username' id='username' onblur=validateUser()/>
<input type='hidden' name='userid' id='userid'/>
When the end user enters their username, I would like to check in a database if this username exists or not. If it exists, I have to keep the userid in the hiddenfield or else throw an error.
Am I doing this correctly? If it is wrong, could you suggest the correct way?
Long version: http://blog.adamcameron.me/2012/10/the-coldfusion-requestresponse-process.html
Short version: no, you're not doing it right.
Mid-sized StackOverflow-friendly version: CFML code runs on the server side of a request; JavaScript runs on the client browser. And to be clear: the ColdFusion server never communicates with the browser directly at all: there's a web server in between. The client browser requests a file, the web server is configured to pass .cfm requests to the ColdFusion server, and it runs its code, returning the resulting string (eg: an HTML web page) to the web server which then returns that to the browser. That HTML might include JavaScript (inline or as external requests) which the browser will then execute.
Hopefully from that you can see that there's no direct interaction between server-side code and client-side code.
You have two facilities at your disposal to get the two communicating asynchronously though. Firstly: CFML code writes out text, but that text can be JS which the browser then runs when it finally receives it. Something like:
<cfset msg ="G'day world">
<script>alert("<cfoutput>#msg#</cfoutput>");</script>
Once the CFML server has processed that, what gets sent back to the browser is:
<script>alert("G'day world");</script>
In this way server-side code data can be used in client-side process if the server-side code "writes out" the data as part of its response. The example above is very trivial and not a "good practice" way of going about this, but it demonstrates the technique.
If you need to use JS code on the client to communicate back with the server, your only (real) recourse is to make an AJAX request back to the server to pass it client-side information for further server-side processing and for the server to respond with something. It is outwith the scope of your question to explain how best to do this, but there is a tonne of information out there to do this.
CFML provides some "wizards" to write HTML and JS out for you to facilitate this, but on the whole this is a bad approach to achieving this end, so I will not recommend it. However I will point you to a project which offers HTML/JS/CSS solutions to the inbuilt CFML wizardry: https://github.com/cfjedimaster/ColdFusion-UI-the-Right-Way
Back to the short answer: no, you cannot do what you are setting out to do for very good reasons, but if you revise your approach, you can achieve the ends that you want.
What you need to look at is passing the form fields back to the server via AJAX (jQuery makes this very easy), and run your <cfquery> code in a separate request.
If you read that blog article I mention from the outset (discloure: I wrote it, but I wrote it specifically for situations like this), then you'll understand why.
If you get stuck when working on part of your solution: raise another question more focused on whatever part you are stuck on.

How to ensure HTML input remains required?

If you create a form using HTML inputs and make the input required using the "required" attribute (<input type="text" required>), what is stopping a user from manually deleting the attribute by using their web browser's built in developer tools or by loading JavaScript by some other means (such as a bookmarklet)?
In other words, how can you ensure the required input remains required?
The client/browser has little control over the request that is sent to the server. A request can be constructed and passed to the server without involving a browser, therefore its the server side code's responsibility to ensure that the required parameters were provided with the request (as well as validate the parameters).
You need to consider a few things:
Everything on the client side can be modified by the client: nothing is stopping me from using my browser console or modifying the source code to change parts of your page, and you can't do anything to stop that. For instance, look how many upvotes your question has:
Obviously that doesn't actually do anything, but that's because all of the heavy lifting is done by Stack Exchange's servers.
Even if you make a field required, people can still fill in the field with a space or asdf and move on. Just because input is required doesn't mean that it is valid.
So, with that in mind, realize that you'll need to work on the server side to validate input. People can't mess with servers (easily) and it's the safest way to validate input. You'll need to deal with validation when your server receives the data because the client side is always vulnerable to user modification.

How to keep track of fields on a web-app

Take Facebook's reply-to-status as an example. When you replies to someone's status, does the script looks into the DOM of that status for the ID of that status, and send an Ajax to update the entry with that ID?
If that's the case, couldn't you just modify the ID and pollute the data
P.S. as a followup, I've seen a client-side MVC implementation, Backbone.js, that manage things like the above w/o the use of any ID, which I still haven't figured out how.
http://documentcloud.github.com/backbone/docs/backbone.html
Here is the source, the relevant code 'view' starts at last 1/4
It will still verify that it's a valid id on the server side, that you have permissions to follow up to that user's statuses, etc.
Yes you can, but keep in mind it's all session/friends list/permissions based too.
There are still checks involved on the server regarding "does user A have access to making a comment on user B's action". Assuming you type a bogus ID, it still needs to be verified you can post on the (spoofed) ID.
If you can, you just made a post on a completely separate topic which is now presumably out of context.
If you can't the post doesn't go through and no worries.
What it comes down to is that the UI is a "convenience" check. There's not real integrity to validating other than gently guiding the user to travel the correct path. The server is where the real protection is because, as every real programmer knows, the user can not be trusted.

gwt javascript checking php

i am using gwt.
i need to check some input data.
all checking functions are located in PHP server check.php
i am not using javascript checking executed from locally.
all i am doing is to send user input to server by ajax and validate in that place
and error message comes from server to client's gwt widget.
is it best approach??
i can do all checking from locally.but not doing.because server side is importent.
all checks must be resides in server so i am doing all checking from server.
if i do check locally and serverside two times ,then will it be best approach??
What you'll want to do is:
Use this account the next time you come back, or any of the others you've created, instead of creating an account each time you come to the site. Avoid this mess.
Create a .php page that accepts JSON-encoded data that you'd like to verify, and respond with some text like "OK" if it's valid. (I'm no PHP expert, but I'm sure there are plenty of them here)
Use GWT's RequestBuilder to send this data to the .php page, and call the RequestCallback's Response's getText() method. Check if the text is "OK" -- if so, the result is valid!
If you need more detail on any of the specifics, just let me know and I'll edit to clear things up.
Generally I agree with Jason (especially the with the first point :D).
I'd like to add that you should do validation on the client side first. Why? Because it allows you to weed out some obviously wrong inputs => less load on the server. But never accept the values from the client, just because your JS code said so - the general rule is to never trust the client side (because, well, it's the client side and the client can change the way your code works).
So in summary, I usually take these steps in my apps, they offer security and lower the load on your server, but may require a bit more work to write and maintain (especially if your client side and server side use different languages):
Validate input client side. If it doesn't pass, don't bother sending it to the server, just show an appropriate message.
If it does pass, send it to the server, but you must rerun the validation on the server side too.
If the server side validations report an error, send it back in some form (JSON with the error message and/or error code, set a HTTP response code, etc).

Categories

Resources