Using the QueryString as a debug switch? - security

I was refactoring some code in a web application today and came across something like this in the base class for all webpages:
if (Request.QueryString["IgnoreValidation"] != null)
{
if (Request.QueryString["IgnoreValidation"].ToUpper() == "TRUE")
{
SessionData.IgnoreValidation = true;
}
}
To me, this appears to be a Very Bad Thing™, so I instantly removed all traces of this flag from the code. For one, there were several if statements littered throughout that checked the value of the flag, leading to cluttered and unclear logic. Secondly, I came across another, more dangerous flag named "IgnoreCreditCardValidation". You can guess what that one did...
I then got to thinking about it and remembered a similar example from a previous job. In the code of an app sold as a "secure authentication module" there was a QueryString parameter used to override the default behavior, effectively allowing anyone with knowledge of it to bypass authentication.
Now my question is more of a confirmation, is this practice as bad as it seems in my head or am I just overreacting and this is commonplace? Are there any cases where there would be a valid reason to do this? To me it just seems like an awful mix of laziness and carelessness.
If this is a duplicate, please feel free to point me in the right direction.
Thanks!

It's horrifying whether it's common practice or not. +1 to you for nuking it with extreme prejudice.

I agree with you. Especially if the module is designed to enforce security, this is a stupid thing to have in a release build (it's not a good idea to have in debug builds either, but that might be reasonable.) It's essentially security-by-obscurity.

It's not you. Whoever wrote that has never dealt with public facing web applications. As you have correctly noted, anyone with knowledge of this 'backdoor' can wreck havoc on your application.

It's the original developer being lazy when it came to both design and testing.
The ideal solution is separate out the validation or credit card authentication etc from the code into separate dlls/services/etc. The real versions can then be replaced by mocks to facilitate testing of the site. The services can also be tested independently.
These mocks never get anywhere near the production server so you should never have backdoors into your code.
You can also replace any/all of the services without having to update your application - as long as the new service presents the same interface as the original.

I'm going against the grain and saying querystrings make good debug switches.
Before everyone jumps on me - using querystring to disable validation is horrendously stupid, a giant security hole, and should never happen. You were completely valid and justified nuking the code immediately.
But for debugging, querystrings work great. We have a few querystrings that will turn on IDs for a few objects on our pages so we can quickly get them without logging into the production database (not everyone has access to the Prod DB of course), or for checking calculation components. You just have to be careful and intelligent about them.

Related

When exactly am I required to set objects to nothing in classic asp?

On one hand the advice to always close objects is so common that I would feel foolish to ignore it (e.g. VBScript Out Of Memory Error).
However it would be equally foolish to ignore the wisdom of Eric Lippert, who appears to disagree: http://blogs.msdn.com/b/ericlippert/archive/2004/04/28/when-are-you-required-to-set-objects-to-nothing.aspx
I've worked to fix a number of web apps with OOM errors in classic asp. My first (time consuming) task is always to search the code for unclosed objects, and objects not set to nothing.
But I've never been 100% convinced that this has helped. (That said, I have found it hard to pinpoint exactly what DOES help...)
This post by Eric is talking about standalone VBScript files, not classic ASP written in VBScript. See the comments, then Eric's own comment:
Re: ASP -- excellent point, and one that I had not considered. In ASP it is sometimes very difficult to know where you are and what scope you're in.
So from this I can say that everything he wrote isn't relevant for classic ASP i.e. you should always Set everything to Nothing.
As for memory issues, I think that assigning objects (or arrays) to global scope like Session or Application is the main reason for such problems. That's the first thing I would look for and rewrite to hold only single identifider in Session then use database to manage the data.
Basically by setting a COM object to Nothing, you are forcing its terminator to run deterministically, which gives you the opportunity to handle any errors it may raise.
If you don't do it, you can get into a situation like the following:
Your code raises an error
The error isn't handled in your code and therefore ...
other objects instantiated in your code go out of scope, and their terminators run
one of the terminators raises an error
and the error that is propagated is the one from the terminator going out of scope, masking the original error.
I do remember from the dark and distant past that it was specifically recommended to close ADO objects. I'm not sure if this was because of a bug in ADO objects, or simply for the above reason (which applies more generally to any objects that can raise errors in their terminators).
And this recommendation is often repeated, though often without any credible reason. ("While ASP should automatically close and free up all object instantiations, it is always a good idea to explicitly close and free up object references yourself").
It's worth noting that in the article, he's not saying you should never worry about setting objects to nothing - just that it should not be the default behaviour for every object in every script.
Though I do suspect he's a little too quick to dismiss the "I saw this elsewhere" method of coding behaviour, I'm willing to bet that there is a reason Eric didn't consider that has caused this to be passed along as a hard 'n' fast rule - dealing with junior programmers.
When you start looking more closely at the Dreyfus model of skill acquisition, you see that at the beginning levels of acquiring a new skill, learners need simple to follow recipes. They do not yet have the knowledge or ability to make the judgement calls Eric qualifies the recommendation with later on.
Think back to when you first started programming. Could you readily judge if you were "set[tting an] expensive objects to Nothing when you are done with them if you are done with them well before they go out of scope"? Did you really know which objects were expensive or when they truly went out of scope?
Thus, most entry level programmers are simply told "always set every object to Nothing when you are done with it" because it is within their grasp to understand and follow. Unfortunately, not many programmers take the time to self-educate, learn, and grow into the higher-level Dreyfus stages where you can use the more nuanced situational approach.
And then we come back to my earlier statement - even the best of us started out at that earlier stage, where we reflexively closed all objects because that was the best we were capable of. We left large bodies of code that people look at now, and project our current competence backwards to the earlier work and assume we did that for reasons we don't understand.
I've got to get going, but I hope to expand this a little futher...

Is there ever a good reason to use PHP inside ExpressionEngine templates?

I've heard mixed things about this. I know it's easy when you're stuck to simply enable PHP in the template and hack your way around a problem. However, it almost always introduces potential security issues, and makes a mess of your template to boot.
In most cases where PHP is used, it would be cleaner to write a simple plugin in PHP to achieve what you need.
My question is this: Is it ever acceptable to use PHP inside ExpressionEngine templates? Or is this considered bad practice? If you were a developer who inherited a site I coded, would you cringe if you saw PHP inside templates?
This could just as easily be a question on the merits of eval() and whether it should ever be used. Most of the answers to questions along those lines are equally applicable here.
My view is that enabling PHP in templates is always a Bad Idea. At best, it's not a terrible idea, but there's always a better option. A custom addon will invariably be a better approach, even with seemingly harmless code snippets. I think it's also most likely to be used by those least qualified to use it. Personally, when I started building sites with EE my PHP skills ranged somewhere between 'totally inept' and 'knows enough to be dangerous'. At that time, if I came across a limitation in EE's code I'd often implement a solution via some inline PHP, partly because the idea of developing a custom addon seemed too daunting and partly because clicking a little 'enable PHP' radio button was so simple. Years later, whenever I need to update one of these sites, I definitely do cringe. Here are some of the side effects of PHP in templates:
Potentially introducing serious security vulnerabilities.
Increasing load times, potentially by a lot.
Debugging code becomes harder (good luck figuring out which file/line number has that error).
With tools like Pkg.io you can have the groundwork for an addon in place in 30 seconds. It requires a tiny amount of extra effort, but the gains are well worth it.
Let's imagine I'm answering this question as part of the 80% of people building websites with ExpressionEngine who may consider themselves as designers and or people who have little to no PHP experience:
Is it ever acceptable to use PHP inside ExpressionEngine templates?
No it's not acceptable, please don't do it!
Or is this considered bad practice?
Yup, pretty much.
If you were a developer who inherited a site I coded, would you cringe
if you saw PHP inside templates?
Definitely would cringe and maybe even curse a little.
Okay, now let's imagine I'm answering as part of the 20% who would consider themselves as an EE developer and or who have most experience programming over say designer all day:
Is it ever acceptable to use PHP inside ExpressionEngine templates?
Once in a while it's acceptable. For example you might find a need to turn on PHP for this Stash setup. It really depends on the complexity of what you are trying to achieve. Most things should go into an add-on whenever possible and being "lazy" doesn't count as a time when PHP is acceptable in templates.
Or is this considered bad practice?
ExpressionEngine and Codeigniter for that matter provide a great base to build add-ons and best practices include proper separation when ever possible. This includes separation from PHP and Templates; more often than not.
If it can go into an add-on it should as mentioned before. With that said, there isn't really anything limiting you from using PHP in templates except knowing that this may have security implications, cause future headaches for clients and other devs/designers etc.
If you were a developer who inherited a site I coded, would you cringe
if you saw PHP inside templates?
Definitely wouldn't cringed (unless your PHP was a disaster right from the start) though, would probably question why such simple and even complex code wasn't where it belonged; in an add-on.
Note: I pulled the percents out of thin air though, they quite possibly could be close to reality.
Also note: I realize the use of designer/developer in my answer could be seen as stereotyping though, wasn't quite sure how to avoid it. Hope no one takes offense.
I would consider using something like the phpstringfun add-on. This splits the different, but you're still working in EE tags.
I wouldn't sweat using small amounts of well-documented PHP in templates, but keep it as simple and abstracted as you can.

How secure is the "if" statement?

Regardless of the language I'm always puzzled by the concept of security through an if. All the code I write relies on success of that one line with if statement:
user = getUserName();
password = getPassword();
if (match(user, password)) {
print secret information;
}
Since it's only one line I feel like sabotage can be relatively simple. Am I overlooking things, or is a single if really the best way to do this?
You are right, an if like this is easily hacked. If one reverse engineers this application, you can easily modify a few instructions to skip the if.
There are various options, like obfuscating the executable or adding more complex checks and in add them in various places in your application. But whatever you do, your application can always be hacked.
Best thing is not to worry about it. By the time your application is so good and great and widely used that people are actually willing to put effort in cracking it, you will probably make enough money to protect it better. Until then, it's a waste of time to even think about it.
In the specific case you are showing, if you were really worried about unauthorized people seeing the secret information output by "print secret information;" you would encrypt the "secret information" with the supplied password. This would ensure that only the person who was able to provide the proper password would be able to see the secret information.
There's one thing about IF's that is often overlooked. It's called timing attack. Suppose you have a web application that does comparison based on direct matching of password sent against password stored in the DB (yes, I know that nobody in his mind will store passwords in the DB, but as Cheshire Cat said, "we are all mad here"). Then comparison procedure takes different time depending on whether the passwords don't match on the first character, on the second one or on the last one. While it might seem that the time difference is tiny, it's enough for attacker to attempt to guess the password even across internet, not talking about local analysis. Timing attack is a bit more complicated, than I described, but in general IF comparison is not 100% safe, at least not in all cases.
The if statement is absolutely secure, and can never be the cause of a vulnerability. Vulnerabilities arise from nearly everything else in your code.
It is possible that the comparison operator that you are using is flawed. For instance the == operator employs fuzzing matching where a range of possible values are accepted. This might not be good for secuirty but its hard to come up with a good example, it doesn't really matter for a password. A simple $password==$_GET['password'] should work just fine.
Your if statement could also be relying on bad regular expression such as
if(preg_match('/(.+)\\.js/'.$_GET['file'])){
readfile($_GET['file']);
}
In this case the regex is looking for a .js anywhere in the string, not enforcing it to be at the end.
?file=../../.js/../../../../../../../etc/passwd
(And this vulnerability won me $3,000 in the Mozilla bug bounty program ;)
If this is a server code - this is not a problem, as long as you keep your server secure.
If this is a client code - you are right. Someone can manipulate your code - either the binary file or the memory image (once loaded). However, this is true for any client application. You can only make it harder (by using tools like PECompact + Anti-debug plugin for example), but you can't achieve very strong security.
I'm not sure to understand your question.
Software security techniques are imperfect, and AFAIK they pre-suppose few bugs in the compiler, and a "perfect" hardware (that is, the processor is interpreting correctly the machine code).
I am not familiar (but interested) with approaches for imperfect hardware (except of course by using redundancy or other techniques, e.g. ECC, to detect hardware errors).
There is nothing insecure about one line with an if in it.
If the code is running on your server, what matters is how secure that server is. If an hacker gains access to it, it doesn't matter how complicated your code is, he will be able to circumvent it.
Similarly, if your code runs on the computer of a potential attacker (like a computer game that you want to protect), there is nothing you can do to stop the attacker. You can make his work slightly more difficult, but that's all.
You shouldn't worry about the security of one line, but of the system as a whole. If you make your code more complicated, all you did is introduce more potential for bugs. Using more complicated code is an attempt at security through obscurity, which doesn't work.
If you can't trust your computer to execute a simple if correctly, you can't trust it at all.

How should dangerous code snippets be published?

When discussing (asking/answering questions about, writing blog posts about, etc.) some programming matters, it may be desirable to give source code examples of what you're talking about; but in some cases these snippets may be dangerous, not because they are directly harmful but because they seem to work at first but only set up for problems later. Two examples would be when discussing concurrency issues, where the code works most of the time but rarely and non-deterministically fails, and when discussing security issues, where the code seems to work but can in fact be exploited; and there could be other examples.
It is necessary to be able to discuss such issues, to foster awareness of them at least. However, I am always worried that someone will come from a search engine, barely read the post, copy and paste the snippet and use it for something; more subtly, someone may read the post, try out the code in a test project and confirm it can indeed be exploited (as he is encouraged to do), then some time later reuse the dangerous code, as he has forgotten the code is dangerous and there is no longer a blog post explaining why the code is dangerous around the snippet.
So I am wondering how to mark such code so that no part of it somehow makes it to production (or if it ever does, then the responsible party could not plausibly deny awareness).
One way I came up with is to put:
an #error (or similar) directive inside each of the functions, as well as
repeated comments warning of the dangerousness of the code (since someone who will try out the code in a test project to confirm the issue will have removed the #error directive).
But since these comments would only clutter up the snippet when reading on the web, I make them the same color as the background (or at least I am trying to; see how I put it in action here, I incidentally have a question on doctype.com asking how to best do this).
If that seems completely overkill, remember that concurrency (and security) issues are very dangerous so I want to do all I can (within reason) to prevent my snippets from causing issues in real software; I am sometimes comparing this to fissile material handling.
(I honestly don't know whether it would be best suited for programmers.stackexchange.com or here, so I'm asking here first; feel free to move to programmers.stackexchange.com if it turns out it would be better there.)
You make a very good point and I think that you handle it pretty well right now.
However, the #error lines show up in the blog post for me, they are not white.
I think that you shouldn't worry so much about it being picked up by a feed or something like that. If the code is pulled away from the warning message on your blog, it's more important to have the #error lines visible.
But overall, I like your system. I might be good idea to set some standard for this, though, as programmers.
I would however add a link to the original post explaining why it is bad, too. That is way more important than just saying it is.
So to summarize: good idea, we should think of a standard. Make sure to include a link to a why.
Personally, yes, I think it's overkill.
I don't think you need to concern yourself with someone who extracts and uses the code without reading the context in which it's given. Such a programmer will likely be making so many other mistakes as to render using your code largely irrelevant.
In short they will have and be creating bigger problems.

Defensive programming [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
When writing code do you consciously program defensively to ensure high program quality and to avoid the possibility of your code being exploited maliciously, e.g. through buffer overflow exploits or code injection ?
What's the "minimum" level of quality you'll always apply to your code ?
In my line of work, our code has to be top quality.
So, we focus on two main things:
Testing
Code reviews
Those bring home the money.
Similar to abyx, in the team I am on developers always use unit testing and code reviews. In addition to that, I also aim to make sure that I don't incorporate code that people may use - I tend to write code only for the basic set of methods required for the object at hand to function as has been spec'd out. I've found that incorporating methods that may never be used, but provide functionality can unintentionally introduce a "backdoor" or unintended/unanticipated use into the system.
It's much easier to go back later and introduce methods, attributes, and properties for which are asked versus anticipating something that may never come.
I'd recommend being defensive for data that enter a "component" or framework. Within a "component" or framework one should think that the data is "correct".
Thinking like this. It is up to the caller to supply correct parameters otherwise ALL functions and methods have to check every incomming parameter. But if the check is only done for the caller the check is only needed once. So, a parameter should be "correct" and thus can be passed through to lower levels.
Always check data from external sources, users etc
A "component" or framework should always check incomming calls.
If there is a bug and a wrong value is used in a call. What is really the right thing todo? One only have an indication that the "data" the program is working on is wrong and some like ASSERTS but others want to use advanced error reporting and possible error recovery. In any case the data is found to be faulty and in few cases it's good to continue working on it. (note it's good if servers don't die at least)
An image sent from a satellite might be a case to try advanced error recovery on...an image downloaded from the internet to put up an error icon for...
I recommend people write code that is fascist in the development environment and benevolent in production.
During development you want to catch bad data/logic/code as early as possible to prevent problems either going unnoticed or resulting in later problems where the root cause is hard to track.
In production handle problems as gracefully as possible. If something really is a non-recoverable error then handle it and present that information to the user.
As an example here's our code to Normalize a vector. If you feed it bad data in development it will scream, in production it returns a safety value.
inline const Vector3 Normalize( Vector3arg vec )
{
const float len = Length(vec);
ASSERTMSG(len > 0.0f "Invalid Normalization");
return len == 0.0f ? vec : vec / len;
}
I always work to prevent things like injection attacks. However, when you work on an internal intranet site, most of the security features feel like wasted effort. I still do them, maybe just not as well.
Well, there is a certain set of best practices for security. At a minimum, for database applications, you need to watch out for SQL Injection.
Other stuff like hashing passwords, encrypting connection strings, etc. are also a standard.
From here on, it depends on the actual application.
Luckily, if you are working with frameworks such as .Net, a lot of security protection comes built-in.
You have to always program defensively I would say even for internal apps, simply because users could just through sheer luck write something that breaks your app. Granted you probably don't have to worry about trying to cheat you out of money but still. Always program defensively and assume the app will fail.
Using Test Driven Development certainly helps. You write a single component at a time and then enumerate all of the potential cases for inputs (via tests) before writing the code. This ensures that you've covered all bases and haven't written any cool code that no-one will use but might break.
Although I don't do anything formal I generally spend some time looking at each class and ensuring that:
if they are in a valid state that they stay in a valid state
there is no way to construct them in an invalid state
Under exceptional circumstances they will fail as gracefully as possible (frequently this is a cleanup and throw)
It depends.
If I am genuinely hacking something up for my own use then I will write the best code that I don't have to think about. Let the compiler be my friend for warnings etc. but I won't automatically create types for the hell of it.
The more likely the code is to be used, even occasionally, I ramp up the level of checks.
minimal magic numbers
better variable names
fully checked & defined array/string lengths
programming by contract assertions
null value checks
exceptions (depending upon context of the code)
basic explanatory comments
accessible usage documentation (if perl etc.)
I'll take a different definition of defensive programming, as the one that's advocated by Effective Java by Josh Bloch. In the book, he talks about how to handle mutable objects that callers pass to your code (e.g., in setters), and mutable objects that you pass to callers (e.g., in getters).
For setters, make sure to clone any mutable objects, and store the clone. This way, callers cannot change the passed-in object after the fact to break your program's invariants.
For getters, either return an immutable view of your internal data, if the interface allows it; or else return a clone of the internal data.
When calling user-supplied callbacks with internal data, send in an immutable view or clone, as appropriate, unless you intend the callback to alter the data, in which case you have to validate it after the fact.
The take-home message is to make sure no outside code can hold an alias to any mutable objects that you use internally, so that you can maintain your invariants.
I am very much of the opinion that correct programming will protect against these risks. Things like avoiding deprecated functions, which (in the Microsoft C++ libraries at least) are commonly deprecated because of security vulnerabilities, and validating everything that crosses an external boundary.
Functions that are only called from your code should not require excessive parameter validation because you control the caller, that is, no external boundary is crossed. Functions called by other people's code should assume that the incoming parameters will be invalid and/or malicious at some point.
My approach to dealing with exposed functions is to simply crash out, with a helpful message if possible. If the caller can't get the parameters right then the problem is in their code and they should fix it, not you. (Obviously you have provided documentation for your function, since it is exposed.)
Code injection is only an issue if your application is able to elevate the current user. If a process can inject code into your application then it could easily write the code to memory and execute it anyway. Without being able to gain full access to the system code injection attacks are pointless. (This is why applications used by administrators should not be writeable by lesser users.)
In my experience, positively employing defensive programming does not necessarily mean that you end up improving the quality of your code. Don't get me wrong, you need to defensively program to catch the kinds of problems that users will come across - users don't like it when your program crashes on them - but this is unlikely to make the code any easier to maintain, test, etc.
Several years ago, we made it policy to use assertions at all levels of our software and this - along with unit testing, code reviews, etc. plus our existing application test suites - had a significant, positive effect on the quality of our code.
Java, Signed JARs and JAAS.
Java to prevent buffer overflow and pointer/stack whacking exploits.
Don't use JNI. ( Java Native Interface) it exposes you to DLL/Shared libraries.
Signed JAR's to stop class loading being a security problem.
JAAS can let your application not trust anyone, even itself.
J2EE has (admittedly limited) built-in support for Role based security.
There is some overhead for some of this but the security holes go away.
Simple answer: It depends.
Too much defensive coding can cause major performance issues.

Resources