DAY 3. CS3600, Northeastern University. Alan Mislove

Similar documents
Copyright (2004) Purdue Research Foundation. All rights reserved.

Secure Programming. Buffer Overflows Learning objectives. Type. 3 Buffer Overflows. 4 An Important Vulnerability. 5 Example Overflow

In Java we have the keyword null, which is the value of an uninitialized reference type

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Fall 2018 Discussion 2: September 3, 2018

Lecture 8 Dynamic Memory Allocation

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CS 11 C track: lecture 5

CSC 1600 Memory Layout for Unix Processes"

Dynamic Allocation in C

Dynamic Allocation in C

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Memory Management I. two kinds of memory: stack and heap

Computer Programming: Skills & Concepts (CP) Strings

Dynamic Data Structures. CSCI 112: Programming in C

o Code, executable, and process o Main memory vs. virtual memory

Arrays and Memory Management

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Memory, Arrays & Pointers

ECE 15B COMPUTER ORGANIZATION

COSC Software Engineering. Lecture 16: Managing Memory Managers

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Program Security and Vulnerabilities Class 2

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Module: Safe Programming. Professor Trent Jaeger. CSE543 - Introduction to Computer and Network Security

Limitations of the stack

Contents of Lecture 3

High Performance Programming Programming in C part 1

CSCE 548 Building Secure Software Buffer Overflow. Professor Lisa Luo Spring 2018

CS 241 Data Organization Binary Trees

Pointers, Arrays, Memory: AKA the cause of those Segfaults

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Introduction to N1031. Components of N1031. Guiding Principles. Walk through, issues, and rationale

Pointers, Arrays, and Strings. CS449 Spring 2016

Computer Science 50: Introduction to Computer Science I Harvard College Fall Quiz 0 Solutions. Answers other than the below may be possible.

Memory Management in C (Dynamic Strings) Personal Software Engineering

3/7/2018. Sometimes, Knowing Which Thing is Enough. ECE 220: Computer Systems & Programming. Often Want to Group Data Together Conceptually

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

Class Information ANNOUCEMENTS

Kurt Schmidt. October 30, 2018

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

CS 61C: Great Ideas in Computer Architecture. Memory Management and Usage

CS349/SE382 A1 C Programming Tutorial

Homework 3 CS161 Computer Security, Fall 2008 Assigned 10/07/08 Due 10/13/08

Memory (Stack and Heap)

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS24 Week 2 Lecture 1

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

TI2725-C, C programming lab, course

Intermediate Programming, Spring 2017*

Heap Arrays. Steven R. Bagley

Fundamentals of Computer Security

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Recitation: C Review. TA s 20 Feb 2017

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Binghamton University. CS-211 Fall Dynamic Memory

CS61C Midterm Review on C & Memory Management

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

C Programming Basics II

Dynamic Memory: Alignment and Fragmentation

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Beyond Stack Smashing: Recent Advances in Exploiting. Jonathan Pincus(MSR) and Brandon Baker (MS)

CS 61c: Great Ideas in Computer Architecture

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

Q1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100

Lecture 9 Assertions and Error Handling CS240

Run Time Environment

Memory Allocation. Static Allocation. Dynamic Allocation. Dynamic Storage Allocation. CS 414: Operating Systems Spring 2008

CS61C : Machine Structures

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

CSC C69: OPERATING SYSTEMS

Create a Program in C (Last Class)

CIS 551 / TCOM 401 Computer and Network Security. Spring 2007 Lecture 2

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

Princeton University Computer Science 217: Introduction to Programming Systems. Modules and Interfaces

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

Dynamic memory. EECS 211 Winter 2019

Arrays and Pointers (part 1)

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

14. Memory API. Operating System: Three Easy Pieces

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Getting Started. Project 1

Chapter 19 Data Structures -struct -dynamic memory allocation

Hacking in C. Memory layout. Radboud University, Nijmegen, The Netherlands. Spring 2018

CSE 333 Midterm Exam 5/10/13

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Process s Address Space. Dynamic Memory. Backing the Heap. Dynamic memory allocation 3/29/2013. When a process starts the heap is empty

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

Dynamic Memory Allocation: Advanced Concepts

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

Transcription:

C BOOTCAMP DAY 3 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh and Pascal Meunier s course at Purdue

Memory management 2

Memory management Two different ways to look at memory allocation Transparent to user Done by the compiler, OS User-defined Memory allocated by the user Why allocate memory? Required by program for permanent variables Reserve working space for program Normally maintained using a stack and a heap 3

Stack A stack is an organized data structure Follows the LIFO (Last In First Out) principle A data item which enters the stack last is the first to be taken out 5 4 3 Push 4 3 Pop 4 3 2 2 2 1 1 1 4

Stack variables void foo(int i) { int j, k; char foo[] = "test"; } Where are j, k, and foo allocated? How long are they valid references? What is their scope? struct mystruct *foo(int i) { struct mystruct; mystruct.i = 7 } return &mystruct; What happens if you try the program above? Can the caller access mystruct? 5

Heap A heap is a collection in memory manipulated by the user/system No order specified for addition/removal Add 6 Del 3 1 2 3 4 5 1 2 3 4 5 6 1 2 4 5 6 6

Dynamic memory allocation There are times when we don t know how much memory is required Employee data base doesn t know how many employees will exist Program accepting command line input of different sizes User requests more records to be created printf("add a new record y/n?"); scanf ("%c", &response); if (response == 'y') { // we now have to allocate space } We use the heap to allocate memory dynamically 7

malloc void *malloc (size_t size) Returns a pointer to a contiguous block in memory of size bytes For example int *x = malloc(sizeof(int)); Returns a valid address, or NULL if an error occurs ALWAYS check the return value of malloc Memory is allocated (automatically) on the heap Allocated space is not initialized; contains garbage Contained in the header file: <stdlib.h> (usually) or <alloc.h> 8

A void *? Why is void * returned? malloc just allocates memory which consists of some number of bytes Memory as such has no data type Programmer must associate a data type with the block of memory How to assign a data type to the memory just created? Use type casting double *x; // x is a pointer to double; malloc returns an address x = (double *) malloc(100); // type casting the memory to be a double* How many doubles can we store? 100/8 = 12 We can clearly see a pit falls of malloc here x = (double *) malloc(100 * sizeof(double)); // better 9

Variants of malloc void *calloc (size_t count, size_t size) Allocated space is automatically initialized to zero Same as malloc, but is contained in <stdlib.h> Still have to cast void pointer to correct type Advantages over malloc Allocated memory is automatically initialized size and count are separated, making it easier to use Less prone to making errors on the correct amount and/or count required int *x; x = (int *) calloc (10, sizeof (int)); 10

Freeing memory You, the programmer, are in charge of freeing memory Only dynamically allocated memory can be freed (i.e., via malloc() or calloc()) int x; // memory for x is statically assigned here, cannot be freed When finished using dynamically allocated memory, free it void free (void *blk); Good practice to avoid memory leaks. Growing loss of memory due to unreleased locations Could prevent program from running properly, due to lack of memory Can run out of memory 11

Using free() char *x; x = (char *) malloc (10 * sizeof (char)); free (x); // frees the memory just assigned Never free a memory block that is not dynamically allocated. int *x; free (x); // error Never double-free char *x = (char *) malloc (10 * sizeof (char)); free (x); free (x); // error Never access freed memory char *x = (char *) malloc (10 * sizeof (char)); free (x); strcpy(x, "welcome"); // error 12

Keep track of your pointers! Dangling pointers char *x, *y; x = (char *) malloc (10 * sizeof (int)); y = (char *) malloc (10 * sizeof (int)); x = y; // cannot access what was in x anymore Can easily lead to memory leaks 13

Writing safe code in unsafe languages (e.g., C) 14

A few tips C provides much less help to the programmer than others You can get yourself into trouble easily Much more liberal with types Also, much harder to debug Memory is just an array of bytes Programmer has to assign meaning You can overwrite memory, making the source of problems A few tips will make your experience in this class easier 15

Buffer/array overflows char b[10]; b[10] = x; Array starts at index zero So [10] is 11th element One byte outside buffer was referenced Off-by-one errors are common and can be exploitable! Real example: int get_request (int d, char buffer[], u_short len) { u_short i; for (i=0; i< len; i++) {... } buffer[i] = \0 ; return i; } 16

What happens with an overflow? If memory doesn't exist: Bus error If memory protection denies access: Segmentation fault General protection fault If access is allowed, memory next to the buffer can be accessed Can overwrite the heap, stack Worst of all options; won t detect immediately Can compromise your program 17

Preventing buffer overflows void foo(int *array, int len); Always pass array/buffer length with array Don t assume you know the length Many library functions require you to do this already int foo[3]; for (i=0; i<=3; i++) foo[i] = 0; Remember that last element of n-length array is n-1 Can happen to the best programmers 18

Dealing with strings Recall, strings in C are NULL-terminated char*s Most C functions don't guarantee NULL-termination No guarantee that the strings you get are properly NULL-terminated Need to carefully read the function description to figure out When it may not NULL-terminate a string How to check for NULL-termination Where to append a NULL character yourself 19

A few string functions char * strncpy(char * dst, const char * src, size_t len); len is the maximum number of characters to copy dst is NULL-terminated only if less than len characters were copied! All calls to strncpy must be followed by a NULL-termination operation int strlen(const char * str); What happens when you call strlen on an improperly terminated string? Strlen scans until a null character is found Can scan outside buffer if string is not null-terminated Strlen is not safe to call unless you know string is NULL-termined 20

And a few more char * strcpy(char * dst, const char * src); How can you use strcpy safely? Set the last character of src to NULL Even if string is shorter than the entire buffer Do not check according to strlen(src)! Check that the src is smaller than or equal to dst Or allocate dst to be at least equal to the size of src 21