1 Part 4: Secure Coding u Many attacks are due to invalidated input to programs and faulty programming u Secure Coding:  Immensely important  Not taught,

Slides:



Advertisements
Similar presentations
Buffer Overflows Nick Feamster CS 6262 Spring 2009 (credit to Vitaly S. from UT for slides)
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CSc 352 Programming Hygiene Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
C Programming - Lecture 5
Gabe Kanzelmeyer CS 450 4/14/10.  What is buffer overflow?  How memory is processed and the stack  The threat  Stack overrun attack  Dangers  Prevention.
Stack buffer overflow
Buffer Overflow Exploits CS-480b Dick Steflik. What is a buffer overflow? Memory global static heap malloc( ), new Stack non-static local variabled value.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Teaching Buffer Overflow Ken Williams NC A&T State University.
Beyond Stack Smashing: Recent Advances in Exploiting Buffer Overruns Jonathan Pincus Microsoft Research Brandon Baker Microsoft Carl Hartung CSCI 7143:
Teaching Buffer Overflow Ken Williams NC A&T State University.
Control hijacking attacks Attacker’s goal: – Take over target machine (e.g. web server) Execute arbitrary code on target by hijacking application control.
CAP6135: Malware and Software Vulnerability Analysis Buffer Overflow I: Attack Introduction Cliff Zou Spring 2012.
Strings COEN 296A Spring Strings Strings are a fundamental concept, but they are not a built-in data type in C/C++. C-Strings C-style string: character.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
CAP6135: Malware and Software Vulnerability Analysis Buffer Overflow : Example of Using GDB to Check Stack Memory Cliff Zou Spring 2011.
Outline Midterm results Static variables Memory model
Chapter 6 Buffer Overflow. Buffer Overflow occurs when the program overwrites data outside the bounds of allocated memory It was one of the first exploited.
Exploiting Buffer Overflows on AIX/PowerPC HP-UX/PA-RISC Solaris/SPARC.
Computer Science Detecting Memory Access Errors via Illegal Write Monitoring Ongoing Research by Emre Can Sezer.
Mitigation of Buffer Overflow Attacks
Secure Coding in C and C++ String Vulnerabilities Lecture 4 Jan 25, 2011 Acknowledgement: These slides are based on author Seacord’s original presentation.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Buffer Overflow CS461/ECE422 Spring Reading Material Based on Chapter 11 of the text.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
Dynamic memory allocation and Pointers Lecture 4.
Overflow Examples 01/13/2012. ACKNOWLEDGEMENTS These slides where compiled from the Malware and Software Vulnerabilities class taught by Dr Cliff Zou.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 IS 2150 / TEL 2810 Introduction to Security James Joshi Associate Professor, SIS Lecture 12.2 Nov 20, 2012 Integer Issues.
Buffer Overflow Group 7Group 8 Nathaniel CrowellDerek Edwards Punna ChalasaniAxel Abellard Steven Studniarz.
Section 3.4: Buffer Overflow Attack: Attack Techniques 1.
A Tool for Pro-active Defense Against the Buffer Overrun Attack D. Bruschi, E. Rosti, R. Banfi Presented By: Warshavsky Alex.
CAP6135: Malware and Software Vulnerability Analysis Buffer Overflow I: Attack Introduction Cliff Zou Spring 2015.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
SDL - Buffer Overflows 1/37 Reference. Based on a presentation provided by Microsoft in relation to the Security Development Lifecycle – Developer Starter.
Buffer overflow and stack smashing attacks Principles of application software security.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
PHY 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.
Security Attacks Tanenbaum & Bo, Modern Operating Systems:4th ed., (c) 2013 Prentice-Hall, Inc. All rights reserved.
Slides by Kent Seamons and Tim van der Horst Last Updated: Nov 11, 2011.
1 2 2 Call The Project Dynamic-Memory 4 4 # include "Utilities.hpp" int main(int argc, char * argv[]) { short int *PtrNo; (*PtrNo) = 5; printf ("(*PtrNo)
CS426Fall 2010/Lecture 141 Computer Security CS 426 Lecture 14 Software Vulnerabilities: Format String and Integer Overflow Vulnerabilities.
1988 Morris Worm … estimated 10% penetration 2001 Code Red … 300,00 computers breached 2003 Slammer/Sapphire … 75,00 infections in 10 min Zotob …
VM: Chapter 7 Buffer Overflows. csci5233 computer security & integrity (VM: Ch. 7) 2 Outline Impact of buffer overflows What is a buffer overflow? Types.
1988 Morris Worm … estimated 10% penetration 2001 Code Red … 300,00 computers breached 2003 Slammer/Sapphire … 75,00 infections in 10 min Zotob …
Beyond Stack Smashing: Recent Advances In Exploiting Buffer Overruns Jonathan Pincus and Brandon Baker Microsoft Researchers IEEE Security and.
1 IS 2150 / TEL 2810 Introduction to Security James Joshi Associate Professor, SIS Lecture 11 Dec 8, 2009 Vulnerability related Integers. String, Race.
CAP6135: Malware and Software Vulnerability Analysis Buffer Overflow : Example of Using GDB to Check Stack Memory Cliff Zou Spring 2014.
Software Security. Bugs Most software has bugs Some bugs cause security vulnerabilities Incorrect processing of security related data Incorrect processing.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Memory-Related Perils and Pitfalls in C
Dynamic Allocation in C
Content Coverity Static Analysis Use cases of Coverity Examples
Buffer Overflow By Collin Donaldson.
Mitigation against Buffer Overflow Attacks
IS 2150 / TEL 2810 Introduction to Security
CNT4704: Computer Networking Special Topic: Buffer Overflow I: Attack Introduction Cliff Zou Fall 2009.
CMSC 414 Computer and Network Security Lecture 21
CS 465 Buffer Overflow Slides by Kent Seamons and Tim van der Horst
Secure Coding in C and C++ Integer Security
Memory Allocation CS 217.
Software Security Lesson Introduction
CSC 495/583 Topics of Software Security Format String Bug (2) & Heap
CAP6135: Malware and Software Vulnerability Analysis Buffer Overflow : Example of Using GDB to Check Stack Memory Cliff Zou Spring 2015.
Introduction to Static Analyzer
CS5123 Software Validation and Quality Assurance
C Programming - Lecture 5
Understanding and Preventing Buffer Overflow Attacks in Unix
CAP6135: Malware and Software Vulnerability Analysis Buffer Overflow : Example of Using GDB to Check Stack Memory Cliff Zou Spring 2013.
Presentation transcript:

1 Part 4: Secure Coding u Many attacks are due to invalidated input to programs and faulty programming u Secure Coding:  Immensely important  Not taught, not well understood  Major problem with software development u Languages used commonly are unsafe  C, C++ are unsafe  Java is much safer u We will use C to show common programming errors Code examples from “Secure Coding in C and C++” by Robert Seacord.

2 Two fundamental attacks 1. Buffer Overflow - writing past the end of an array or structure 2. Arbitrary Memory Write - writing to some arbitrary memory location The data written and the memory location chosen is under the control of the input data Input data is crafted by the attacker

3 gets is BAD u Never use gets, there is no safe way to use gets.  Even if you use getc, there could be problems (be careful) //gets problem void main (void) { char password[80]; puts ( “ Enter 8 char password: “); gets(password); }

4 Strings are Trouble u Strcpy, strcat are unsafe, in most cases. //string problems void main (int argc, char *argv[] ) { char name[2048]; // which line may overwrite? strcpy (name, argv[1]); strcat (name, “ = “); strcat (name, argv[2]); } //good int main (int argc, char *argv[] ) { char *buff = (char *)malloc(strlen(argv[1]+1); if (buf != NULL) { strcpy(buff, argv[1]); printf(“argv[1] =%s\n”, buff); } else { /* could not alloc, recover… */ } return 0;}

5 Off by one errors u Spot the errors //error int main (int argc, char *argv[] ) { char source[10]; strcpy(source, “ ”)  char *dest = (char *)malloc(strlen(source));  for (int I = 1; i<=11; i++) { dest[i] = source[i]; } dest[i] = ‘\0’;  printf(“dest = %s\n”, dest); }

6 More Grief u Counting errors u What happens after execution (difficult)? //bad, counting errors int main (int argc, char *argv[] ) { char a[16], b[16], c[32]; strcpy(a, ” abcdef”); strcpy(b, ” abcdef”); strcpy(c, a); strcpy(c, b); printf(”c = %s \n”, c); }

7 Double Dumb u Not just gets, more trouble bool IsPasswdOK(void) { char password[12]; gets(password); if (!strcmp(password, “goodpass”)) return(true) else return(false); }

8 Safe String Operations fgets, gets_s : Allows input size specifications strcpy_s, strcat_s : same strncpy (dest, source, size-1) : watch out for counting errors strncat : same Microsoft STRSAFE library n = read(fd, buff, n) // safe but complex programming needed

9 Overflow “protection” u Compiler checked bounds  Often inadequate, slow u Stackgap : introduce random gaps in stack u Canaries u Libsafe : replaces normal string operations, ensures overflows do not cross stack frame boundaries u Nothing can match proper input validation

10 Attack prone u Looks safe, but is not, wrong use of safe functions u Attacker can cause arc injection // call wrong function void good_f(char* str) { … } void main ( ); { static char buf [10] static void (*fptr)(char *str); fptr = &good_fl strnpy(buf, argv[1], strlen(argv[1]) fptr(argv[2]); } Attacker can overwrite fptr and provide args to fptr

11 Memory Layout generic Unix Win32 code data heap stack Global data BSS segment heap stack Reserved stack Reserved heap Reserved stack heap Reserved heap stack constant vars static vars un-init-vars

12 Where do these go? // memory layout static int initial = 1; // global data static int non-init; // BSS segment void main(int argc, char* argv[]) // stack { int i = 1, j; //stack static int x = 2 // global data static int y; // BSS segment int *buf = malloc (30); // buff on stack, contents on heap }

13 Arbitrary Memory Write u Via Overflow // bad memory write void foo (int* arg, int len); { char buff [50] ; int val = 25; int *ptr; = 30; memcpy(buff, arg, len); *ptr = val; … }

14 Function Pointer u Use of function pointer may be harmful // attackable function calls good-f(char *str) { printf(str) }; // watch out void main(int argc, char* argv[]) { void (*fptr) (const char *str); fptr = &good_f; *fptr(“hi ”); //attackable Good_f(“there\n”); //non-attackable }

15 Dangling Pointer u Free list structure is complex, and damage can be done by:  Using free memory  Double free u Prestored pointers are a source of errors p = malloc(50); …. Some code …… free(p) …… Some code …… *p is used here

16 Free Memory Error u Check the return value of malloc, else you may get… //referencing free memory int *mat(int *a, *b, n) { int *c = malloc(n * sizeof(int)); // no check? int i; for (i=0; i<n; i++) c += a[i] + b[i]; return c; } //two errors, subtle for (p=head; p != NULL; p = p->next) { // error 1 q = p-> next; free(p) ; // error 2 }

17 Double Free u More common that you think // freeing same memory twice x = malloc (size); //work on it free(x); y = malloc(size); //work on it; free(x); // often a cut and paste error

18 The Unlink Attack u Overflow in allocated memory may make unlinking dangerous Buffer overflow in HEAP – unlink attack int main(int arrgc, char *argv[]); { char first, second, third; first = malloc (222); second = malloc (12); third = malloc (12); strcpy(first, argv[1]); // may mess up mem alloc free(first); free(second); free(third); }

19 Mitigations u Make pointer null after free free(p); p = NULL; u Use consistent strategy  Do it in constructors and destructors  Do it at beginning and end of each module  Pair malloc and free  Keep you own free list (fixed size items) u Canaries u Guard pages u Randomization of malloc strategy

20 Integers are rather complex u C/C++ has many integer types  Unsigned, short, long, long long u Integers have ranks  Integer promotions are not well understood, conversions are also used and can cause errors (truncation, overflow)  Mixing unsigned ans signed integers are a problem, assigning negative numbers to unsigned integers is common (attack)

21 Size Matters u Obvious error INTEGER Security int main (int argc, char **argv); { unsigned short int total; total = strlen(argv[1])+strlen(argv[2]); char *buf = malloc (total); strcpy (buf, argv[1]); strcpy (buf, argv2)); }

22 Automatic promotions and casting u May not work, and then may //integer promotions char c1, c2, c3 result; c1 = 100; c2 = 90; c3 = -120; result = c1+c2+c3; // will work correctly (BAD)

23 From Real Life u Jpeg file comment size includes some other 2 bytes //JPEG vulnerability void getcomment(unsigned int len, char *src) { unsigned int size; size = len - 2; char comment = (char *) malloc(size + 1); memcpy (comment, src, size); } read the value of len from JPG file and then get comment.

24 Easy Heap Overflow u What does memcpy expect as type of len? // buffer overflow with –ve number main (argc, argv) { int len, char buf [size]; //size is a constant len = atoi(argv[1]); if (len <= size) ( memcpy(buf, argv[2], len); else printf(“too much data”); }

25 skip // truncation error main(argc, argv) { unsigned short int total; total = strlen(argv[1])+strlen(argv[2]); char *buf = malloc (total) strcpy(buf, argv[1]); strcat(buf, argv[2]); }

26 Skip // truncation problem with conversion bool func(char * name, long cbBuf); unsigned short bufSize = cbBuf; char *buf = (char *) malloc (bufSize); if buf { memcpy ( buf, name, cbBuf); }

27 Attackers think -ve u Most programs do not check for –ve values //negative index int *table = null; int insert(int pos, int value) { if (!table) table = maloc (400) if (pos > 99) { return -1} table[pos] = value; }

28 printf can be harmful u Check for user provided input u What does argv[0] actually contain? //usage exploit void usage(char *p) { char str[1024]; snprintf(str, 1024, “Usage: %s \n”, p); printf(usageStr); } Main() {if argc not > 2 usage(argv[0]); //easier to attack … printf(argv[1]);

29 Printf attacks //simplest func(char *user) { printf(user);} attack1: %s%s%s%s%s%s………… may crash attack2: %08x, %08x, %08x, ………… attack3: use %x a few times and then use %s attack4: \xdc\xf5\x42\x01%08x%08x%08x%08x%s (very tricky)

30 skip //buffer overflow char buffer[512]; sprintf(buffer, “Wrong command: %s\n”, user); //stretchable buffer char outbuf[512], buffer[512]; sprintf(buffer, “Wrong Command: %.400s”, user); sprintf(outbuf, buffer); -> input %497\x3c\xd3\xff\xbf\....[shellcode]

31 Memory Writes with printf u %n = write # of chars outputted %u wite integer using u spaces //overwriting memory int i; printf(“Hello %n\n”, (int*) &i); also: printf(“\xdc\xf5\x42\x0108x%08x%08x%08x%n”) //[write specific address] int i; printf("%10u%n", 1, &i); //i=10 printf("%100u%n", 1, &i); //i=100

32 An incomplete example unsigned char foo[8] printf(%x16u%n, 1, &foo[0]); printf(%x32u%n, 1, &foo[1]); printf(%x64u%n, 1, &foo[2]); printf(%x128u%n, 1, &foo[3]); printf("%16u%16u%32u%64u%n", 1, &foo[1], 1, &foo[2], 1, &foo[3], 1, &foo[4]);

33 Args to Prinf void foo(int p,int q, char *r, int s, int t) { int a[4] = {1,2,3,4}; print the stack here }; main() { foo(55, 56,"abcdefgh", 57, 58); }; bfabf458: 1 bfabf45c: 2 bfabf460: 3 bfabf464: 4 bfabf468: bfabf488 // base pointer bfabf46c: // return address bfabf470: 37 // 55 - arg 1 bfabf474: 38 // 56 - arg 2 bfabf478: // address for "abc... bfabf47c: 39 // 57 - arg 3 bfabf480: 3a // 58 - arg 4