Archive for the ‘Security’ Category
Monday, August 24th, 2009
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Most C programmers, even beginners, would claim that arrays are easy, except those abundant off-by-one errors and they are right. Arrays are easy indeed. However, here are a few points to consider when writing a program that needs a rather large array (By the way, the thought for this article came into mind while helping a colleague to resolve an error a couple of days ago). When creating a large array (e.g. something like int a[1000][1000], which BTW takes up around 3.8 MB on most machines), you might not have any issue at all or might see either a compile time error or worse, runtime errors.
Why do these errors happen? Depending on your machine’s limitations you are most probably consuming the total available stack (if you used a local variable) or data memory. Depending on your compiler, these might be flagged at compile time or surface when you try to run your program. Or it might be that your compiler isn’t able to work with large arrays. What you can do to alleviate these:
- The first and best way is to minimize your array size (This makes for an amazing example here from the bookd “Programming Peals”: http://www.cs.bell-labs.com/cm/cs/pearls/cto.html )
- Use “huge” memory model.
- Use a global variable (or a static variable if you are particular about its visibility to the rest of the program). The stack is generally quite limited as compared to the data memory available to a program. So, a variable with static storage would ensure that you use memory from the data segment.
- Don’t declare it as an array at all and instead use a pointer and dynamically allocate the memory required for it. You might have to use special allocation calls instead of normal malloc/calloc to get this working though (e.g. using farmalloc)
- Create a section in assembly with the “Area” directive (or whatever it is for your particular assembler) and reserve space for your array there and refer to that array as an extern variable.
The first approach is something that you should always look for. But if you can’t mimize your need any further, choose one out of the rest two. But few things to be kept in mind here that these options can still fail, e.g., when you don’t have enough RAM/heap memory remaining at runtime (of course, you would have planned for a graceful exit though in such case instead of the random crash that would have occured otherwise). But still these could be useful to you in case you don’t have any real RAM limitations but just that your compiler isn’t able to work with large objects.
© Safer Code | Large Arrays In C
Tags: BSS, C CPP, heap, Large Arrays, Programming Pearls, Stack Overflo
Posted in C/C++, Optimization, Security | 5 Comments »
Wednesday, June 10th, 2009
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Even an expert programmer cannot claim of writing bug free code. Bugs are here to stay during a software development life cycle. But what every programmer needs to do is to test his code before the code goes into the main repository. So, programmers have different techniques to do this. Running Test cases, getting code reviewed, code walk through, running manual tests, ad-hoc tests are various things performed by people and Bang!!! code goes into the repository. Let’s consider the following psuedo-code:
char* someString = (char*) malloc(100);
if(someString != NULL){
// do something
}else{
// handle error condition
}
Continue Reading
© Safer Code | “De-Bugging” Code before Check-in
Tags: bugs, C, crash, debugging, Efficiency, Languages, programming, safety and security, Security, testing
Posted in C/C++, Security | No Comments »
Monday, March 23rd, 2009
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Every programmer, no matter how great he is, makes mistakes sometime or the other while coding. Although every compiler tries its best to put across every possible error during compilation,many mistakes skip the wrath of compiler. Some are seemingly very innocent and very tough to be caught even during code review, sometimes even get through the cycle of testing. The real face of these mistakes show up always on the customer side by crashing the system.
Consider the following example:
int multiply(int m, int n)
{
int result = 0;
result = m * n;
return result;
}
void func()
{
int m = 32767;
int n = 32767;
int result = 0;
result = multiply( m, n );
}
Read the rest of this entry
© Safer Code | Lint your code: Find probable mistakes much before testing
Tags: buffer overflow, C, Flex Lint, LINT, MISRA, PC Lint, Safety, warnings
Posted in C/C++, General, Security | 3 Comments »
Tuesday, February 10th, 2009
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Everyone must have used rand() sometime or the other while writing C code. The problem with rand() in most of the platforms is that it is easy to predict the output. Being based on unsigned int, it is just a simple function using a seed which is always the last randomly generated some number. This seed is not very tough to guess for an advanced hacker. once this seed is guessed,, any password or information based on random number generation can be easilt cracked and maligned.
following code is abridged code of rand() function implementation referenced from the book The C programming Language written by Brian Kernighan and Dennis Ritchie
unsigned long int next = 1;
int rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next / 65536) % 32768;
}
This type of function is generally called linear congruential function. As you can notice yourself, that these type of linear congruential functions are very much predictable and are not recommended for security sensitive applications. If you look at the above given code, it is obvious that if the underlying environment does not change, then the random number generation can easily be guessed as it will generate same random number on running the application again and again.
Continue Reading the rest of the entry
© Safer Code | Predicting the rand() and using Cryptographic Random Numbers
Tags: C, Concepts, CryptGenRandom, Cryptography, Efficiency, rand, Random Numbers, Security, security holes
Posted in C/C++, General, Security | 7 Comments »
Tuesday, January 13th, 2009
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Except for few good C programmers, others generally tend to ignore variable initialization or I should rather say “proper variable initialization”. Generally seen, the variable declaration itself is not done with a good thinking. Improper local variable initialization might not be good for the working of the program but improper global variable initialization might get your software or system hacked.
The uninitialized variable or a wrongly initialized variable might lead a program to change its normal course of flow from the intended one. For example: If a variable “index” is being used for array navigation and is left uninitialized, it might contain a garbage value which can lead to array index out of bounds error. or if the variable “index” is initialized wrongly to –1, it might lead to serious flaw in code flow. Even if an integer value is being initialized to ‘0’, it might lead to a security check bypass because for some programs, even a ‘0’ is considered a valid value.
Lets take an example of a code piece.
int isMachineRunning = GetMachineStatus();
int state = GetUserState(isMachineRunning);
int userid = 0;
if (state) {
userid = ExtractUserID(state);
}
/* do stuff */
if (uid == 0) {
DoAdminThings();
}
Continue Reading >>
© Safer Code | Improper Variable Initialization
Tags: buffer overflow, C, Efficiency, initialization, Languages, Security, variable declaration, variables
Posted in C/C++, Java, Security | No Comments »
Tuesday, December 16th, 2008
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Alright!!! Let’s get started. This is one of many subjects which always overwhelms me. Why so? Ofcourse, the reasons can not be explained here but then, the reason should be the least of your worries.
Okay, if you know enough about this, then please post your knowledge tips as comments because your comments might help towards my unexplained reasons.
You may find similar information on other websites but then, it’s a wild world and I am not intending to infringe any copyrights.
Now to begin with, let’s first understand how to evaluate the performance of java code and protect the java code from tainted objects. We’ve already talked about Tainted Object Propagation in my previous post in context with databases. now, it is in context with application code.
I’ll explain this with an example of enum pattern.
We can have enums in Java in two ways. Continue for detailed reading
© Safer Code | Using Enum Pattern in Java < 1.5
Tags: bytecode, Concepts, Efficiency, efficient code, input validation, Java, pattern, reverse engineering, Safety, Security, untrusted inputs
Posted in General, Java, Security | 1 Comment »
Monday, December 8th, 2008
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Basically, Tainted Object Propagation is the term defined for using incorrect or invalid inputs to get more than required information from the system and in some cases, taking control of the system. Although this technique is much widely used to misuse web applications and database oriented applications, but this holds true for any API publisher who exposes his API’s to third party application writers.
Again, just like previous post, Let’s start with an example.
Consider that a web page or an application takes an input “userName” and the application executes the following query to find that particular user.
HttpServletRequest request = ...;
String userName = request.getParameter("name");
Connection con = ...
String query = "SELECT * FROM Users " + " WHERE name = ’" + userName + "’";
con.execute(query);
Now, this is the usual code written by programmers to get the particular from the database. Now, if an attacker gets the control of the userName field, he can set it to ‘OR 1=1; This query allows the user to circumvent user name check and returns all the users from the database. In this case, the input variable “userName” is considered as Tainted Object.
Continue Reading
© Safer Code | Tainted Object Propagation
Tags: Database, database input, Java, Queries, Security, SQL Injection, Taint, Tainted Object
Posted in General, Java, Security | 5 Comments »
Tuesday, December 2nd, 2008
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Last time, we advised you to use ditch the unsafe functions like strcpy and strcat, and use their safer replacements (strlcpy, strlcat) instead. However, there is a small problem with this that you might discover that your compiler (especially gcc) does not have these functions in their implementation of the c library (libc). Why is this so? Read this thread about the original patch that was submitted to add these functions to libc. Essentially, it was rejected on the basis that these functions hide problems instead of solving them and would actually lead to hard to detect bugs that creep in because of unsolicited truncation caused by these functions. A sample implementation of strlcpy looks like this:
#include <sys/types.h>
#include <string.h>
/*
* Copy src to string dst of size siz. At most siz-1 characters
* will be copied. Always NUL terminates (unless siz == 0).
* Returns strlen(src); if retval >= siz, truncation occurred.
*/
size_t
strlcpy(char *dst, const char *src, size_t siz)
{
char *d = dst;
const char *s = src;
size_t n = siz;
/* Copy as many bytes as will fit */
if (n != 0) {
while (--n != 0) {
if ((*d++ = *s++) == '\0')
break;
}
}
/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
if (siz != 0)
*d = '\0'; /* NUL-terminate dst */
while (*s++)
;
}
return(s - src - 1); /* count does not include NUL */
}
Now, there are supporters for both the sides. Solaris and BSD accepted these functions while GNU/Linux refuses to do so till date. The stand that I’d like to take here is that this is at least a step towards the right direction because a truncation bug is much better than an attacker taking over the control of your network just by pushing out a long string onto the stack. However, we could indeed augment the implementation above to communicate back to the caller somehow that truncation occurred. Whichever side you choose, be aware that these problems are very real and don’t just keep on using the older unsafe versions (Even in words of Ulrich Drepper, the opposer of strlcpy: “ The users of these functions[strcpy, strcat] should be severly punished”).
© Safer Code | Unsafe Functions In C And Their Safer Replacements: Strings Part II
Tags: buffer overflow, C, Computer Security, strcat, strcpy, Strings, strlcat, strlcpy, Ulrich Drepper
Posted in C/C++, Security | 8 Comments »
Tuesday, November 18th, 2008
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
In my previous posts, I have been emphasizing on validating Integer and String inputs by putting various checks in place. But now, I’ll suggest you to consider any type of input to your application or software as “Evil”. Consider the following two rules for any input data:
- All input is evil until proven otherwise.
- Data must be validated as it crosses the boundary between untrusted and trusted environments.
Till now, I explained how to validate Integer and String data, but today, I’ll explain what is to be validated in the input data. First things first, Look for valid data and reject everything else. You should deny all access until you are sure that the input in the request is valid. You should look for valid data and not look for invalid data for two reasons:
- There might be more than one valid way to represent the data.
-
For example: a word “Rose” can be represented in many ways like “ROSE”, “rose”, “R%6fse”, “RoSE” et cetera. All the mentioned words are the variations of single word “Rose” and they are valid variations. But, This can definitely be a problem for an application.
- You might miss an invalid data pattern.
Consider the following code: (more…)
© Safer Code | All Input is Evil
Tags: C, Concepts, input validation, programming, Safety, Security, security holes, untrusted inputs
Posted in C/C++, General, Security | 3 Comments »
Tuesday, November 11th, 2008
Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Alright!! In my last post about untrusted inputs, we talked about validating the data of the “integer” input parameters, checking the out parameters et cetera.This time, we’ll talk about other types of inputs. If you have written a program to take in multiple lines of strings as an input from the user, you need to make sure that the input is not tainted. It is clean and as per your expectations. For example: If your program requires an answer for a question which can be subjective, then you need to provide a string buffer good enough to get a complete answer but not large enough to crash your system or make it run out of memory. Or you need to protect your system from getting any malicious scripts being inserted.Strings are a very risky area for inputs as there is pre-defined rule for this type of validation. So, following are the points to ponder to make your code safe and secure.
- Firstly, do use regular expressions to validate the string input. For example, ^[A-Za-z0-9]+$ specifies that the string must be at least one character long and that it can only include upper-case letters, lower-case letters, and the digits 0 through 9 (in any order). You can use regular expressions to limit which characters are allowed and to be more specific (for example, you can often limit even further what the first character can be).If you use regular expressions, be sure to indicate that you want to match the beginning (usually symbolized by ^) and end (usually symbolized by $) of the data in your match. If you forget to include ^ or $, an attacker could include legal text inside their attack to bypass your check.
- Now, if your program needs more variety of input and the above point doesn’t fulfil the requirements then you need to make a bit more complicated regular expressions. If the data is a filename (or will be used to create one), be very restrictive. Ideally, don’t let users choose filenames, and if that won’t work, limit the characters to small patterns such as ^[A-Za-z0-9][A-Za-z0-9._\-]*$. You should consider omitting from the legal patterns characters like “/”, control characters (especially newline), and a leading “.”Similarly, you need to take care for email strings, locale specific strings. UTF-8 encoding characters et cetera. In most of the programs, complex regular expressions are good enough to validate a string. But in certain cases, a malicious input containing some script code can spoil the fun.
- If your program faces HTML tags or script related instructions in the input, the input should be rejected immidiately or your program might get infected with self executing malicious code. This technique is generally used in Cross Site scripting attack. (XSS attack). These problems are especially a problem for Web applications. Now, you need to again take care not to validate any input which looks like an HTML tag. The easiest way is to use above mentioned regular expressions which won’t allow the entry of ‘<’ or ‘>’ character. But if you must support some of the HTML tags like <a href=> etc, please validate them exclusively by filtering the whole string using a regex like ^(http|ftp|https)://[-A-Za-z0-9._/]+$. A pattern that allows some more complex patterns is: ^(http|ftp|https)://[-A-Za-z0-9._]+(\/([A-Za-z0-9\-\_\.\!\~\*\'\(\)\%\?]+))*/?$
- For more complex strings, like reading a data file, regular expressions, again, prove useful but the ideal way is to break the file into multiple chunks rather than reading it in one complete string.
To Keep your String input kept in well defined range or buffer, make sure that your program terminates it with a NULL character. This will ensure that even if a large buffer is inserted using the input, the sting will get truncated as soon as the buffer gets full and it will be protected from buffer overflow.
© Safer Code | Validating Untrusted String Inputs
Tags: buffer overflow, C, Cross Site Scriping, memory, regular expressions, string input, Strings, untrusted inputs, validation, XSS
Posted in C/C++, General, Security | 1 Comment »