P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\titulka.jpg PA193 - Secure coding principles and practices Language level vulnerabilities: Buffer overflow, type overflow, strings •Petr Švenda svenda@fi.muni.cz • P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Security engineering – big picture •Phases 1.Requirements 2. 2.Design 3. 3.Implementation 4. 4.Testing/assurance •Activities •Security requirements •Abuse cases •Architectural risk analysis •Security-oriented design •Code review (with tools) •Risk-based security tools •Penetration testing 2 | PA193 - Buffer overflow, string vulnerabilities Based on Software security by M. Hicks (Coursera): https://class.coursera.org/softwaresec-002 P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Overview •Lecture: problems, prevention –buffer overflow (stack/heap/type) –string formatting problems –compiler protection –platform protections (DEP, ASLR) •Labs –compiler flags, buffer overflow exercises 3 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg PROBLEM? • 4 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Motivation problem •Quiz – what is insecure in given program? •Can you come up with attack? • • • •Classic buffer overflow •Detailed exploitation demo during labs this week • • • 5 | PA193 - Buffer overflow, string vulnerabilities #define USER_INPUT_MAX_LENGTH 8 char userName[USER_INPUT_MAX_LENGTH]; gets(userName); P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Process memory layout • 6 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\Obrázky\Programming\stack2.gif http://www.drdobbs.com/security/anatomy-of-a-stack-smashing-attack-and-h/240001832# Nejsou videt detaily P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Stack memory layout • 7 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\Obrázky\Programming\stack1.gif http://www.drdobbs.com/security/anatomy-of-a-stack-smashing-attack-and-h/240001832# P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Stack overflow • 8 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\Obrázky\Programming\stack4.gif http://www.drdobbs.com/security/anatomy-of-a-stack-smashing-attack-and-h/240001832# > P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Memory overflow - taxonomy 1.Buffer overflows 2.Stack overflows 3.Format strings 4.Heap overflows 5..data/.bss segment overflows • 9 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg • 10 | PA193 - Buffer overflow, string vulnerabilities // Note: GCC and MSVC uses different memory alignment // Try "12345678DevilEvecosia" as a password for gcc build // Try "1234567812345678Devil I am. Ha Ha" as a password for MSVC debug build void demoBufferOverflowData() { int unused_variable = 30; #define NORMAL_USER 'n' #define ADMIN_USER 'a' int userRights = NORMAL_USER; #define USER_INPUT_MAX_LENGTH 8 char userName[USER_INPUT_MAX_LENGTH]; char passwd[USER_INPUT_MAX_LENGTH]; // print some info about variables printf("%-20s: %p\n", "userName", userName); printf("%-20s: %p\n", "passwd", passwd); printf("%-20s: %p\n", "unused_variable", &unused_variable); printf("%-20s: %p\n", "userRights", &userRights); printf("\n"); // Get user name memset(userName, 1, USER_INPUT_MAX_LENGTH); memset(passwd, 2, USER_INPUT_MAX_LENGTH); printf("login as: "); fflush(stdout); gets(userName); // Get password printf("%s@vulnerable.machine.com: ", userName); fflush(stdout); gets(passwd); // Check user rights (set to NORMAL_USER and not changed in code) if (userRights == NORMAL_USER) { printf("\nWelcome, normal user '%s', your rights are limited.\n\n", userName); fflush(stdout); } if (userRights == ADMIN_USER) { printf("\nWelcome, all mighty admin user '%s'!\n", userName); fflush(stdout); } // How to FIX: //memset(userName, 0, USER_INPUT_MAX_LENGTH); //fgets(userName, USER_INPUT_MAX_LENGTH - 1, stdin); //memset(passwd, 0, USER_INPUT_MAX_LENGTH); //fgets(passwd, USER_INPUT_MAX_LENGTH - 1, stdin); } P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg •Úvod do C, 5.5.2014 • •void demoBufferOverflowData() { • int unused_variable = 30; •#define NORMAL_USER 'n' •#define ADMIN_USER 'a' • int userRights = NORMAL_USER; •#define USER_INPUT_MAX_LENGTH 8 • char userName[USER_INPUT_MAX_LENGTH]; • char passwd[USER_INPUT_MAX_LENGTH]; • • // print some info about variables • printf("%-20s: %p\n", "userName", userName); • printf("%-20s: %p\n", "passwd", passwd); • printf("%-20s: %p\n", "unused_variable", &unused_variable); • printf("%-20s: %p\n", "userRights", &userRights); • printf("\n"); • • // Get user name • printf("login as: "); • gets(userName); • • // Get password • printf("%s@vulnerable.machine.com: ", userName); • gets(passwd); • • // Check user rights (set to NORMAL_USER and not changed in code) • if (userRights == NORMAL_USER) { • printf("\nWelcome, normal user '%s', your rights are limited.\n\n", userName); • } • if (userRights == ADMIN_USER) { • printf("\nWelcome, all mighty admin user '%s'!\n", userName); • } •} •Reading username and password (no length checking) •Print information about current user rights •Array with fixed length (will be overwritten) •Variable containing current access rights •Help output of address of local variables stored on the stack P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg •| PA193 - Buffer overflow, string vulnerabilities Data in memory • bufferOverflow1 •passwd •userName •userRights •unused_variable P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg •| PA193 - Buffer overflow, string vulnerabilities Running without malicious input • bufferOverflow_correct •passwd •userName P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg •| PA193 - Buffer overflow, string vulnerabilities Running with malicious input – userName • bufferOverflow2 •insert ‘evil’ into userName P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg •| PA193 - Buffer overflow, string vulnerabilities Running with malicious input - passwd • • • • • • • • • •Too long password overflow userName and userRights bufferOverflow3 •Insert •‘1234567812345678Devil I am. Ha Ha’ into passwd P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg •Úvod do C, 5.5.2014 Running with attacker input - result • bufferOverflow_hacked P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Other stack overflow demos 1.Stack overflow – auth. privileges change 2.Adjacent memory overflow – reveal password 3.Smash function return address – attacker code exec 4.Type overflow – overflow integer causing BO 5.Buffer overflow - shell execution • •Example with debugging with instruction-wise mode 17 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg • 18 | PA193 - Buffer overflow, string vulnerabilities void demoAdjacentMemoryOverflow(char* userName, char* password) { // See more at http://www.awarenetwork.org/etc/alpha/?x=5 // Once string is not null terminated, lot of functions will behave wrongly: // sprintf, fprintf, snprintf, strcpy, strcat, strlen, strstr, strchr, read... // memcpy, memmove - if length to copy is computed via strlen(string) char message[100]; char realPassword[] = "very secret password nbu123"; char buf[8]; // print some info about variables printf("%-20s: %p\n", "message", message); printf("%-20s: %p\n", "userName", userName); printf("%-20s: %p\n", "password", password); printf("%-20s: %p\n", "realPassword", &realPassword); printf("%-20s: %p\n", "buf", &buf); printf("\n"); memset(buf, 0, sizeof(buf)); memset(message, 1, sizeof(message)); strncpy(buf,userName,sizeof(buf)); // We will copy only characters which fits into buf // Now print username to standard output - nothing sensitive, right? sprintf(message, "Checking '%s' password\n",buf); printf("%s", message); if (strcmp(password, realPassword) == 0) { printf("Correct password.\n"); } else { printf("Wrong password.\n"); } // FIX: Do not allow to have non-terminated string // Clear buffer for text with zeroes (terminating zero will be there) // strncpy(buf,arg1,sizeof(buf) - 1); } P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg • 19 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Type-overflow vulnerabilities - motivation •Quiz – what is insecure in given program? •Can you come up with attack? • • • •And what about following variant? –Be aware: char can be both signed (x64) or unsigned (ARM) • 20 | PA193 - Buffer overflow, string vulnerabilities for (unsigned char i = 10; i >= 0; i--) { /* ... */ } for (char i = 10; i >= 0; i--) { /* ... */ } P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Type overflow – basic problem •Types are having limited range for the values –char: 256 values, int: 232 values –add, multiplication can reach lower/upper limit –char value = 250 + 10 == ? •Signed vs. unsigned types –for (unsigned char i = 10; i >= 0; i--) {/* ... */ } •Type value will underflow/overflow –CPU overflow flag is set –but without active checking not detected in program •Occurs also in higher level languages (Java…) 21 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Type overflow – example with dynalloc • 22 | PA193 - Buffer overflow, string vulnerabilities typedef struct _some_structure { float someData[1000]; } some_structure; void demoDataTypeOverflow(int totalItemsCount, some_structure* pItem, int itemPosition) { // See http://blogs.msdn.com/oldnewthing/archive/2004/01/29/64389.aspx some_structure* data_copy = NULL; int bytesToAllocation = totalItemsCount * sizeof(some_structure); printf("Bytes to allocation: %d\n", bytesToAllocation); data_copy = (some_structure*) malloc(bytesToAllocation); if (itemPosition >= 0 && itemPosition < totalItemsCount) { memcpy(&(data_copy[itemPosition]), pItem, sizeof(some_structure)); } else { printf("Out of bound assignment"); return; } free(data_copy); } Basic idea: •Data to be copied into newly allocated mem. •Computation of required size type-overflow •Too small memory chunk is allocated •Copy will write behind allocated memory P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Safe add and mult operations in C/C++ •Compiler-specific non-standard extensions of C/C++ •GCC –__builtin_add_overflow, __builtin_mul_overflow … – –Result returned as third (pointer passed) argument –Returns true if overflow occurs –https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html •MSVC –SafeInt wrapper template (for int, char…) –Overloaded all common operations (drop in replacement) –Returns SafeIntException if overflow/underflow –https://msdn.microsoft.com/en-us/library/dd570023.aspx – – 23 | PA193 - Buffer overflow, string vulnerabilities bool __builtin_add_overflow (type1 a, type2 b, type3 *res) SafeInt c1 = 1; SafeInt c2 = 2; P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Safe add and mult operations in Java 24 | PA193 - Buffer overflow, string vulnerabilities •Java SE 8 introduces extensions to java.lang.Math •ArithmeticException thrown if overflow/underflow • public static int addExact(int x, int y) public static long addExact(long x, long y) public static int decrementExact(int a) public static long decrementExact(long a) public static int incrementExact(int a) public static long incrementExact(long a) public static int multiplyExact(int x, int y) public static long multiplyExact(long x, long y) public static int negateExact(int a) public static long negateExact(long a) public static int subtractExact(int x, int y) public static long subtractExact(long x, long y) public static int toIntExact(long value) P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Format string vulnerabilities - motivation •Quiz – what is insecure in given program? •Can you come up with attack? • 25 | PA193 - Buffer overflow, string vulnerabilities int main(int argc, char * argv[]) { printf(argv[1]); return 0; } P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Format string vulnerabilities •Wide class of functions accepting format string –printf("%s", X); –resulting string is returned to user (= potential attacker) –formatting string can be under attackers control –variables formatted into string can be controlled •Resulting vulnerability –memory content from stack is formatted into string –possibly any memory if attacker control buffer pointer • 26 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Information disclosure vulnerabilities •Exploitable memory vulnerability leading to read access (not write access) –attacker learns some information from the memory •Direct exploitation –secret information (cryptographic key, password...) •Precursor for next step (very important with DEP&ASRL) –module version –current memory layout after ASRL (stack/heap pointers) –stack protection cookies (/GS) – 27 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Format string vulnerability - example •Example retrieval of security cookie and return address • 28 | PA193 - Buffer overflow, string vulnerabilities int main(int argc, char* argv[]) { char buf[64] = {}; sprintf(buf, argv[1]); return printf("%s\n", buf); } •argv[1] submitted by an attacker •E.g., %x%x%x….%x •Stack content is printed •Including security cookie and RA P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Non-terminating functions - example •What is wrong with following code? 29 | PA193 - Buffer overflow, string vulnerabilities int main(int argc, char* argv[]) { char buf[16]; strncpy(buf, argv[1], sizeof(buf)); return printf("%s\n",buf); } P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg strncpy - manual • 30 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\School\PA193_SecureProgramming\2014\strncpy.png http://www.cplusplus.com/reference/cstring/strncpy/?kw=strncpy P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Non-terminating functions for strings •strncpy •snprintf •vsnprintf •mbstowcs •MultiByteToWideChar • •Non-null terminated Unicode string more dangerous –C-string processing stops on first zero –any binary zero (ASCII) –16-bit aligned wide zero character (UNICODE) • •wcsncpy •snwprintf •vsnwprintf •wcstombs •WideCharToMultiByte • 31 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Heap overflow • 32 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\Obrázky\Programming\heap1.jpg D:\Documents\Obrázky\Programming\heap2.jpg Buffer overflow in allocation 1 overwrites header for allocation 2 (and possibly other) Linked list between allocated blocks Felix "FX" Lindner, http://www.h-online.com/security/features/A-Heap-of-Risk-747220.html Corrupted allocation 2 data are later processed by unlink() function P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Heap overflow – more details •Assumption: buffer overflow possible for buffer at heap •Problem: –attacker needs to write his pointer to memory later used as jump –no return pointer (jump) is stored on heap (as was for stack) •Different mechanism for misuse –overwrite malloc metadata (few bytes before allocated block) •only next, prev, size and used can be manipulated •fake header (hdr) for fake block is created –let unlink function to be called (merge free blocks) •fake block is also merged during merge operation •hdr->next->next->prev = hdr->next->prev; 33 | PA193 - Buffer overflow, string vulnerabilities address in stack that will be interpreted later as jump pointer address of attacker’s code P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg SOURCE CODE PREVENTION • 34 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg How to detect and prevent problems? 1.Protection on the source code level –languages with/without implicit protection •containers/languages with array boundary checking –usage of safe alternatives to vulnerable function (this lecture) •vulnerable and safe functions for string manipulations –proper input checking (next lectures) –automatic detection by static and dynamic checkers (next lectures) –security testing, fuzzing (next lectures) 2.Protection by compiler (+ compiler flags) (this lecture) –runtime checks introduced by compiler (stack protection) 3.Protection by execution environment (this lecture) –DEP, ASRL... • 35 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg How to write code securely (w.r.t. BO) I. •Be aware of possibilities and principles •Never trust user’s input, always check defensively •Use safe versions of string/memory functions •Always provide a format string argument •Use self-resizing strings (C++ std::string) •Use automatic bounds checking if possible –C++ std::vector.at(i)instead of vector[i] • 36 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg How to write code securely (w.r.t. BO) II. •Run application with lowest possible privileges •Let your code to be reviewed •Use compiler-added protection •Use protection offered by platform (privileges, DEP, ASRL, sandboxing...) 37 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Secure C library •Secure versions of commonly misused functions –bounds checking for string handling functions –better error handling •Also added to new C standard ISO/IEC 9899:2011 •Microsoft Security-Enhanced Versions of CRT Functions –MSVC compiler issue warning C4996, more functions then in C11 •Secure C Library –http://docwiki.embarcadero.com/RADStudio/XE3/en/Secure_C_Library –http://msdn.microsoft.com/en-us/library/8ef0s5kh%28v=vs.80%29.aspx –http://msdn.microsoft.com/en-us/library/wd3wzwts%28v=vs.80%29.aspx –http://www.drdobbs.com/cpp/the-new-c-standard-explored/232901670 38 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Secure C library – selected functions •Formatted input/output functions –gets_s –scanf_s, wscanf_s, fscanf_s, fwscanf_s, sscanf_s, swscanf_s, vfscanf_s, vfwscanf_s, vscanf_s, vwscanf_s, vsscanf_s, vswscanf_s –fprintf_s, fwprintf_s, printf_s, printf_s, snprintf_s, snwprintf_s, sprintf_s, swprintf_s, vfprintf_s, vfwprintf_s, vprintf_s, vwprintf_s, vsnprintf_s, vsnwprintf_s, vsprintf_s, vswprintf_s –functions take additional argument with buffer length •File-related functions –tmpfile_s, tmpnam_s, fopen_s, freopen_s •takes pointer to resulting file handle as parameter •return error code 39 | PA193 - Buffer overflow, string vulnerabilities char *gets( char *buffer ); char *gets_s( char *buffer, size_t sizeInCharacters ); P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Secure C library – selected functions •Environment, utilities –getenv_s, wgetenv_s –bsearch_s, qsort_s • Memory copy functions –memcpy_s, memmove_s, strcpy_s, wcscpy_s, strncpy_s, wcsncpy_s •Concatenation functions – strcat_s, wcscat_s, strncat_s, wcsncat_s •Search functions –strtok_s, wcstok_s •Time manipulation functions... • 40 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg CERT C/C++ Coding Standard •CERT C Coding Standard –https://www.securecoding.cert.org/confluence/display/seccode/CERT+C+Coding+Standard •CERT C++ Coding Standard –https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=637 •Cern secure coding recommendation for C –https://security.web.cern.ch/security/recommendations/en/codetools/c.shtml •Smashing the stack in 2011 –https://paulmakowski.wordpress.com/2011/01/25/smashing-the-stack-in-2011/ – – • • 41 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg COMPILER PREVENTIONS MSVC, GCC • 42 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg MSVC Compiler security flags - /RTC •Microsoft’s MSVC in Visual Studio –http://msdn.microsoft.com/en-us/library/aa290051%28v=vs.71%29.aspx •Nice overview of available protections –http://msdn.microsoft.com/en-us/library/bb430720.aspx •Visual Studio ® Configuration properties ® C/C++ ® All options •Run-time checks –/RTCu switch •uninitialized variables check –/RTCs switch •stack protection (stack pointer verification) •initialization of local variables to a nonzero value •detect overruns and underruns of local variables such as arrays –/RTC1 == /RTCsu 43 | PA193 - Buffer overflow, string vulnerabilities /RTC is intended for DEBUG mode, unused for RELEASE P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg – –randomized cookie between local variables and return address –function prolog (add security cookie) –and epilog (check cookie) • 44 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\Obrázky\Programming\stack5_canary.gif D:\Documents\Obrázky\Programming\stack4.gif Stack without canary word http://www.drdobbs.com/security/anatomy-of-a-stack-smashing-attack-and-h/240001832# •Canary word (CY) P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg MSVC Compiler security flags - /GS •/GS switch (added from 2003, evolves in time) –http://msdn.microsoft.com/en-us/library/8dbf701c.aspx –multiple different protections against buffer overflow –mostly focused on stack protection •/GS protects: –return address of function –address of exception handler –vulnerable function parameters (arguments) –some of the local buffers (GS buffers) •/GS protection is (automatically) added only when needed –to limit performance impact, decided by compiler (/GS rules) –#pragma strict_gs_check(on) - enforce strict rules application – 45 | PA193 - Buffer overflow, string vulnerabilities /GS is applied in both DEBUG and RELEASE modes P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg /GS Security cookie (‘canary’) - details •/GS Security cookie –random DWORD number generated at program start –master cookie stored in .data section of loaded module –xored with function return address (pointer encoding) –corruption results in jump to undefined value •__security_init_cookie –http://msdn.microsoft.com/en-us/library/ms235362.aspx – – • 46 | PA193 - Buffer overflow, string vulnerabilities Stack after /GS Function parameters Function return address Frame pointer Cookie Exception Handler frame Locally declared variables and buffers Callee save registers Stack without /GS Function parameters Function return address Frame pointer Exception Handler frame Locally declared variables and buffers Callee save registers P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg /GS buffers •Buffers with special protection added –http://msdn.microsoft.com/en-us/library/8dbf701c.aspx –automatically and heuristically selected by compiler •Applies to: –array larger than 4 bytes, more than two elements, element type is not pointer type –data structure with size more than 8 bytes with no pointers –buffer allocated by using the _alloca function •stack-based dynamic allocation –any class or structure with GS buffer • 47 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg /GS – vulnerable parameters •Protection of function’s vulnerable parameters –parameters passed into function –copy of vulnerable parameters (during fnc’s prolog) placed below the storage area for any other buffers –variables prone to buffer overflow are put on higher address so their overflow will not overwrite other local variables •Applies to: –pointer –C++ reference –C-structure containing pointer –GS buffer 48 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Is /GS protection bulletproof? •Return address of X can be overwritten inside Y •Incorrect jump is executed only later after X ends •… • • 49 | PA193 - Buffer overflow, string vulnerabilities Function parameters Function return address (of Y == X) Frame pointer Cookie Exception Handler frame Locally declared variables and buffers Callee save registers D:\Documents\Obrázky\question.png Function parameters Function return address (of X) Frame pointer Cookie Exception Handler frame Locally declared variables and buffers Callee save registers Y X P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg /GS – what is NOT protected •/GS compiler option does not protect against all buffer overrun security attacks •Corruption of address in vtable –(table of addresses for virtual methods) •Example: buffer and a vtable in an object, a buffer overrun could corrupt the vtable •Functions with variable arguments list (...) 50 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg /GS – more references •Compiler Security Checks In Depth (MS) –http://msdn.microsoft.com/en-us/library/aa290051%28v=vs.71%29.aspx •/GS cookie effectiveness (MS) –http://blogs.technet.com/b/srd/archive/2009/03/16/gs-cookie-protection-effectiveness-and-limitatio ns.aspx •Windows ISV Software Security Defenses –http://msdn.microsoft.com/en-us/library/bb430720.aspx •How to bypass /GS cookie –https://www.corelan.be/index.php/2009/09/21/exploit-writing-tutorial-part-6-bypassing-stack-cookie s-safeseh-hw-dep-and-aslr/ – • 51 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg GCC compiler - StackGuard & ProPolice •StackGuard released in 1997 as extension to GCC –but never included as official buffer overflow protection •GCC Stack-Smashing Protector (ProPolice) –patch to GCC 3.x –included in GCC 4.1 release –-fstack-protector (string protection only) –-fstack-protector-all (protection of all types) –on some systems enabled by default (OpenBSD) •-fno-stack-protector (disable protection) • • • 52 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg GCC compiler & ProPolice - example • 53 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\School\PX_SecureProgramming\01_BufferOverflow\gcc_ssp_code.png http://www.drdobbs.com/security/anatomy-of-a-stack-smashing-attack-and-h/240001832# P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg GCC -fno-stack-protector • 54 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\School\PX_SecureProgramming\01_BufferOverflow\gcc_ssp_noprotect.png D:\Documents\School\PX_SecureProgramming\01_BufferOverflow\gcc_ssp_code.png P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg • 55 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\School\PX_SecureProgramming\01_BufferOverflow\gcc_ssp_protect.png D:\Documents\School\PX_SecureProgramming\01_BufferOverflow\gcc_ssp_code.png P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg How to bypass stack protection cookie? •Scenario: –long-term running of daemon on server –no exchange of cookie between calls 1.Obtain security cookie by one call –cookie is now known and can be incorporated into stack-smashing data 2.Use second call to change only the return address 56 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Control flow integrity •Promising technique with low overhead •Classic CFI (2005), Modular CFI (2014) –avg 5% impact, 12% in worst case –part of LLVM compiler (but only for C) 1.Analysis of source code to establish control-flow graph (which function can call what other functions) 2.Assign shared labels between valid caller X and callee Y 3.When returning into function X, shared label is checked 4.Return to other function is not permitted • •https://class.coursera.org/softwaresec-002/lecture/view?lecture_id=49 • 1. 57 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg PLATFORM PROTECTIONS • 58 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Data Execution Prevention (DEP) •Motto: When boundary between code and data blurs (buffer overflow, SQL injection…) then exploitation might be possible •Data Execution Prevention (DEP) –prevents application to execute code from non-executable memory region –available in modern operating systems •Linux kernel > 2.6.8, WinXP SP2, Mac OS X, iOS, Android –difference between ‘hardware’ and ‘software’ based DEP • 59 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Hardware DEP •Supported from AMD64 and Intel Pentium 4 –OS must add support of this feature (around 2004) •CPU marks memory page as non-executable –most significant bit (63th) in page table entry (NX bit) –0 == execute, 1 == data-only (non-executable) •Protection typically against buffer overflows •Cannot protect against all attacks! –e.g., code compiled at runtime (produced by JIT compiler) must have both instructions and data in executable page –attacker redirect execution to generated code (JIT spray) –used to bypass Adobe PDF and Flash security features 60 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Software “DEP” •Unrelated to NX bit (no CPU support required) •When exception is raised, OS checks if exception handling routine pointer is in executable area –Microsoft’s Safe Structured Exception Handling •Software DEP is not preventing general execution in non-executable pages –different form of protection than hardware DEP 61 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Return-oriented programming (ROP) I. •Return-into-library technique (Solar Designer, 1997) –http://seclists.org/bugtraq/1997/Aug/63 –method for bypassing DEP –no write of attacker’s code to stack (as is marked by DEP) 1.function return address is replaced by pointer of selected standard library function instead 2.library function arguments are also replaced according to attackers needs 3.function return will result in execution of library function with given arguments •Example: system call wrappers like system() – • 62 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Return-oriented programming (ROP) II. •But 64-bit hardware introduced different calling convention –first arguments to function are passed in CPU registers instead of via stack –harder to mount return-into-library attack •Borrowed code chunks –attacker tries to find instruction sequences from any function that pop values from the stack into registers –necessary arguments are inserted into registers –return-into-library attack is then executed as before •Return-oriented programming extends previous technique –multiple borrowed code chunks (gadgets) connected to execute Turing-complete functionality (Shacham, 2007) –automated search for gadgets possible by ROPgadget –https://www.youtube.com/watch?v=a8_fDdWB2-M –partially defended by ASLR (but information leakage) – 63 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Blind ROP •Recent technique (IEEE S&P 2014) –Randomization assumed –But no re-randomization on restart if server crash 1.Information leak for reading the stack 2.Find gadgets at runtime to affect write() 3.Dump binary to find gadgets (same as before) 64 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Address Space Layout Randomization (ASLR) •Random reposition of executable base, stack, heap and libraries address in process’s address space –aim is to prevent exploit to reliably jump to required address –performed every time a process is executed –random offset added to otherwise fixed address –entropy of random offset is important (bruteforce) •Applies to program and also dynamic libraries •Introduced by Memco software (1997) –fully implemented in Linux PaX patch (2001) –MS Windows Vista, enabled by default (2007) –MS Windows 8, improved entropy (2012) 65 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg ASLR – how much entropy? •Usually depends on available memory –possible attack combination with enforced low-memory situation •Linux PaX patch (2001) –around 24 bits entropy •MS Windows Vista (2007) –heap only around 5-7 bits entropy –stack 13-14 bits entropy –code 8 bits entropy –http://www.blackhat.com/presentations/bh-dc-07/Whitehouse/Presentation/bh-dc-07-Whitehouse.pdf •MS Windows 8 (2012) –additional entropy, Lagged Fibonacci Generator, registry keys, TPM, Time, ACPI, new rdrand CPU instruction –http://media.blackhat.com/bh-us-12/Briefings/M_Miller/BH_US_12_Miller_Exploit_Mitigation_Slides.pd f – 66 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg ASRL entropy in MS Windows 7&8 (2012) • 67 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\School\PX_SecureProgramming\01_BufferOverflow\ASRL_entropy_win7and8.png P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg DEP&ASRL – MSVC compilation flags •/NXCOMPAT (on by default) –program is compatible with hardware DEP •/SAFESEH (on by default, only 32bit programs) •software DEP •/DYNAMICBASE (on by default) –basic ASLR –Property Pages ® Configuration Properties ® Linker ® Advanced ® Randomized Base Address –http://msdn.microsoft.com/en-us/library/bb384887.aspx •/HIGHENTROPYVA (on by default, only 64bit programs) –ASRL with higher entropy –http://msdn.microsoft.com/en-us/library/dn195771.aspx • • • 68 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg ASRL – impact on attacks •ASLR introduced big shift in attacker mentality •Attacks are now based on gaps in ASRL –legacy programs/libraries/functions without ASRL support •! /DYNAMICBASE –address space spraying (heap/JIT) –predictable memory regions, insufficient entropy – – 69 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg DEP and ASLR should be combined •“For ASLR to be effective, DEP/NX must be enabled by default too.” M. Howard, Microsoft •/GS combined with /DYNAMICBASE and /NXCOMPAT –/NXCOMPAT prevents insertion of new attackers code and forces ROP –/DYNAMICBASE randomizes code chunks used later for ROP –/GS prevents modification of return pointer used later for ROP –/DYNAMICBASE randomizes position of master cookie for /GS •Visual Studio ® Configuration properties ® –Linker ® All options –C/C++ ® All options – 70 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg SUMMARY • 71 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg • 72 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\School\PX_SecureProgramming\01_BufferOverflow\MS_memoryattacks_state_2012.png P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Final checklist 1.Be aware of possible problems and attacks –Don’t make exploitable errors at the first place! –Automated protections cannot fully defend everything 2.Use safe versions of vulnerable functions –Secure C library (xxx_s functions) –Self-resizing strings/containers for C++ 3.Compile with all protection flags –MSVC: /RTC1,/DYNAMICBASE,/GS,/NXCOMPAT –GCC: -fstack-protector-all 4.Apply automated tools –BinScope Binary Analyzer, static and dynamic analyzers, vulns. scanners 5.Take advantage of protection in the modern OSes –and follow news in improvements in DEP, ASRL... – 73 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Mandatory reading •SANS: 2016 State of Application Security –https://www.sans.org/reading-room/whitepapers/analyst/2016-state-application-security-skills-confi gurations-components-36917 –How mature is AppSec in companies? Which industry leads? –Which applications are of main security concern? –What is expected time to deploy patch for security vulnerability? –What about third-party components? •SoK: Eternal War in Memory –http://www.cs.berkeley.edu/~dawnsong/papers/Oakland13-SoK-CR.pdf –http://www.slideshare.net/daniel_bilar/song-2013-so-k-eternal-war-in-memory –What are techniques to ensure memory safety? –What is performance penalty for memory protection techniques? – • – • – 74 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg • 75 | PA193 - Buffer overflow, string vulnerabilities question •Questions P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg • 76 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Additional reading •Compiler Security Checks In Depth (MS) –http://msdn.microsoft.com/en-us/library/aa290051%28v=vs.71%29.aspx •GS cookie effectiveness (MS) –http://blogs.technet.com/b/srd/archive/2009/03/16/gs-cookie-protection-effectiveness-and-limitatio ns.aspx •Design Your Program for Security –http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/internals.html •Smashing The Stack For Fun And Profit –http://www-inst.cs.berkeley.edu/~cs161/fa08/papers/stack_smashing.pdf •Practical return oriented programming –http://365.rsaconference.com/servlet/JiveServlet/previewBody/2573-102-1-3232/RR-304.pdf – – 77 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Books - optional •Writing secure code, chap. 5 •Security Development Lifecycle, chap. 11 •Embedded Systems Security, D., M. Kleidermacher • 78 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Tutorials - optional •Buffer Overflow Exploitation Megaprimer (Linux) –http://www.securitytube.net/groups?operation=view&groupId=4 •Tenouk Buffer Overflow tutorial (Linux) –http://www.tenouk.com/Bufferoverflowc/bufferoverflowvulexploitdemo.html •Format string vulnerabilities primer (Linux) –http://www.securitytube.net/groups?operation=view&groupId=3 •Buffer overflow in Easy RM to MP3 utility (Windows) –https://www.corelan.be/index.php/2009/07/19/exploit-writing-tutorial-part-1-stack-based-overflows/ – • 79 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg Heap overflow - references •Detailed explanation (Felix "FX" Lindner, 2006) –http://www.h-online.com/security/features/A-Heap-of-Risk-747161.html?view=print •Explanation in Phrack magazine (blackngel, 2009) –http://www.phrack.org/issues.html?issue=66&id=10#article •Defeating heap protection (Alexander Anisimov) –http://www.ptsecurity.com/download/defeating-xpsp2-heap-protection.pdf •Diehard – drop-in replacement for malloc with memory randomization –http://plasma.cs.umass.edu/emery/diehard.html –https://github.com/emeryberger/DieHard • 80 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg ROP - references •Explanation of ROP –https://www.usenix.org/legacy/event/sec11/tech/full_papers/Schwartz.pdf •Blind ROP –Return-oriented programming without source code –http://www.scs.stanford.edu/brop/ •Automatic search for ROP gadgets –https://github.com/0vercl0k/rp – – 81 | PA193 - Buffer overflow, string vulnerabilities P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg D:\Documents\Obrázky\eternalmemorywars.png SoK: Eternal War in Memory • • • • • • • • • • 82 | PA193 - Buffer overflow, string vulnerabilities http://www.cs.berkeley.edu/~dawnsong/papers/Oakland13-SoK-CR.pdf P:\CRCS\2012_0178_Redesign_loga_a_JVS\PPT_prezentace\sablona\pracovni\normalni.jpg SoK: Eternal War in Memory • 83 | PA193 - Buffer overflow, string vulnerabilities D:\Documents\Obrázky\memorywars_comparison.png http://www.cs.berkeley.edu/~dawnsong/papers/Oakland13-SoK-CR.pdf