Buffer Overflows. CSE 351 Autumn Instructor: Justin Hsia

Similar documents
Software Vulnerabilities

Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

Buffer Overflows. Code Security: Buffer Overflows. Buffer Overflows are everywhere. 13 Buffer Overflow 12 Nov 2015

X86-64 Architecture Guide

Unix Security Technologies. Pete Markowsky <peterm[at] ccs.neu.edu>

EECS 354 Network Security. Introduction

CS Computer Security Thirteenth topic: System attacks. defenses

Off-by-One exploitation tutorial

Bypassing Browser Memory Protections in Windows Vista

Hacking Techniques & Intrusion Detection. Ali Al-Shemery arabnix [at] gmail

Bypassing Memory Protections: The Future of Exploitation

Cryptography and Network Security Prof. D. Mukhopadhyay Department of Computer Science and Engineering

Quiz I Solutions MASSACHUSETTS INSTITUTE OF TECHNOLOGY Fall Department of Electrical Engineering and Computer Science

Introduction to Information Security

Dynamic Behavior Analysis Using Binary Instrumentation

Exploiting nginx chunked overflow bug, the undisclosed attack vector

Format string exploitation on windows Using Immunity Debugger / Python. By Abysssec Inc

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08

Cataloguing and Avoiding the Buffer Overflow Attacks in Network Operating Systems

Lecture 7: Machine-Level Programming I: Basics Mohamed Zahran (aka Z)

Return-oriented programming without returns

CSE331: Introduction to Networks and Security. Lecture 15 Fall 2006

Hotpatching and the Rise of Third-Party Patches

SECURITY B-SIDES: ATLANTA STRATEGIC PENETRATION TESTING. Presented by: Dave Kennedy Eric Smith

How to Sandbox IIS Automatically without 0 False Positive and Negative

Korset: Code-based Intrusion Detection for Linux

Defense in Depth: Protecting Against Zero-Day Attacks

3. Broken Account and Session Management. 4. Cross-Site Scripting (XSS) Flaws. Web browsers execute code sent from websites. Account Management

Certified Ethical Hacker (CEH) Ethical Hacking & Counter Measures Course 9962; 5 Days, Instructor-Led

Integrated Network Vulnerability Scanning & Penetration Testing SAINTcorporation.com

x64 Cheat Sheet Fall 2015

CS61: Systems Programing and Machine Organization

For a 64-bit system. I - Presentation Of The Shellcode

ERNW Newsletter 51 / September 2015

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Assembly Language: Function Calls" Jennifer Rexford!

Automated Repair of Binary and Assembly Programs for Cooperating Embedded Devices

Lecture 21: Buffer Overflow Attack. Lecture Notes on Computer and Network Security. by Avi Kak

Securing software by enforcing data-flow integrity

64-Bit NASM Notes. Invoking 64-Bit NASM

ECS 165B: Database System Implementa6on Lecture 2

CSCE 465 Computer & Network Security

Buffer Overflows. Security 2011

Where s the FEEB? The Effectiveness of Instruction Set Randomization

Bypassing Windows Hardware-enforced Data Execution Prevention

CS 416: Opera-ng Systems Design

風 水. Heap Feng Shui in JavaScript. Alexander Sotirov.

CSE331: Introduction to Networks and Security. Lecture 17 Fall 2006

Introduction to computer and network security. Session 2 : Examples of vulnerabilities and attacks pt1

Betriebssysteme KU Security

System Security Fundamentals

Chapter 15 Operating System Security

How To Detect A Buffer Overflow Vulnerability In Binary Code

I Control Your Code Attack Vectors Through the Eyes of Software-based Fault Isolation. Mathias Payer, ETH Zurich

A43. Modern Hacking Techniques and IP Security. By Shawn Mullen. Las Vegas, NV IBM TRAINING. IBM Corporation 2006

CMSC 421, Operating Systems. Fall Security. URL: Dr. Kalpakis

Sources: On the Web: Slides will be available on:

System Calls and Standard I/O

Custom Penetration Testing

Stack Overflows. Mitchell Adair

Summary of the SEED Labs For Authors and Publishers

Testing for Security

A Test Suite for Basic CWE Effectiveness. Paul E. Black.

Advanced IBM AIX Heap Exploitation. Tim Shelton V.P. Research & Development HAWK Network Defense, Inc. tshelton@hawkdefense.com

Stack Allocation. Run-Time Data Structures. Static Structures

Practical taint analysis for protecting buggy binaries

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

Hack Your SQL Server Database Before the Hackers Do

Violating Database - Enforced Security Mechanisms

CSC 405 Introduction to Computer Security

esrever gnireenigne tfosorcim seiranib

X05. An Overview of Source Code Scanning Tools. Loulwa Salem. Las Vegas, NV. IBM Corporation IBM System p, AIX 5L & Linux Technical University

Operating Systems. Privileged Instructions

02 B The Java Virtual Machine

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

C Compiler Targeting the Java Virtual Machine

Lecture 22: C Programming 4 Embedded Systems

The programming language C. sws1 1

Exploits: XSS, SQLI, Buffer Overflow

Modern Binary Exploitation Course Syllabus

Bypassing Anti- Virus Scanners

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

The Hardware/Software Interface CSE 351 Spring 2016

90% of data breaches are caused by software vulnerabilities.

Hydra. Advanced x86 polymorphic engine. Incorporates existing techniques and introduces new ones in one package. All but one feature OS-independent

Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings:

CSE331: Introduction to Networks and Security. Lecture 18 Fall 2006

Lecture 26: Obfuscation

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

How To Write Portable Programs In C

Transcription:

Buffer Overflows CSE 351 Autumn 2016 Instructor: Justin Hsia Teaching Assistants: Chris Ma Hunter Zahn John Kaltenbach Kevin Bi Sachin Mehta Suraj Bhat Thomas Neuman Waylon Huang Xi Liu Yufang Sun Alt text: I looked at some of the data dumps from vulnerable sites, and it was... bad. I saw emails, passwords, password hints. SSL keys and session cookies. Important servers brimming with visitor IPs. Attack ships on fire off the shoulder of Orion, c beams glittering in the dark near the Tannhäuser Gate. I should probably patch OpenSSL. http://xkcd.com/1353/

Administrivia Lab 2 due, Homework 2 released today Midterm on Nov. 2 in lecture Make a cheat sheet! two sided letter page, handwritten Midterm details Piazza post: @225 Past Num Rep and Floating Point questions and solutions posted Midterm review session 5 7pm on Monday, Oct. 31 in EEB 105 Extra office hours Sachin Fri 10/28, 5 8pm, CSE 218 Justin Tue 11/1, 12:30 4:30pm, CSE 438 2

Buffer overflows Buffer overflows are possible because C does not check array boundaries Buffer overflows are dangerous because buffers for user input are often stored on the stack Specific topics: Address space layout (more details!) Input buffers on the stack Overflowing buffers and injecting code Defenses against buffer overflows 3

x86 64 Linux Memory Layout Stack Runtime stack (8MB limit) for local vars Heap Dynamically allocated as needed malloc(), calloc(), new, Data Statically allocated data Read only: string literals Read/write: global arrays and variables Code / Shared Libraries Executable machine instructions Read only Hex Address 0x00007FFFFFFFFFFF 0x400000 0x000000 not drawn to scale Stack Heap Shared Libraries Heap Data Instructions 8MB 4

Reminder: x86 64/Linux Stack Frame Caller s Stack Frame Arguments (if > 6 args) for this call Return address Pushed by call instruction Current/ Callee Stack Frame Old frame pointer (optional) Saved register context (when reusing registers) Local variables (if can t be kept in registers) Argument build area (If callee needs to call another function parameters for function about to call, if needed) Frame pointer %rbp (Optional) Stack pointer %rsp Caller Frame Higher Addresses Arguments 7+ Return Addr Old %rbp Saved Registers + Local Variables Argument Build (Optional) Lower Addresses 5

Memory Allocation Example char big_array[1l<<24]; /* 16 MB */ char huge_array[1l<<31]; /* 2 GB */ int global = 0; int useless() { return 0; not drawn to scale Stack Heap int main() { void *p1, *p2, *p3, *p4; int local = 0; p1 = malloc(1l << 28); /* 256 MB */ p2 = malloc(1l << 8); /* 256 B */ p3 = malloc(1l << 32); /* 4 GB */ p4 = malloc(1l << 8); /* 256 B */ /* Some print statements... */ Where does everything go? Shared Libraries Heap Data Instructions 6

Memory Allocation Example char big_array[1l<<24]; /* 16 MB */ char huge_array[1l<<31]; /* 2 GB */ int global = 0; int useless() { return 0; not drawn to scale Stack Heap int main() { void *p1, *p2, *p3, *p4; int local = 0; p1 = malloc(1l << 28); /* 256 MB */ p2 = malloc(1l << 8); /* 256 B */ p3 = malloc(1l << 32); /* 4 GB */ p4 = malloc(1l << 8); /* 256 B */ /* Some print statements... */ Where does everything go? Shared Libraries Heap Data Instructions 7

Buffer overflows Buffer overflows are possible because C does not check array boundaries Buffer overflows are dangerous because buffers for user input are often stored on the stack Specific topics: Address space layout (more details!) Input buffers on the stack Overflowing buffers and injecting code Defenses against buffer overflows 8

Internet Worm These characteristics of the traditional Linux memory layout provide opportunities for malicious programs Stack grows backwards in memory Data and instructions both stored in the same memory November, 1988 Internet Worm attacks thousands of Internet hosts. How did it happen? Stack buffer overflow exploits! 9

Buffer Overflow in a nutshell Many Unix/Linux/C functions don t check argument sizes C does not check array bounds Allows overflowing (writing past the end of) buffers (arrays) Overflows of buffers on the stack overwrite interesting data Attackers just choose the right inputs Why a big deal? It is (was?) the #1 technical cause of security vulnerabilities #1 overall cause is social engineering / user ignorance Simplest form Unchecked lengths on string inputs Particularly for bounded character arrays on the stack Sometimes referred to as stack smashing 10

String Library Code Implementation of Unix function gets() /* Get string from stdin */ char* gets(char* dest) { int c = getchar(); char* p = dest; while (c!= EOF && c!= '\n') { *p++ = c; c = getchar(); *p = '\0'; return dest; What could go wrong in this code? pointer to start of an array same as: *p = c; p++; 11

String Library Code Implementation of Unix function gets() /* Get string from stdin */ char* gets(char* dest) { int c = getchar(); char* p = dest; while (c!= EOF && c!= '\n') { *p++ = c; c = getchar(); *p = '\0'; return dest; No way to specify limit on number of characters to read Similar problems with other Unix functions: strcpy: Copies string of arbitrary length to a dst scanf, fscanf, sscanf, when given %s specifier 12

Vulnerable Buffer Code /* Echo Line */ void echo() { char buf[4]; /* Way too small! */ gets(buf); puts(buf); void call_echo() { echo(); unix>./buf-nsp Enter string: 012345678901234567890123 012345678901234567890123 unix>./buf-nsp Enter string: 0123456789012345678901234 Segmentation Fault 13

Buffer Overflow Disassembly echo: 00000000004006cf <echo>: 4006cf: 48 83 ec 18 sub $24,%rsp 4006d3: 48 89 e7 mov %rsp,%rdi 4006d6: e8 a5 ff ff ff callq 400680 <gets> 4006db: 48 89 e7 mov %rsp,%rdi 4006de: e8 3d fe ff ff callq 400520 <puts@plt> 4006e3: 48 83 c4 18 add $24,%rsp 4006e7: c3 ret call_echo: 4006e8: 48 83 ec 08 sub $8,%rsp 4006ec: b8 00 00 00 00 mov $0x0,%eax 4006f1: e8 d9 ff ff ff callq 4006cf <echo> 4006f6: 48 83 c4 08 add $8,%rsp 4006fa: c3 ret return address 14

Buffer Overflow Stack Before call to gets Stack frame for call_echo Return address (8 bytes) /* Echo Line */ void echo() { char buf[4]; /* Way too small! */ gets(buf); puts(buf); 20 bytes unused echo: subq movq call $24, %rsp %rsp, %rdi gets [3] [2] [1] [0] buf %rsp Note: addresses increasing right to left, bottom to top 15

Buffer Overflow Example Before call to gets Stack frame for call_echo 00 00 00 00 00 40 06 f6 20 bytes unused void echo() { char buf[4]; gets(buf); call_echo: echo: subq movq call 4006f1: callq 4006cf <echo> 4006f6: add $8,%rsp $24, %rsp %rsp, %rdi gets [3] [2] [1] [0] buf %rsp 16

Buffer Overflow Example #1 After call to gets Stack frame for call_echo 00 00 00 00 00 40 06 f6 00 32 31 30 39 38 37 36 35 34 33 32 31 30 39 38 37 36 35 34 33 32 31 30 Note: Digit is just 0x3 in ASCII! buf %rsp void echo() { char buf[4]; gets(buf); call_echo: echo: subq movq call 4006f1: callq 4006cf <echo> 4006f6: add $8,%rsp unix>./buf-nsp Enter string: 01234567890123456789012 01234567890123456789012 Overflowed buffer, but did not corrupt state $24, %rsp %rsp, %rdi gets 17

Buffer Overflow Example #2 After call to gets Stack frame for call_echo 00 00 00 00 00 40 00 34 33 32 31 30 39 38 37 36 35 34 33 32 31 30 39 38 37 36 35 34 33 32 31 30 buf %rsp void echo() { char buf[4]; gets(buf); call_echo: echo: subq movq call 4006f1: callq 4006cf <echo> 4006f6: add $8,%rsp $24, %rsp %rsp, %rdi gets unix>./buf-nsp Enter string: 0123456789012345678901234 Segmentation Fault Overflowed buffer and corrupted return pointer 18

Buffer Overflow Example #3 After call to gets Stack frame for call_echo 00 00 00 00 00 40 06 00 33 32 31 30 39 38 37 36 35 34 33 32 31 30 39 38 37 36 35 34 33 32 31 30 buf %rsp void echo() { char buf[4]; gets(buf); call_echo: echo: subq movq call 4006f1: callq 4006cf <echo> 4006f6: add $8,%rsp unix>./buf-nsp Type a string: 012345678901234567890123 012345678901234567890123 Overflowed buffer, corrupted return pointer, but program seems to work! $24, %rsp %rsp, %rdi gets 19

Buffer Overflow Example #3 Explained After call to gets Stack frame for call_echo 00 00 00 00 00 40 06 00 33 32 31 30 39 38 37 36 35 34 33 32 31 30 39 38 37 36 35 34 33 32 31 30 buf %rsp register_tm_clones: 400600: mov %rsp,%rbp 400603: mov %rax,%rdx 400606: shr $0x3f,%rdx 40060a: add %rdx,%rax 40060d: sar %rax 400610: jne 400614 400612: pop %rbp 400613: retq Returns to unrelated code. Lots of things happen, but without modifying critical state. Eventually executes retq back to main. 20

Malicious Use of Buffer Overflow: Code Injection Attacks Stack after call to gets() High Addresses void foo(){ bar(); A:... return address A A B+24 A (return address) foo stack frame int bar() { char buf[64]; gets(buf);... return...; buf starts here data written by gets() B pad exploit code bar stack frame Low Addresses Input string contains byte representation of executable code Overwrite return address A with address of buffer B When bar() executes ret, will jump to exploit code 21

Exploits Based on Buffer Overflows Buffer overflow bugs can allow remote machines to execute arbitrary code on victim machines Distressingly common in real programs Programmers keep making the same mistakes Recent measures make these attacks much more difficult Examples across the decades Original Internet worm (1988) Still happens!! Heartbleed (2014, affected 17% of servers) Fun: Nintendo hacks Using glitches to rewrite code: https://www.youtube.com/watch?v=tqk 2jUQBUY FlappyBird in Mario: https://www.youtube.com/watch?v=hb6ey73slv0 You will learn some of the tricks in Lab 3 Hopefully to convince you to never leave such holes in your programs!! 22

Example: the original Internet worm (1988) Exploited a few vulnerabilities to spread Early versions of the finger server (fingerd) used gets() to read the argument sent by the client: finger droh@cs.cmu.edu Worm attacked fingerd server by sending phony argument: finger exploit-code padding new-return-addr Exploit code: executed a root shell on the victim machine with a direct TCP connection to the attacker Once on a machine, scanned for other machines to attack Invaded ~6000 computers in hours (10% of the Internet) see June 1989 article in Comm. of the ACM The young author of the worm was prosecuted 23

Heartbleed (2014!) Buffer over read in OpenSSL Open source security library Bug in a small range of versions Heartbeat packet Specifies length of message Server echoes it back Library just trusted this length Allowed attackers to read contents of memory anywhere they wanted Est. 17% of Internet affected Catastrophic Github, Yahoo, Stack Overflow, Amazon AWS,... By FenixFeather Own work, CC BY SA 3.0, https://commons.wikimedia.org/w/index.php?curid=32276981 24

Dealing with buffer overflow attacks 1) Avoid overflow vulnerabilities 2) Employ system level protections 3) Have compiler use stack canaries 25

1) Avoid Overflow Vulnerabilities in Code /* Echo Line */ void echo() { char buf[4]; /* Way too small! */ fgets(buf, 4, stdin); puts(buf); Use library routines that limit string lengths fgets instead of gets (2 nd argument to fgets sets limit) strncpy instead of strcpy Don t use scanf with %s conversion specification Use fgets to read the string Or use %ns where n is a suitable integer 26

2) System Level Protections High Addresses Randomized stack offsets At start of program, allocate random amount of space on stack Shifts stack addresses for entire program Addresses will vary from one run to another Makes it difficult for hacker to predict beginning of inserted code Example: Code from Slide 6 executed 5 times; address of variable local = 0x7ffe4d3be87c 0x7fff75a4f9fc 0x7ffeadb7c80c 0x7ffeaea2fdac 0x7ffcd452017c Stack repositioned each time program executes Random allocation B? main s stack frame Other functions stack frames B? pad exploit code Low Addresses 27

2) System Level Protections Non executable code segments In traditional x86, can mark region of memory as either read only or writeable Can execute anything readable x86 64 added explicit execute permission Stack marked as non executable Do NOT execute code in Stack, Static Data, or Heap regions Hardware support needed data written by gets() B Stack after call to gets() B pad exploit code foo stack frame bar stack frame Any attempt to execute this code will fail 28

3) Stack Canaries Basic Idea: place special value ( canary ) on stack just beyond buffer Secret value known only to compiler After buffer but before return address Check for corruption before exiting function GCC implementation (now default) -fstack-protector Code back on Slide 13 (buf-nsp) compiled with fnostack-protector flag unix>./buf Enter string: 01234567 01234567 unix>./buf Enter string: 012345678 *** stack smashing detected *** 29

Protected Buffer Disassembly echo: 40072f: sub $0x18,%rsp 400733: mov %fs:0x28,%rax 40073c: mov %rax,0x8(%rsp) 400741: xor %eax,%eax 400743: mov %rsp,%rdi 400746: callq 4006e0 <gets> 40074b: mov %rsp,%rdi 40074e: callq 400570 <puts@plt> 400753: mov 0x8(%rsp),%rax 400758: xor %fs:0x28,%rax 400761: je 400768 <echo+0x39> 400763: callq 400580 < stack_chk_fail@plt> 400768: add $0x18,%rsp 40076c: retq 30

Setting Up Canary Before call to gets Stack frame for call_echo Return address (8 bytes) Canary (8 bytes) [3] [2] [1] [0] /* Echo Line */ void echo() { char buf[4]; /* Way too small! */ gets(buf); puts(buf); echo: buf %rsp Segment register (don t worry about it) movq %fs:40, %rax # Get canary movq %rax, 8(%rsp) # Place on stack xorl %eax, %eax # Erase canary 31

Checking Canary After call to gets Stack frame for call_echo Return address (8 bytes) Canary (8 bytes) 00 36 35 34 33 32 31 30 buf %rsp /* Echo Line */ void echo() { char buf[4]; /* Way too small! */ gets(buf); puts(buf); echo: movq 8(%rsp), %rax # retrieve from Stack xorq %fs:40, %rax # compare to canary je.l6 # if same, OK call stack_chk_fail # els, FAIL.L6: Input: 0123456 32

Summary 1) Avoid overflow vulnerabilities Use library routines that limit string lengths 2) Employ system level protections Randomized Stack offsets Code on the Stack is not executable 3) Have compiler use stack canaries 33