Best method to submit content with jQuery - javascript

Maybe you can help me understand some pretty basic stuff here. I am new to jQuery and web in general (though I have a lot of winforms / win32 experience). I have a website that runs on Google App Engine and uses Django and jQuery. The website is used to order a service. It has three forms:
A form in which you describe yourself (e.g you input name, address and so forth) you click next and then the following form appears:
A form in which you input the info of the service you want, such as service name and date. this form needs to display the data you entered in the previous form (form 1) in case you forgot something. you click next, and then the system needs to save all the data you wrote so far, and process your request for a service (this is done at the server side). this form is now displayed:
A form which shows a summary of your service request (and allows you to do other things such as sending the info to other people and so forth).
How would you transfer the data from form 1 to form 2 and then to the server? POST? is this safe? how will you do this in code? is there a way to transfer JS objects?

Make one form in one page and using JavaScript display sections of the form as needed. As far as submitting form values is concerned, you can either submit directly to script via form attribute action="...script url..." , or if you choose to employ AJAX you can use JavaScript or use jQuery's $.post().

This is a pretty open ended question.
So I'll start with one of the unnumbered questions first: "Is this safe".
The quick answer is probably no.
Here's some examples of how to answer that question:
Example:
I want to make a javascript app that
can collect data. I will hold all
data in this javascript object.
1: Is this safe. 2: No it's not, it
can be manipulated by anyone with a
browser.
Example 2:
I will just transmit that stuff via GET or POST to my
server and then mess with it there.
1: Is this safe. 2: No it's not, I
don't really get how stuff is stored
and my ignorance will cause my data to
get stolen.
Example 3:
I totally understand my server and my
initial page.
1: Is this safe. 2: No it's not,
unless all of my data is transmitted
over SSL/TSL it is widely available to
nefarious uses.
Example 4:
I have an SSL service and I understand
everything about my data transmission. I need to
store my information to retrieve it later.
1: Is this safe. 2: No it's not. I am using Google App engine so I'm just a trusting individual OR I'm using S3 and I trust them. or I'm using a sql server with whatever os and I trust those vendors, etc.
Example 5:
I feel ignorant that I just blindly
trust my vendor.
1: Is this safe? 2: No it's not.
(Obviously)
All that said you're using a Google App Engine backend so there's a ton of help on this.
Sorry it's my birthday and your question caused me to wax philosophically while I waste the day at work.
But remember, the prudent answer to "Is it safe" is always "No"

Related

Hiding my admin login information HTML

I'm pretty new to HTML, like 1 week new. I am making a web store and I want to be able to login into an "admin panel" to make it easier for me to manage my products. Add new, remove, rename etc. My problem is, I have my login information stored in the html code and I use if-statements to check the validity.
When I was testing the code, I was curious and wanted to inspect element. Unsurprisingly, there was my entire login information and anybody can have access to it.
I need to somehow hide it, or hide the login fields from users except me. But I do not know how to approach that. I thought of a few solutions like have a hidden part on the store page and if I click it a certain amount of times then it will show the fields. But I think I'm complicating it.
Any ideas are greatly appreciated. Thanks. Below is my function for logging in.
function login()
{
var username = "test username";
var password = "testpassword";
if(document.getElementById("username field").value == username && document.getElementById("password field").value == password)
{
var btn = document.createElement("BUTTON");
document.body.appendChild(btn);
<!-- hide the user name field after login -->
document.getElementById("username field").hidden = true;
<!-- hide the password field after login -->
document.getElementById("password field").hidden = true;
<!-- hide the login button after login -->
document.getElementById("login btn").hidden = true;
<!-- show a message indicating login was successfull -->
window.alert("Login successfull! Welcome back admin!")
}
else
{
window.alert("Sorry, you are not authorized to view this page.");
}
}
And this is a screenshot of the inspect element. I don't want anything too crazy like a database because I'm the only user, just a way to be able to access the admin panel without exposing myself. Thanks again.
Inspect Element Screenshot
EDIT:
I am not using my own server, I am using Wix.com to make the initial website and then using the HTML widget to create a webstore. I don't think they allow people to have any communication with their servers whatsoever.
Username and password validation should never be done on the client side. It should always be done on the server. Do not use javascript for this task. Allow your user to enter their username and password in a form, and then submit the form to a server side script to validate their credentials. Doing it on the client side will never be secure.
There's no easy solution to your particular request, but before I oblige you with the details I'd like to stress three very important points.
1: Javascript is not Safe
Javascript is a client side language, which means every piece of data you'll ever be dealing with that comes from your user can be directly modified. These include, but are not limited too, any values or attributes of HTML tags, inline Javascript, loaded image files, etc. Essentially, anything that is cached on the user's computer can be modified and might not be what you're expecting to receive.
As such, a Javascript authentication system is absolutely not safe by any definition of the word. For a local page that only you can access, it would do the job, but that begs the question of why you need authentication in the first place. Even then, as a new developer you'd be widely encouraged to never try do it anyway. There's no point practising and learning how to do something in a completely insecure way and nobody is likely to suggest it.
2: Authentication is a tricky topic
Authenticating logins is not an easy thing to do. Yes, it's easy to make a login script but it's not easy to do it properly. I would never try to discourage anyone from making something themselves nor discourage a new developer from pursuing any goal, but authentication is not something you should be learning only a week into HTML. I'm sorry if that comes across as harsh, but there are people who have been masterminding applications for years who still don't do it securely.
3: Third Party are Best
It's possible to make your own authentication system that likely only the most determined of attackers could access, but it wouldn't involve Javascript authentication. Consider Javascript to be more of a convenience to the user than a solution for the developer. Javascript can do some remarkable things, but being a trusted source of data is something it will never do. Please understand this important point, because the source code you have provided is riddled with security flaws.
--
Now, on to what you want to do. Identifying that you're the "admin" user is something you're putting a password in to do. If you could figure out you're the owner of this site before putting in your password, you wouldn't need the password, right? In short, you can't do what you want to do; not reliably, anyway. It's possible to only show those forms if you're using a particular IP, but IPs can be masked, imitated and changed, which makes it insecure.
There are several third party authentication methods that you can use to do all the heavy lifting for you. All you do is put the fields on your page and they'll handle the rest. You can use any Social Media login (Facebook, Twitter, Google Plus, etc) or you can use O Auth, which deals with all the heavy lifting of authentication for you.
I don't mean to discourage you, nor anyone else, from pursuing their own authentication methods but if I'm honest with you I think this is something way beyond your skill level that you shouldn't be considering right now.
If you serve the pages via a server, you can enforce basic HTTP auth. Should be really simple to set up and you would have the benefit of a standard of security.
Here are the Apache docs for this, for example.

Fail-safe way to validate forms in Javascript/Ajax rather than PHP?

Ok, so currently I handle all HTML form submissions in PHP. I submit the form to a PHP file which:
Checks against a cookie created at page load to prevent CSRF.
Contains a require_once() that handles validation.
Runs other logic.
If any of these steps fail, the user is redirected in PHP to the page they came from with an error message.
How I submit the form:
<form method="post" action="filename.php">
This system is fail-safe; as if anything goes wrong, the user is returned to the page they came from even with Javascript disabled.
So my question is; can I create a fail-safe system using just Ajax (an Ajax request to the server on form submission)? So that I don't need this PHP system at all? Is there a recommended procedure/tutorial for this?
I've avoided this so far as the overhead of having both a PHP form handling system as a fail-safe for potential hackers, as well as Ajax, can take several hours per form.
Just to clarify, I don't require support for users that have Javascript disabled. I just want to make sure my system if fail-safe in that situation. I've had a good look around, but it's proving difficult to find clarification on this.
The short answer for the most part is: no.
It is unwise to consider anything client-side as reliable or fail-safe, this is especially true when it comes to validating user input. A rule of thumb is: never trust the user.
Currently, per the description, your form is being submitted to a PHP script that validates form data. This way is going to be your best line of defense since you have a large amount of control on the data you are working with.
It sounds like you want to cut out the form submission and not force another page load. You can use AJAX to pass form information for validation to your script, but your PHP code is still going to be crucial to the validation process.
Basically you want to make your PHP validation solid. Next, start adding some AJAX calls that pass information from forms to your PHP code, but be prepared to fall back to standard form submission if AJAX is unavailable. If there are no problems with AJAX, you can still submit the data, have PHP do its processing, then return a payload indicating success or failure. Keep in mind though, in this context AJAX is just some sugar for the validation. You are only sweetening the deal by saving yourself having to reload a page and transfer the entire document again.
But remember: it is not reliable, and it is not fail-safe. Server side validation is the light at the end of the tunnel.

How "secure" is the ASP .NET Controller

I am still very new to the concepts and design of ASP .NET's MVC and AJAX and I was wondering how secure the Controller is to unwanted user's when webdeployed.
I ask because for fun I made a little admin panel that requires a user name and password. Once input is entered the information is AJAX submitted to a ActionResult method in the Controller that just compares the strings to see if they match, then returns the response back to the AJAX.
My question is, how easy is it for someone to get into my Controller and see the hard-coded password?
No professional-type person will ever try to break into this, as it is a free site for a university club, but I want to make sure that the average Computer Science student couldn't just "break in" if they happen to "rage" or get mad about something (you never know! haha).
Question: Is having a password validation within the Controller "decently" secure on a ASP .NET MVC web-deployed application? Why or why not?
Here is the actual code in case the use of it matters for the answer (domain is omitted for privacy)
Note: I understand this use of Javascript might be bad, but I am looking for an answer relative to AJAX and Controller security of the password check.
View (Admin/)
//runs preloadFunc immediately
window.onpaint = preloadFunc();
function preloadFunc() {
var prompting = prompt("Please enter the password", "****");
if (prompting != null) {
$.ajax({
url: "/Admin/magicCheck",
type: "POST",
data: "magic=" + prompting,
success: function (resp) {
if (resp.Success) {
//continue loading page
}
else {
//wrong password, re-ask
preloadFunc();
}
},
error: function () {
//re-ask
preloadFunc();
}
});
}
else {
// Hitting cancel
window.stop();
window.location.replace("google.com");
}
}
Controller (ActionResult Snippet)
[HttpPost]
public ActionResult magicCheck(string magic)
{
bool success = false;
if (magic == "pass")
{
success = true;
}
else
{
success = false;
}
return Json(new { Success = success });
}
Again I am new to MVC and AJAX, let alone anything dealing with security so I am just wondering how secure the Controller is, specifically on webdeploy for this simple password setup.
During normal operation, there is no concern as your code is compiled, the DLL prevented from being served, and there is no way for the browser to request the controller to divulge its own code.
However, it is not impossible (but quite rare) that unforeseen bugs, vulnerabilities, or misconfigurations of the server could lead to the server divulging compiled code, web.config, etc., whereby someone could disassemble the code (IL is easily decompiled) and reveal your secret.
More worrisome would be someone having physical access to the server just grabbing the binaries directly and disassembling to find your secret.
Another thing to consider is who, during normal situations, might see that secret and whether or not they should know it. A developer, tester, or reviewer may be allowed to write or inspect code, but you may not want them to know the secret.
One way to handle this is not store secrets in plain text. Instead, create a hash of the valid value, then update your application to hash the user's input in the same manner, and compare the results. That way if the user ever gets your source code, they can't read the original plain text value or even copy/paste it into your UI. You can roll your own code to do the hashing, use the FormsAuthentication API, or something else.
Finally, do not rely on client-side enforcement of security. You can check security on the client side to have the UI react appropriately, but all server-side requests should be doing checks to make sure the user's security claims are valid.
The question really goes out of scope from here, regarding how to manage identities, passwords, and make security assertions. Spend a little time looking through the myriad articles on the subject. Also, the Visual Studio ASP.NET project templates include a lot of the security infrastructure already stubbed out for you to give you a head start.
Never leaving things to chance is an important policy. Learning about ASP.NET and MVC's various facilities for authentication and authorization is a worthwhile effort. Plus, there are numerous APIs you can plug in to do a lot of the heavy lifting for you.
As has already been pointed out if you can get a hold of the binaries for an app (or for that matter ANY .NET application not just MVC) then it's definately game over.
Just sat in front of me here and now I have 3 applications that make it child's play to see what's inside.
Telerick - Just Decompile
IL-Spy
Are both freely downloadable in seconds, and the former of the two will take an entire compiled assembly, and actually not just reverse engineer the code, but will create me a solution file and other project assets too, allowing me to load it immediately back into Visual Studio.
Visual Studio meanwhile, will allow me to reference the binaries in another project, then let me browse into them to find out their calling structure using nothing more than the simple object browser.
You can obfuscate your assemblies, and there are plenty of apps to do this, but they still stop short of stopping you from de-compiling the code, and instead just make the reverse engineered code hard to read.
on the flip side
Even if you don't employ anything mentioned above, you can still use command line tools such as "Strings" or editors such as "Ultra Edit 32" and "Notepad++" that can display hex bytes and readable ASCII, to visually pick out interesting text strings (This approach also works well on natively compiled code too)
If your just worried about casual drive by / accidental intrusions, then the first thing you'll want to do is to make sure you DON'T keep your source code in the server folder.
It's amazing just how many production MVC sites Iv'e come accross where the developer has the active project files and development configuration actually on the server that's serving live to the internet.
Thankfully, in most cases, IIS7 is set with sensible defaults, which means that things like '*.CS' files, or 'web.config' files are refused when an attempt is made to download them.
It's by no means however an exact science, just try the following link to see what I mean!!
filetype:config inurl:web.config inurl:ftp
(Don't worry it's safe, it's just a regular Google Search link)
So, to avoid this kind of scenario of leaking documents, a few rules to follow:
Use the web publishing wizard, that will ensure that ONLY the files needed to run end up on the server
Don't point your live web based FTP root at your project root, in fact if you can don't use FTP at all
DO double check everything, and if possible get a couple of trusted friends to try and download things they shouldn't, even with a head start they should struggle
Moving on from the server config, you have a huge mountain of choices for security.
One thing I definitely don't advocate doing though, is rolling your own.
For years now .NET has had a number of very good security based systems baked into it's core, with the mainstay being "ASP.NET Membership" and the current new comer being "ASP.NET simple membership"
Each product has it's own strengths and weaknesses, but every one of them has something that the method your using doesn't and that's global protection
As your existing code stands, it's a simple password on that controller only.
However, what if I don't give it a password.
What happens if I instead, decide to try a few random url's and happen to get lucky.
eg: http://example.com/admin/banned/
and, oh look I have the banned users page up.
This is EXACTLY the type of low hanging entry point that unskilled script kiddies and web-vandals look for. They wander around from site to site, trying random and pseudo random URL's like this, and often times they do get lucky, and find an unprotected page that allows them to get just far enough in, to run an automated script to do the rest.
The scary part is, small college club sites like yours are exactly the type of thing they look for too, a lot of them do this kind of thing for the bragging rights, which they then parade in front of friends with even less skill than themselves, who then look upon them as "Hacking Heroes" because they broke into a "College Site"
If however, you employ something like ASP.NET membership, then not only are you using security that's been tried and tested, but your also placing this protection on every page in your site without having to add boiler plate code to each and every controller you write.
Instead you use simple data annotations to say "This controller is Unprotected" and "This one lets in users without admin status" letting ASP.NET apply site wide security that says "NO" to everything you don't otherwise set rules for.
Finally, if you want the last word in ASP.NET security, MVC or otherwise, then go visit Troyhunt.com I guarantee, if you weren't scared before hand, you will be afterwards.
It looks like you are sending a password via AJAX POST. To your question, my answer would be that you should consider using SSL or encrypt the password prior to sending it via POST. See this answer for an example and explanation SSL Alternative - encrypt password with JavaScript submit to PHP to decrypt
As HackedByChinese said, the actual code being stored in your compiled files (DLL) wouldn't be too big of a deal. If you want to be extra paranoid, you can also store the password in your web.config and encrypt it there. Here's an example and explanation of that How to encrypt username and password in Web.config in C# 2.0
This code is not secure at all. Your JavaScript code can be replaced with EVERYTHING user wants. So someone can just get rid of your preloadFunc. Average computer sience student will execute this code directly from console:
if (resp.Success) {
//continue loading page
//this code can be executed by hand, from console
}
And that will be all when it comes to your security.
Authentication and authorization info should go to server with every request. As a simple solution, you could use FormsAuthentication, by calling
FormsAuthentication.SetAuthCookie("admin")
in /Admin/magicCheck, only if password is correct.
Then you should decorate data retrieval methods with [Authorize] attribute to check if cookie is present.
Using SSL to secure communication between browser and server would be wise too, otherwise password travels in clear text.

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

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.

Comparison of simple User Regeistration by PHP and Javascript

A simple user registration may be completed by PHP (framework: Codeigniter,etc..) and Javascript.Following is simple flow:
PHP
A registration view with form input(user_name,e-mail,password)
post the data to an controller to validation
-Pass, redirect to a completion view
-Failed, go back to the registration view with some alert strings.
Javascript
A registration html with input text(user_name,e-mail,password)
Validation could be done by Javascript directly before submit; Alert strings could be
generated by Javscript. Even submission could be done by ajax. Then redirect to the
completion page.
I found myself code more javascript less PHP. Even the user registration could be done without the "form" tag,right? I am afraid of some parts I had miss or ignore.
Could someone gives me an simple comparison of good/bad parts about these two methods?
User registration details have to be stored on the server. You can use any language you like there, JavaScript (node.js is the current preferred way to achieve that), Perl (PSGI/Plack), Python (WGSI), C# (ASP.NET), PHP (mod_php), whatever. If you did it entirely with client side JavaScript, then the registration would exist only for a particular browser (which makes it rather pointless for almost anything on the WWW).
You can do a lot of things with client side JavaScript.
You can test if the data enter by the user conforms to the requirements you've set (such as "usernames contain only ascii alphanumeric characters").
You can't stop data that doesn't conform to those requirements being submitted to your server though - everything outside your server is beyond your control. Users can edit your pages in their browser as much as they wish. Client side validation is a convenience to the user (giving feedback without a server round trip and page reload), nothing more.
You can use Ajax instead of an HTML form … but there is no reason to do that. It just adds an unnecessary dependancy on JavaScript. That doesn't mean Ajax can't be useful, you could use it to ask the server if a username was already taken while the user is filling out the rest of the form.

Categories

Resources