Secure programming in dynamic languages - security

Mistakes in memory management in C, C++, and their ilk are well known. I mostly program in dynamic, weakly typed languages. Are there issues which are particularly important in languages of this type? What language specific issues might I keep an eye out for?
I'm generally mindful of standard security issues, and try to think about the ways in which code could be misused, but am sure there are plenty of less superficial mistakes I could be making, and am interested in expanding my knowledge in this area.

If you use anything similar to eval() then there is risks for attacks, esp if you are trusting something from outside your application.

Just because you're not writing the lower level code doesn't mean that the language you are using, and therefore your app, wont have these kinds of security problems. So my answer to your question is to ensure that you stay up to date on the latest releases on whatever tools you are using. This is more of an issue for you if you host the environment in which your app run, otherwise it's more of a problem for users of your app if they have to run it on their machines.

SQL Injection is a common attack which doesn't depend on type management. Generally, missing input validation is a very common reason for security issues.

In the case of JavaScript the main vulnerabilities according to the EC-Council Secure Programmer Vol.1 are the following:
Cross Site Scriptting (XSS). In a XSS
attack, attackers submit client-side
executable scripts by inserting
malicious Javascript, VBScript,
ActiveX, HTML or Flash into vulnerable
dynamic page and execute the script on
the user's machine to collect the
user's information.
Avoiding XSS:
Constrain Input:
Define a codepage that decide wich characters are problemetic,
Restrict variables to choose characters that are explicitly allowed.
Filter metacharacters depending on the interpreter (HTML, browser and file system)
Aply canonicalization:
- The canonicalization technique brinbgs the input to an appropiate from before validating the input.
Validate de input:
Validate all external input for field length, data type, range, and for a white list to ensure acceptance of onlyknown unproblematic characters.
Encode Output
Convert metacharacters e.g: <, >, and "",use HTML entities instead.
Encode user-supplied output so that any inserted script are prevented from being transmitted to users in an executable form.
JavaScript Hijacking: Allows an
unauthorized party to read
confidential information. Occurs
because most web-browsers that
implement a security model do not
anticipate the use of Javascript for
communication. JavaScrpt Hijacking is
generally carried out through
cross-site request forgery. Coss-site
request forgeryis an attack that
enables the victim to sumbit one or
more HTTP requests to a vulnerable
website. This attack compromises data
integrity and confidentiality, meaning
an attacker can read the victim's
information and modify the information
stored on the vulnerable site.
A Javascript Hijacking attack can be defended:
By declinig malicious requests.
By preventing direct execution of the JavaScript response.

Related

Is HTTP X-XSS-Protection response header sufficient for handling reflected XSS attacks

I am a newbie in web application development. My application is using AngularJS\NodeJS. A security tool reported reflected XSS vulnerability in our application. From my search on the internet I found that there is a HTTP X-XSS-Protection response header which appears to protect the application against reflected XSS attacks. However, I am not sure if that should be sufficient for handling the reflected XSS attacks or additionally any input sanitization should also be done in the application.
X-XSS-Protection is not enough, and is already enabled by default in most browsers. All it does is it enables the built-in XSS protection in browsers, but the trick is, to the best of my knowledge (maybe somebody will correct me) it is not specified what exactly the browser should do. Based on my experience, browsers only filter the most trivial XSS, when there is a parameter with javascript between script tags - such javascript from the parameter will not be run. For example if the parameter is
something <script>alert(1)</script> something
this will not be run by the browser. And apparently that's it.
For example if you have server-side code like
<div class="userclass-{{$userinput}}">
then this can be exploited with the string abc" onclick="alert(1)" x=", and this will go through the built-in filter in any browser I tried.
And then we haven't talked about stored or DOM XSS, where this protection is totally useless.
With Angular, it is slightly harder to make your code vulnerable to XSS (see here how to bind stuff as html for example), but it is by far not impossible, and because you would almost never need an actual script tag for that, this built-in protection has very limited use in an Angular app.
Also while input validation/sanitization is nice to have, what you actually need against XSS in general is output encoding. With Angular, that is somewhat easier than with many other frameworks, but Angular is not the silver bullet, your application can still be vulnerable.
In short, anytime you display user input anywhere (more precisely, anytime you insert user input into the page DOM), you have to make sure that javascript from the user can't be run. This can be achieved via output encoding, and secure Javascript use, which can mean a lot of things, mostly using your template engine or data binding in a way that only binds stuff as text, and not anything else (eg. tags).
What X-XSS-Protection does is browser dependent and can't be relied upon for security. It is meant as an extra layer to make it more difficult to exploit vulnerable applications, but is not meant as a replacement for correct encoding. It is a warning that an application is vulnerable and the responsibility to fix it is on the application developers.
This is why in Chrome, errors in the XSS filter are not even considered security bugs. See the Chrome Security FAQ:
Are XSS filter bypasses considered security bugs?
No. Chromium contains a reflected XSS filter (called XSSAuditor) that
is a best-effort second line of defense against reflected XSS flaws
found in web sites. We do not treat these bypasses as security bugs in
Chromium because the underlying issue is in the web site itself. We
treat them as functional bugs, and we do appreciate such reports.
The XSSAuditor is not able to defend against persistent XSS or
DOM-based XSS. There will also be a number of infrequently occurring
reflected XSS corner cases, however, that it will never be able to
cover. Among these are:
Multiple unsanitized variables injected into the page.
Unexpected server side transformation or decoding of the payload.
And there are plently of bugs. There are ways found to bypass the filter regularly. Just last week there was a fairly simple looking injected style attribute bypass.
Such a filter would need to tell where values in the output have come from by only looking at the input and the output, without seeing any templates or server-side code. When any processing is done to the input, or there's multiple kinds of decoding occurring, or multiple values are combined together, this can be very difficult.
Much easier would be to take care of the encoding at the template level. Here, we can easily tell the difference between variable values and static code because they haven't been merged together yet.

interpreters in injection attacks

The OWASP definition of injection attacks says that -
Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.
What does interpreter means in each case (LDAP, OS, SQL etc)? Is an interpreter needed for all types of injection attacks such as XML, XPath, HTTP etc?
Yes, the nature of a code injection attack is that the attacker tricks the application into running some code statements that are not part of the intended functions of that application.
This means there has to be some mechanism to parse and execute the malicious code contained in the attacker's payload before the owner of the application can stop it.
In theory, an application could compile code and run it automatically, but it's much more common for this type of attack to use malicious code that is not compiled, but is interpreted at runtime.
Your other examples, XML, XPath, HTTP, are not typically associated with code injection.
XML is not code, it's a data format.
HTTP is not code, it's a protocol.
XPath is sort of like code, but a very specialized type of code. It's an expression language to identify elements in an XML document. It's limited in what it can do, so it's not a common vector for code injection attacks.

What are the security implications (if any) of allowing any password?

As Ars and many others have pointed out, even large organizations with extensive, presumably intelligent IT departments employ rules for password creation that are not always in the best interest of security.
Sometimes though, it is still hard to understand why some applications restrict certain characters but allow others, and why other applications have rules that contrast all other applications. All of this makes me feel like I am missing something.
I have been taught to never trust raw input from a user, so it feels wrong to allow input from the user and not validate it, however I am conflicted. In this case I feel there is a strong argument for allowing the user to enter anything, and not validate it (because there would be no need).
For illustrative reasons, take the following hypothetical user registration system:
A Hypothetical User Registration System
A user navigates to a form for registering an account with a website.
Among other inputs, the user is prompted for a password. The user is told they may enter any desired password. There are no rules. It can be absolutely any string of characters.
Upon receiving the submitted form (or any request, legitimate or malicious), the server does not validate the password field: it simply hashes whatever was given.
The hash is stored in a database for use later.
for instance, in PHP:
password_hash($_POST['password'], PASSWORD_DEFAULT);
If there are any, what are the security implications of this system?
Is there any kind of specially-crafted request that someone can possible submit that would cause unintended consequences in this system? If so, please provide examples.
Would some server-side languages be susceptible to attacks from this, but others not? Which ones?
Again, this system is illustrative. Please do not argue what merits or downfalls a system like this may have in terms of the security of its users' passwords themselves, only what security implications it may have on the system itself.
The most common reason for preventing certain characters is that the developers don't know how to correctly handle passwords in whatever language they are working in, and rather than learn to do so, they try to limit what data they accept (often incorrectly). Alternately, they rely on third party components that handle passwords incorrectly and believe that they are powerless to fix this. (This is described in the article you link.)
If the code is precisely as you describe, with no fancy JavaScript in the middle touching the input, no middleware unpacking data structures, no logging systems writing passwords, no writing raw passwords into the database, no SQL queries built up as strings that might include the password, no unhashed passwords in the database, no incorrectly encoded strings in URLs, etc., then yeah, it's great. It's almost perfect (I'd much rather you apply some hashing before posting to the server, but there are some arguments there either way).
In modern applications, developers slap together all of the things mentioned in the last paragraph, and then apply a layer of hope and prayer and then scramble to patch when someone publishes an exploit. Everything in the last paragraph is horrible, and common.
So if you see restrictions on what characters are acceptable, it means the password handling system was either built poorly or the developers don't trust it. That is common, so restrictions are common.

Is worrying about XSS,CSRF,sql injection, cookie stealing enough to cover web-security?

Web applications on uncompromised computers are vulnerable to XSS,CRSF,sql injection attacks and cookie stealing in unsecure wifi environments.
To prevent those security issues there are the folowing remedies
sql injection: a good datamapper(like linq-to-sql) does not have the risk of sql injection (am i naïeve to believe this?)
CSRF: Every form-post is verified with the <%:Html.AntiForgeryToken() %> (this is a token in a asp.net mvc environment that is stored in a cookie and verified on the server)
XSS: every form that is allowed to post html is converted, only bb code is allowed, the rest is encoded . All possible save actions are done with a post event so rogue img tags should have no effect
cookie stealing: https
Am i now invulnerable to web-based hacking attempts(when implemented correctly)? Or am i missing some other security issues in web-development?(except for possible holes in the OS platform or other software)
The easy answer is "No you're not invulnerable - nobody is!"
This is a good start, but there are a few other things you could do. The main one you haven't mentioned is validation of untrusted data against a white-list and this is important as it spans multiple exploits such as both SQLi and XSS. Take a look at OWASP Top 10 for .NET developers part 1: Injection and in particular, the section about "All input must be validated against a whitelist of acceptable value ranges".
Next up, you should apply the principle of least privilege to the accounts connecting to your SQL Server. See the heading under this name in the previous link.
Given you're working with ASP.NET, make sure Request Validation remains on and if you absolutely, positively need to disable it, just do it at a page level. More on this in Request Validation, DotNetNuke and design utopia.
For your output encoding, the main thing is to ensure that you're encoding for the right context. HTML encoding != JavaScript encoding != CSS encoding. More on this in OWASP Top 10 for .NET developers part 2: Cross-Site Scripting (XSS).
For the cookies, make them HTTP only and if possible, only allow them to be served securely (if you're happy to only run over HTTPS). Try putting your web.config through the web.config security analyser which will help point you in the right direction.
Another CSRF defense - albeit one with a usability impact - is CAPTCHA. Obviously you want to use this sparingly but if you've got any really critical functions you want to protect, this puts a pretty swift stop to it. More in OWASP Top 10 for .NET developers part 5: Cross-Site Request Forgery (CSRF).
Other than that, it sounds like you're aware of many of the important principles. It won't make you invulnerable, but it's a good start.
Am I now invulnerable to web-based hacking attempts?
Because, no matter how good you are, everyone makes mistakes, the answer is no. You almost certainly forgot to sanitize some input, or use some anti-forgery token. If you haven't now, you or another developer will as your application grows larger.
This is one of the reason we use frameworks - MVC, for example, will automatically generate anti-CSRF tokens, while LINQ-to-SQL (as you mentioned) will sanitize input for the database. So, if you are not already using a framework which makes anti-XSS and anti-CSRF measures the default, you should begin now.
Of course, these will protect you against these specific threats, but it's never possible to be secure against all threats. For instance, if you have an insecure SQL-connection password, it's possible that someone will brute-force your DB password and gain access. If you don't keep your versions of .Net/SQL-Server/everything up to date, you could be the victim of online worm (and even if you do, it's still possible to be zero-dayed).
There are even problems you can't solve in software: A script kiddie could DDOS your site. Your server-company could go bankrupt. A shady competitor could simply take a hedge-clippers to your internet line. Your warehouse could burn down. A developer could sell the source-code to a company in Russia.
The point is, again, you can't ever be secure against everything - you can only be secure against specific threats.
This is the definitive guide to web attacks. Also, I would recommend you use Metasploit against your web app.
It definitely is not enough! There are several other security issues you have to keep in mind when developing a web-app.
To get an overview you can use the OWASP Top-Ten
I think this is an very interesting post to read when thinking about web-security: What should a developer know before building a public web site?
There is a section about security that contains good links for most of the threats you are facing when developing web-apps.
The most important thing to keep in mind when thinking about security is:
Never trust user input!
[I am answering to this "old" question because I think it is always an actual topic.]
About what you didn't mention:
You missed a dangerous attack in MVC frameworks: Over Posting Attack
You also missed the most annoying threats: Denial of Service
You also should pay enough attention to file uploads (if any...) and many more...
About what you mentioned:
XSS is really really really waster and more annoying to mitigate. There are several types of encoding including Html Encoding, Javascript Encoding, CSS Encoding, Html Attribute Encoding, Url Encoding, ...
Each of them should be performed to the proper content, in the proper place - i.e. Just doing Html Encoding the content is not enough in all situations.
And the most annoying about XSS, is that there are some situations that you should perform Combinational Encoding(i.e. first JavascriptEncode and then HtmlEncode...!!!)
Take a look at the following link to become more familiar with a nightmare called XSS...!!!
XSS Filter Evasion Cheat Sheet - OWASP

What are the common website vulnerabilities, and the programming languages related to them?

As far as know, I must be careful with PHP, and I think Javascript. What else?
Security vulnerabilities are (mostly) independent of the language involved (except for memory issues).
Instead, you should focus on tasks with potential vulnerabilities, such as processing user input or handling sensitive data.
Some things to watch out for:
Always use parameters in SQL
Always escape correctly (when generating HTML, JSON, Javascript strings, or anything else)
Be extremely careful when executing code dynamically (eg, eval, automatic updates, etc)
Always validate user input on the server
You should also read articles about security, such as the Top 25 Most Dangerous Programming Errors.
OWASP provides an annual report describing the top ten web application security flaws (see link below for description of the project and the most recent report). As SLaks wrote, many vulnerabilities are independent of the language. Web applications need to be designed with security in mind.
http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project

Resources