Buffer Overflow Data Gone Wild
Total Page:16
File Type:pdf, Size:1020Kb
CS1
Buffer Overflow – "Data gone wild"
Background
Summary:Buffer overflow occurs when data is input or written beyond the allocated bounds of an buffer, array, or other object causing a program crash or a vulnerability that hackers might exploit.
Description: A buffer overflow occurs when data is written beyond the boundaries of a fixed length buffer overwriting adjacent memory locations which may include other buffers, variables and program flow data. Considered the “nuclear bomb” of the software industry, the buffer overflow is one of the most persistent security vulnerabilities and frequently used attacks.
Risk – How can it happen?: Writing outside the bounds of a block of allocated memory can corrupt data, crash the program, or allow the execution of malicious code.
Example of Occurrence: A buffer overflow in a 2004 version of AOL's AIM instant- messaging software exposed users to buffer overflow vulnerabilities. If a user posted a URL in their “I'm away” message, any of his or her friends who clicked on that link might be vulnerable to attack. AOL's response was to suggest that users update to a new version that would fix the bug. Paul Roberts “AOL IM 'Away' message flaw deemed critical”, Inforworld, August 9, 2004 http://www.infoworld.com/article/04/08/09/HNaolimflaw_1.html
Example in Code: public class Overflow {
public static void main(String[] args) {
int[] vals = new int[10];
for (int i =0; i < 20; i++) { vals[i] = i; } } }
When this program is run, the loop counter will exceed the value of a suitable index for the array. When the assignment statement tries to store a value in vals[10], buffer overflow occurs. The result is unpredictable. Depending on the operating system and the specific nature of the overflow, it may not cause any apparent problems, or it will cause the program to crash.
How can I avoid buffer overflow problems?
Make sure you have enough space: Before copying data to a fixed size block, make
© 2009 Towson University 1 CS1 sure it is large enough to hold the data that you are going to copy. If it is not large enough, do not copy more data than your available space can hold. If your program is not able to continue properly after filling the available space, you may have to find some way to recover from the error.
Validate indices: If you have an integer variable, verify that it is within the proper bounds before you use it as an index to an array. This validation is particularly important for any values that might have been provided as user input or other untrusted input, such as information that might be read from a file or from a network connection.
When possible, use buffer-size accessors: Loops that iterate over arrays need to know the size of the array. Using a variable with the wrong value or the incorrect constant value can lead to buffer overflows. Some languages - including Java – provide operators that can be used to retrieve the size of an array. Using these operators can help you avoid some of these problems
Use alternative data structures that reduce the risk of overflows: Many buffer overflow vulnerabilities can be avoided by using vectors or other structures instead of traditional arrays. When possible, use ArrayLists and iterators instead of arrays and integer- indexed loop. Note that these tools will not prevent you from running into trouble: you will still have to write your code carefully and correctly. However, they can reduce your risk of buffer overflow vulnerabilities.
© 2009 Towson University 2 CS1
Laboratory/Homework Assignment: import java.util.Scanner; public class Overflow2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); int[] vals = new int[10];
System.out.println("How many values should be stored in the array? "); int count = scan.nextInt(); V 0 <=count < 10
for (int i = 0; i < count; i++ ) V 0 <=count < 10 vals[i] = count-i; V 0 <=i <10 }
System.out.println("Which value do you wish to retrieve? "); int which = scan.nextInt(); V
System.out.println("Your value is " +vals[which]); V 0 <=which < 10 } }
1. Run and compile the above program. Describe the results. What happens if you type “3” for the first prompt? 7? 12? 20? What happens if you type 10 for the first prompt and then 3, 7, 12, and 20 for the second prompt?
If you type any number that is greater than 10 or less than zero for the first prompt , or greater than 9 or less than zero for the second prompt, the program will not work correctly: you’ll get an ArrayIndexOutOfBoundsException and the program will terminate. If your values are within those ranges, the program will work.
2. Complete the checklist below for this program.
3. List the potential buffer overflow errors.
1. count may be greater than 9 or less than zero. 2. which may be greater than 9 or less than zero.
4. Provide example inputs that might cause buffer overflow problems
If either of the input values are greater than or equal to 10, a buffer overflow might result. For example, the first value might 30 and the second value might be 15.
5. What strategies might you use to remove potential buffer overflow vulnerabilities from this program?
© 2009 Towson University 3 CS1
The easiest way to remove potential buffer overflow vulnerabilities from this program is to check the values of which and count variables, making sure that they are both within the bounds of the array size.
Alternatively, the creation of the array could be delayed until after the user types the number of objects to put into it. If this approach is taken, you would be guaranteed that there is enough space for the objects that would be put in the array when the loop executes. Note that you would still need to make sure to verify that the which variable is in the correct range.
6. Write a program that reads at most 10 temperatures (stored as floating point values) from a file. Your program should include the following elements:
A prompt asking the user for the name of the file containing the temperatures A method to read the temperatures into an array. A method that prints the temperatures A method that computes the average temperature A main that uses each of these methods.
If there are more than 10 values, your program should ignore any values after the first 10. If there are no values in the file, an appropriate error message should be printed. Test this program with files containing the following sets of values. Indicate the average that you get in each case. Your program should handle each of these cases appropriately.
Code is given below after question 7
a. Empty file No values in file b. 40.3 35.8 29.6 45 17.8 19.2 38.6 31.5 27.8 39.9
40.3 35.8 29.6 45.0 17.8 19.2 38.6 31.5 27.8 39.9 The average of the values is 32.549995
c. 19.2 38.6 31.5 27.8 39.9
19.2 38.6 31.5 27.8 39.9 The average of the values is 31.4
d. 40.3 35.8 29.6 45 17.8 19.2 38.6 31.5 27.8 39.9 19.7 22.6 18.8
40.3 35.8 29.6 45.0 17.8 19.2 38.6 31.5 27.8 39.9 The average of the values is 32.549995
© 2009 Towson University 4 CS1
7. Complete the checklist below for your program. Did you find any vulnerabilities? If so, list them and revise the program to eliminate them.
import java.io.*; import java.util.*; public class Temps {
public static final int ARRAY_SIZE=10;
public static void main(String[] args) throws FileNotFoundException {
float[] temps = new float[ARRAY_SIZE];
String fname = getFileName();
FileReader reader = new FileReader(fname); Scanner inFile = new Scanner(reader);
int count = readValues(inFile,temps); inFile.close();
if (count == 0) { System.out.println("No values in file"); } else { printValues(temps,count); float average = getAverage(temps,count); System.out.println("The average of the values is "+average); } }
public static String getFileName() { Scanner s = new Scanner(System.in); System.out.print("Please type the name of the data file: "); String name = s.next(); return name; }
public static int readValues(Scanner in,float[] temps) { int i = 0; float val; while (in.hasNextFloat() && (i < temps.length)) { 0<= i < temps.length val = in.nextFloat(); temps[i] = val; V 0 <= i < temps.length i++; } return i; }
public static void printValues(float[] vals,int count) {
for (int i = 0; i < count; i++) { 0
© 2009 Towson University 5 CS1
public static float getAverage(float[] temps,int count) { float sum = 0.0f; for (int i = 0; i < count; i++) { 0 < I < count sum += temps[i]; V 0 <= i } Security Checklist: Security Checklist Vulnerability Buffer Overflow Course CS1 Task – Check each line of code Completed 1. Finding Arrays: 1.1 Underline each array declaration 1.2. For each array, underline all subsequent references 2. Index Variables – legal range for an array of size n is 0 <= i < n 2.1 For each underlined access that uses a variable as an index, write the legal range next to it. 2.2 For each index marked in 2.1, underline all occurrences of that variable. 2.3. Mark with a V any assignments, inputs or operations that may modify these index variables. Does your code verify that these operations will result in an index value that is within the appropriate bounds? If not, you may have a vulnerability. 3. Loops that modify index variables 3.1 Find loops that modify variables used to index arrays. For any index that occurs as part of a loop conditional, underline the loop limit. For example, if i < max is the conditional in a for loop, underline max 3.2. Write the legal range of the array index next to the loop limit as you did in step 2.1. Mark with a V if the loop limit could exceed the legal range of the array index. Watch out for loop that go until i <=max , as the largest valid index is max-1 3.3 If either the upper or lower loop limit is a variable, it must be checked just as indices are checked in Step 2 Shaded areas indicate vulnerabilities! Discussion 1. Describe the buffer overflow problem A buffer overflow occurs when a program attempts to access a value that is outside of the specified data buffer. The most common occurrence of this vulnerability involves trying to access an element that is beyond the bounds of an array. Attempting to write to the 15 position in a 10- item array, for example, would cause a buffer overflow. © 2009 Towson University 6 CS1 2. Give three real life examples of buffer overflow attacks (research on the web). 1. The 1998 Morris Internet Worm 2. 2001 Code Red Worm – Microsoft Internet Information Services 3. 2003 SQL Slammer – Microsoft SQL Server 2000 Source: http://en.wikipedia.org/wiki/Buffer_overflow 3. What can result from a buffer overflow? The potential impact of a buffer overflow will largely depend on the programming language. Some languages, such as Java, automatically identify situations that would lead to buffer overflows. These languages will generally indicate an error by throwing an exception, which the program should handle appropriately. If exceptions are not handled, the program will terminate. C, C++, and other similar languages do not stop programs from writing outside the bounds of a buffer. Programs written in these languages can write data beyond the bounds of a buffer, often without any obvious problems. However, this out-of-bounds data can also corrupt the values of variables, change the state of the program so as to make continued execution impossible, and create vulnerabilities that attackers might use to take control of computers. 4. List three ways you could potentially overflow a buffer in your program. 1. Having a loop counter that increments an index variable so it goes beyond the end of a data array. 2. Using a user supplied value to index an array, without verifying that it has an appropriate value. 3. Copy multiple items from one array to another without verifying that they can fit without overflowing. 5. How could you prevent a buffer overflow from occurring in your program? 1. Make sure you have enough space: allocate buffers that are large enough to complete your tasks. 2. Check index values: before using an integer or a variable to either retrieve a value from an array or store a value to an array, verify that it is within the appropriate range. Don’t forget that arrays are zero-indexed: if an array has 10 elements, all indices must be greater than or equal to zero, and less than or equal to 9. 3. Beware of code that copies items from one array to another: this sort of code has been involved in many real buffer overflow vulnerabilities. 6. Buffer overflows can be troublesome if they are used by attackers to run their own code. What sort of things might an attacker try to do if he or she were able to run any code they wanted on a computer? Directly malicious attackers might destory data or otherwise render the computer unusable. Criminals in search of useful information might try to read files, looking for credit card numbers, social security numbers, and other information that can be useful for theft, fraud, and identity theft. Others might use an attacked computer to run software that will be used to attack still other computers, creating an army of compromised computers that might be used to send spam mail or conduct large-scale coordinated attacks. © 2009 Towson University 7 CS1 © 2009 Towson University 8