Issues with using eval() to execute user-supplied code? - javascript

I have a calculator widget (jsfiddle) that uses javascript's eval() function to evaluate the user's input to work as a calculator. It's an embedded widget in a chrome extension, so it doesn't have any database or anything else attached that could be hurt, and it doesn't send or receive any data.
Obviously, since it uses javascript's eval function, any javascript can be executed by this box. Is there any risk involved with this? I'm fairly new to javascript so I'm not sure what could result from the user being able to evaluate their own javascript inside this widget. Wouldn't anything they do just be reverted upon refresh?

JavaScript runs on the client side, so your server is not in any imminent danger.
But this could be a problem if users could save their inputs somehow and give a link to other users, as this would allow for the execution of arbitrary JavaScript (ie: Cross-site scripting aka XSS)

All other "eval is evil" and "quality of code" concerns aside...
...the security concern isn't about allowing user-supplied code: the user can delete every file they own if they feel like it. Not recommended, but entirely possible.
The danger with JavaScript, be it eval() or otherwise, is allowing an attacker to run code on the users behalf (without consent), in the context of said user (ergo browser/domain).
This is known as XSS: Cross-Site Scripting:
Cross-site scripting holes are web-application vulnerabilities which allow attackers to bypass client-side security ... by finding ways of injecting malicious scripts into web pages [which may or may not involve eval], an attacker can gain elevated access-privileges to sensitive page-content, session cookies, and a variety of other information maintained by the browser on behalf of the user. Cross-site scripting attacks are therefore a special case of code injection.
Happy coding.

See: "eval is evil" from Efficient JavaScript code:
The 'eval' method, and related constructs such as 'new Function', are extremely wasteful. They effectively require the browser to create an entirely new scripting environment (just like creating a new web page), import all variables from the current scope, execute the script, collect the garbage, and export the variables back into the original environment. Additionally, the code cannot be cached for optimisation purposes. eval and its relatives should be avoided if at all possible.

Related

Preventing JavaScript 'functions' running on client

Is there some way to prevent certain 'functions' in JavaScript from running on the client. I have concerns that something like Mimikatz that could be run from memory and enable a hacker to compromise a host. Ideally this would detect definable code that is not allowed to run and prevent execution.
There are a few problems with what you're describing. The first is that it's very easy to obfuscate JavaScript. For example, let's say you didn't want the eval function to be executed. It's easy enough to design a regular expression that would remove direct calls to eval. Except what if it's not named eval anymore?
var e = eval;
e('evil');`
You could detect that too, but you end up going down a rabbit hole trying to anticipate obfuscation techniques. If you really want to do this, I suggest starting with a browser plugin like Greasemonkey or Tampermonkey. It's going to be a lot of work and you'll get a lot of false positives.
Another issue is deciding what to block. Depending on implementation, there are only a dozen or so global functions in JavaScript, plus another few dozen global objects. Which will be blocked? None of them are inherently dangerous unless there's a vulnerability in the JavaScript engine or browser. If you're aware a vulnerability, patching is going to be far safer and easier than filtering JavaScript.
The most common way that JavaScript is used in attacks is through cross-site scripting (XSS). The two main approaches are using a malicious script to steal data from the domain, or reformatting the page to prompt the user for sensitive data (usually credentials or payment card numbers). Both techniques use the same JavaScript functions that legitimate pages do, so it's effectively impossible to prevent by analyzing the JavaScript. It is possible to block simple XSS attacks by looking for JavaScript in a request parameter, but browsers already do that.
Your specific example of Mimikatz isn't JavaScript-specific. Mimikatz is a generic tool for post-exploitation. In other words, the attacker must first find a way into your system, then uses Mimikatz to make it easier to stay in and perform mischief. Again, without an initial vulnerability in the JavaScript engine or browser, an attacker won't be able to run something like Mimikatz using JS.
If you're still worried, look at a plugin like NoScript. It supports policies defining which domains can run JavaScript. It's not as granular as you'd like, but it's easy to setup.

Is it possible to hack with javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm familiar with the term hacking. Although i never will become one of those hackers who scam people or make trouble, i believe it's an essential aspect any person who calls themselves a programmer must be able to do, as it is mainly about problem solving. But how does it work? When those people hack games or websites or the guy who hacked sony, do they use a programming langauge like ANSI C or c++ or assembly. Assuming they use a programming language, would it be possible to use javascript to hack in the same way you'd use any other language to hack. Furthermore, what do you have to do to be able to hack too. I just wanna know how it works, and the theory behind it all.
Hacking is unique every time. Exploiting some types of vulnerability doesn't require any particular language at all. Sometimes you hack whatever's there, in whatever language or form you find it. Sometimes it's necessary to automate part of the process, for example password cracking, for which you can use any language you like.
Cracking a commercial game commonly involves studying its disassembled machine code, figuring out which part does the CD or license check, and surgically replacing a few bytes of the code such that the check is skipped.
Hacking a website commonly involves discovery of some small clumsiness on the part of its developers, which allows viewing of should-be private data, or permits execution of custom code if it does not sanitize data properly. SQL injection is a common flaw when values sent to a database are not properly protected within quotes ("...") and so you can give values which break out of the quotes to execute your own commands. Cross-site scripting is a type of hack that uses JavaScript: If a website blindly takes parameters from the URL or submitted form data and displays them on the page without safely encoding them as text (worryingly common), you can provide a <script> tag for execution on that page. Causing someone to visit such a URL allows execution of scripted actions on their behalf. Code injection is also possible on the server side with PHP (or Perl, or similar), if sloppy code gives access to an eval-like function, or if server misconfiguration allows user-uploaded files to be interpreted by the server as scripts.
Hacking into an operating system or server program remotely may exploit bugs in its handling of network commands. Improper handling of malformed network commands can cause it to bungle user authentication checks or even to directly execute code provided in the network packet, such as via a buffer overflow.
Bugs in web browsers, plugins, and document viewers are similar. What should be safe types of file can be crafted with non-standard or broken values. If the programmer forgot to handle these cases safely they can often be used to escape the normal limits of the file type.
Viruses can also be slipped onto a machine via physical exchange of USB stick or CD or convincing someone to install virus-laden software. Such viruses are often written anew for each purpose (to avoid anti-virus software), but there are some common ones available.
Weak or badly implemented encryption can permit brute-force decoding of encrypted data or passwords. Non-existent encryption can permit wiretapping of data directly. A lack of encryption can also permit unauthenticated commands to be sent to a user or server.
Very obvious passwords, or unchanged default passwords, may allow simple guesswork to get into a system. Some people use the same password everywhere. This give websites the power to simply walk in to a user's email account and then take control of everything associated with it. It also means a password leak on one insecure website may be used to access accounts on many other websites.
And sometimes, "hacking" is social engineering. For example, imagine phoning up a junior employee and pretending to be someone in charge, to trick them into revealing internal information or reset a password. Phishing emails are a common, semi-automated form of social engineering.
Breaking into a system is rarely just one of these steps. It's often a long process of analyzing the system, identifying minor flaws and leveraging them to see if a useful attack vector is exposed, then branching out from that to gain more access.
I've never done it, of course.
There is a sort of "hacking" possible with javascript. You can run javascript from the adressbar. Try typing javascript: alert("hello"); in your address bar while on this website.
This way it it possible to hijack local variables, cookies for instance.
But since javascript runs on the client-side. People would have to use your workstation in order to gain access to your cookies. It is a technique that can be used to alter login data and pretend to be somebody else (if the site had been badly built).
If you really want to learn more about this there are some 'javascript hacking lessons' that can be found here: http://www.hackthissite.org/pages/index/index.php
Side note, there is a difference between hacking and cracking. Reference: http://en.wikipedia.org/wiki/Hacker_(programmer_subculture)
There are many exploits that can use javascript, probably the most well-known is going to be cross-site scripting (XSS).
http://en.wikipedia.org/wiki/Cross-site_scripting
To follow up on Michael's answer, it is good to know the vulnerabilities in software and how people exploit those vulnerabilities in order to protect against them, however hacking is not something you want to be known for.
For a start, you are actually referring to what is known as Cracking, not hacking. This question will surely be closed, however some brief observations ^_^
Cracking comes from a base level understanding of how computer systems are built, hence you don't learn how to crack/hack, you learn about computer engineering in order to reverse-engineer.
A popular platform for hacking is Linux; over windows for example as its open source so experienced programmers can write their own programs. Although experienced hackers can accomplish their goal on any platform.
There are many levels of hacking however, simple website security is worlds apart from hacking in to Sony and facing jail ^_^
You may have some fun on http://www.hackthis.co.uk though
It depends on many things, for example: how the html code is structured, for example, I don't know if you could hack an iframe, but a normal web-page would be relative easy to hack. Another security pitfall programmers usually do is passing sensitive information via url query-string, then you could get those pieces of data and submitting them wherever they are used in the html code.
There could be another details, but I don't figure them out right now.

How can javascript (or a browser extension) detect the use of restricted functions?

I'm developing a scripting extension, similar to Greasemonkey or Chrome's content-script engine. This extension will allow script writers to do very dangerous things like access local files.
If I ever release this extension to the public, I would like it to be able to warn novice users if a script will use a "dangerous" function. I'd like this warning to be as hard to circumvent as possible.
For example, the extension can search for the protected string GM_openSQL_Connection and warn the user -- maybe like this:
Assume that the base web page will never be able to access GM_openSQL_Connection thanks to sandboxing mechanisms. Likewise, no <script> node will be able to.
But, the script writer could still circumvent the simple search, from above, with something like:
eval (decodeURI ("GM_op%65nSQL_Connection (...);") )
So the question is what are the kinds of ways in which an evil scripter can fool the check for restricted function usage, and how might I prevent such mischief?
Note: false warnings can be okay. For example if the script author uses the text "GM_openSQL_Connection" in an otherwise static string, then he will just have to put up with the (false) warning.
What are the ways in which an evil scripter can fool the check for restricted function us[age]?
There are thousands of combinations, for example, with eval(), new Function(), combinations of String.fromCharCode() and decodeURI() (like in your example).
How might I prevent such mischief?
Could you overload/shadow specific bad functions/objects/variables?
GM_openSQL_Connection = function() {
warnUser();
};
To set a flag if the extension attempts to access a forbidden function or variable, simply have a var isDangerous = false which is set to true if a forbidden function is called or the get/set on a forbidden property is accessed/modified.
If the isDangerous is true, then you can mark that extension as potentially having dangerous function/property calls/accesses.
Trying to scan the script to detect whether it uses any of these interfaces is the wrong approach. It is too easy to evade through obfuscation, as you seem to be discovering. It's fundamentally insecure: there's no way to make it work.
Here is a better approach. Require the script-writer to include a manifest that declares what special APIs it needs access to. Then, run the script in a secure Javascript sandbox which only exposes the allowed APIs and APIs it has requested, but nothing more. If the script doesn't request GM_openSQL_Connection in its manifest, don't expose that API to the script.
Because Javascript is a dynamic language that allows monkey-patching and unrestricted access to the global object, it takes some doing to build a secure sandbox that restricts what APIs the script can access. Therefore, I recommend that you use an existing sandboxing solution. One approach is to run the user script in a sandbox, and give the sandboxed code a library that's full of stubs for the sensitive APIs, where the stubs just use postMessage to send a RPC request to your extension code. This avoids having references that cross the sandbox boundary, which is good as (depending upon sandboxing technology) those kind of references typically carry a substantial potential for security vulnerabilities.
Then, you can drive your user warnings based upon the contents of the manifest. Important: please think carefully about this from a user's perspective. Will ordinary users be able to make sense of the warnings? Will they be able to make sensible decisions? Will users be in a better position to make good decisions than you will? Will users be overwhelmed by constant warnings, and just start ignoring them and clicking 'ok' (the cry-wolf effect)?
For information on technology for Javascript sandboxing, please read the following question on IT Security: How to scan Javascript for malicious code?. In the future, you might get answers on the IT Security site for this kind of question.

Security and JavaScript files containing a site's logic

Now that JavaScript libraries like jQuery are more popular than ever, .js files are starting to contain more and more of a site's logic. How and where it pulls data/information from, how that info is processed, etc. This isn't necessarily a bad thing, but I'm wondering to what extend this might be a security concern.
Of course the real processing of data still happens in the backend using PHP or some other language, and it is key that you make sure that nothing unwanted happens at that point. But just by looking at the .js of a site (that relies heavily on e.g. jQuery), it'll tell a person maybe more than you, as a developer, would like. Especially since every browser nowadays comes with a fairly extensive web developer environment or add-on. Even for a novice manipulating the DOM isn't that big of a deal anymore. And once you figure out what code there is, and how you might be able to influence it by editing the DOM, the 'fun' starts.
So my main concerns are:
I don't want everyone to be able to look at a .js file and see exactly (or rather: for a large part) how my site, web app or CMS works — what is there, what it does, how it does it, etc.
I'm worried that by 'unveiling' this information, people who are a lot smarter than I am figure out a way to manipulate the DOM in order to influence JavaScript functions they now know the site uses, possibly bypassing backend checks that I implemented (and thus wrongly assuming they were good enough).
I already use different .js files for different parts of e.g. a web app. But there's always stuff that has to be globally available, and sometimes this contains more than I'd like to be public. And since it's all "out there", who's to say they can't find those other files anyway.
I sometimes see a huge chuck of JavaScript without line breaks and all that. Like the compact jQuery files. I'm sure there are applications or tricks to convert your normal .js file to one long string. But if it can do that, isn't it just as easy to turn it back to something more readable (making it pointless except for saving space)?
Lastly I was thinking about whether it was possible to detect if a request for a .js file comes from the site itself (by including the script in the HTML), instead of a direct download. Maybe by blocking the latter using e.g. Apache's ModRewrite, it's possible to use a .js file in the HTML, but when someone tries to access it, it's blocked.
What are your thoughts about this? Am I overreacting? Should I split my JS as much as possible or just spend more time triple checking (backend) scripts and including more checks to prevent harm-doing? Or are there some best-practices to limit the exposure of JavaScripts and all the info they contain?
Nothing in your JavaScript should be a security risk, if you've set things up right. Attempting to access an AJAX endpoint one finds in a JavaScript file should check the user's permissions and fail if they don't have the right ones.
Having someone view your JavaScript is only a security risk if you're doing something broken like having calls to something like /ajax/secret_endpoint_that_requires_no_authentication.php, in which case your issue isn't insecure JavaScript, it's insecure code.
I sometimes see a huge chuck of JavaScript without line breaks and all that. Like the compact jQuery files. I'm sure there are applications or tricks to convert your normal .js file to one long string. But if it can do that, isn't it just as easy to turn it back to something more readable (making it pointless except for saving space)?
This is generally minification (to reduce bandwidth usage), not obfuscation. It is easily reversible. There are obfuscation techniques that'll make all variable and function names something useless like "aa", "bb", etc., but they're reversible with enough effort.
Lastly I was thinking about whether it was possible to detect if a request for a .js file comes from the site itself (by including the script in the HTML), instead of a direct download. Maybe by blocking the latter using e.g. Apache's ModRewrite, it's possible to use a .js file in the HTML, but when someone tries to access it, it's blocked.
It's possible to do this, but it's easily worked around by any half-competent attacker. Bottom line: nothing you send a non-privileged user's browser should ever be sensitive data.
Of course you should spend more time checking back-end scripts. You have to approach the security problem as if the attacker is one of the key developers on your site, somebody who knows exactly how everything works. Every single URL in your site that does something to your database has to be protected to make sure that every parameter is within allowed constraints: a user can only change their own data, can only make changes within legal ranges, can only change things in a state that allows changes, etc etc etc. None of that has anything at all to do with what your Javascript looks like or whether or not anyone can read it, and jQuery has nothing at all to do with the problem (unless you've done it all wrong).
Remember: an HTTP request to your site can come from anywhere and be initiated by any piece of software in the universe. You have no control over that, and nothing you do to place restrictions on what clients can load what pages will have any effect on that. Don't bother with "REFERER" checks because the values can be faked. Don't rely on data scrubbing routines in your Javascript because those can be bypassed.
Well, you're right to be thinking about this stuff. It's a non-trivial and much misunderstood area of web application development.
In my opinion, the answer is that yes it can create more security issues, simply because (as you point out) the vectors for attack are increased. Fundamentally not much changes from a traditional (non JS) web application and the same best practises and approaches will server you very well. Eg, watching out for SQL injection, buffer overflows, response splitting, etc... You just have more places you need to watch out for it.
In terms of the scripts themselves, the issues around cross-domain security are probably the most prevalent. Research and learn how to avoid XSS attacks in particular, and also CSRF attacks.
JavaScript obfuscation is not typically carried out for security reasons, and you're right that it can be fairly easily reverse engineered. People do it, partially to protect intellectual property, but mainly to make the code download weight smaller.
I'd recommend Christopher Wells book published by O'Reilly called 'Securing Ajax Applications'.
There is free software that does JavaScript Obfuscation. Although there is not security though obscurity. This does not prevent all attacks against your system. It does make it more difficult, but not impossible for other people to rip off your JavaScript and use it.
There is also the issue of client side trust. By having a lot of logic on the client side the client is given the power to choose what it wants to execute. For instance if you are escaping quote marks in JavaScript to protect against SQL Injection. A Hacker is going to write exploit code to build his own HTTP request bypassing the escaping routines altogether.
TamperData and FireBug are commonly used by hackers to gain a deeper understanding of a Web Application.
JavaScript code alone CAN have vulnerabilities in it. A good example is DOM Based XSS. Although I admit this is not a very common type of XSS.
Here's a book by Billy Hoffman about Ajax security:
http://www.amazon.com/Ajax-Security-Billy-Hoffman/dp/0321491939/ref=sr_1_1?ie=UTF8&s=books&qid=1266538410&sr=1-1

Server-side JavaScript cleanup or sandbox?

I am looking at allowing users to enter JavaScript to specify some logic in my app. The JavaScript would be entered and displayed in a browser, but it would be saved and validated server-side first.
This opens up obvious security implications.
Ideally, I would want to only allow a subset of the JavaScript language. Intuitively, an opt-in approach - specifying what is allowed, and disallowing everything else - seems more secure than an opt-out approach - specifying what is disallowed.
A lot of the solutions I've seen are client-side - I think a server-side solution makes more sense for my needs, since I can give feedback to the user if the JavaScript is invalid, and only save it on the server once it's "clean".
It would also be useful to put in place something to parse the JavaScript and perform some checks - for example, I would provide some variables to the user, I would want to check that they're not using any uninitialized variables, or that the code returns something in an expected format. A sandbox solution should at the very least not hinder this, but it could potentially actively help - if it works by parsing the code and not just regexps, and I can put my own hooks in to check some syntax.
Google Caja looks like it might do what I want, but I haven't dived into it very much.
What approach would you recommend?
Open-source solutions are great. I don't mind writing my own code, but this seems like a non-trivial problem to solve properly from scratch.
If you don't mind leaving out browsers that don't support web worker threads, you can try JSandbox, which effectively sandboxes execution of JavaScript in "sandbox" worker threads.

Categories

Resources