FIT3173: Other Exploits, Memory Defense and Secure Implementation
Dr Xiao of Software Systems and Cybersecurity
Faculty of Information Technology
Copyright By PowCoder代写 加微信 powcoder
Learning Outcomes of This Lecture
• Show some other Memory Exploits beyond BOF
• Understand the meaning of memory safety
• Analyze violations of temporal safety and spatial safety
• Understand the meaning of type safety
• Know how to adopt secure coding principles and rules in programming • Evaluate the vulnerability of command injection and race condition
Other Memory Exploits
• Format string vulnerabilities • Integer overflow
• Read overflow
Format Strings
• C’s printf family supports formatted I/O: print data in specific formats
• Syntax: printf(“format string”,
• Output: 12 0x0000000c hello • Format string is optional
• If not found, variable is printed in default format, which opens a door to format string injection attack!
What’s the difference?
Attacker controls the format string
• %x – Read data from the stack
• %c – Read character from memory
• %n – Write an integer to locations in memory
$ ./fmt_vuln %08x.%08x.%08x.%08x.%08x%08x.%08x.% 08x.%08x.%08x.%08x.%08x.%08x.%08x.%08 x.%08x
The right way to print user-controlled input:
%08x.%08x.%08x.%08x.%08x%08x.%08x.% 08x.%08x.%08x.%08x.%08x.%08x.%08x.%08 x.%08x
The wrong way to print user-controlled input:
bffb9aac.6474e552.0045465d.005bdbaf.0044 b5dc00001e3c.bffb9f54.bffb9cfc.00000000.00 000001.78383025.3830252e.30252e78.252e7 838.2e783830.78383025
Example Cont.
• %x – Read data from the stack
• %c – Read character from memory
• %n – Write an integer to locations in memory
$ ./fmt_vuln %c.%c.%c.%c.%c.%c.%c.%c.%c.%c.% c.%c.%c.%c.%c.%c
The right way to print user-controlled input:
%c.%c.%c.%c.%c.%c.%c.%c.%c.%c.% c.%c.%c.%c.%c.%c
The wrong way to print user-controlled input:
.R.]…<..\.. .%.c...%.c..
Integer Overflow • Integer variables commonly used for array indexing and arithmetic
• unsigned int: 32 bit [0, 232-1] • int: 32 bit [-231, 231-1]
• short: 16 bit [-215, 215-1]
• unsigned short: 16 bit [0, 216-1]
• Integer variables can overflow if one writes a value larger (or smaller) than the maximum (or minimum) possible value for the integer type
• Maliciously chosen integer overflows can also change program behaviour, and can be exploitable by attackers
Q: what is the output of this function?
num_mul = 0x0
Q: which line is vulnerable?
• With input:
• len1 = 0x104 (= 256 + 4)
• len2 = 0xfffffffc (= 232 – 4) • Length sum overflows:
• len1 + len 2 = 256
• Bypass the buffer overflow check
• How to fix it?
Q: which line is vulnerable?
• With input:
• len = 0xffffffff (negative number)
• Bypass the buffer overflow check
• Casting len as an unsigned int when executing memcpy
• How to fix it?
Q: which line is vulnerable?
• if nresp is set as 1073741824 (0x40000000)
• then nresp*sizeof(char*) overflows to become 0
• subsequent writes to allocated response overflow it
• How to fix it?
Array Indexing Errors “Negative indexing” errors:
• Attack input pos = -1 passes if test, and overflows table
• Arrays in C are start at 0 and indexed by pointer arithmetic
• table[-1] overflows table towards lower memory addresses!
Array Indexing Errors “Off by One” errors:
• Arrays in C start at 0, so kbuf[799] is last character of kbuf
• loop overflows kbuf by one int!
Read Overflow
read integer read message
echo message
Q: Is this program vulnerable?
Read Overflow
read integer read message
echo message
% ./echo-server
every good boy does fine
ECHO: |every good boy does fine| 10
hello there
ECHO: |hello ther|
ECHO: |hello..here..y does fine.|
Read Overflow
read integer read message
echo message
% ./echo-server
every good boy does fine
ECHO: |every good boy does fine| 10
hello there
ECHO: |hello ther|
ECHO: |hello..here..y does fine.|
OK: input len < buf size
Leak data of previous message: len > size
Low-level Attacks in Common
• The attacker is able to control some data that is used by the program
• The use of that data permits unintentional access to some memory area in the program
• past a buffer
• to arbitrary positions on the stack
Low-level Attacks due to Lack of Memory Safety
• Memory-safe program:
• only creates pointers through standard means, e.g., p = malloc(…), or p = &x, or p = &buf[5], etc.
• only uses a pointer to access memory that belongs to that pointer
• Temporal safety (unintended time) and spatial safety (unintended address)
Spatial Safety • View pointers as triples (p,b,e)
• p is the actual pointer
• b is the base of the memory region it may access • e is the extent (bounds) of that region
• Legitimate access: iff b <= p <= e - sizeof (typeof(p))
• Operations:
• Pointer arithmetic increments p, leaves b and e alone; • Using &: e determined by size of original type
Spatial Safety violation: Buffer overflow
• Overrunning the bounds of the source and/or destination buffers implies either src or dst is illegal.
Temporal Safety
• A temporal safety violation occurs when trying to access undefined memory
• Spatial safety assures it was to a legal region
• Temporal safety assures that region is still in play • Memory regions either defined or undefined
• Defined means allocated (and active)
• Undefined means unallocated, uninitialised, or deallocated • Pretend memory is infinitely large
Violation of Temporal Safety: Dangling Pointers
Accessing a freed pointer violates temporal safety
Accessing uninitialised pointers is also not OK
Integer Overflows
overflows to become 0 Is memory safe?
buffer with size 0 violation...
• Integer overflows often enable buffer overflows
• Happens often enough we think of them independently
Memory Safety for C
• C/C++: not memory safe
• You can write memory safe programs ... (how to guarantee that?)
• Compilers could add code to check for violations
• An out-of-bounds access would result in an immediate failure
• Performance has been the limiting factor
• Work by Jones and Kelly in 1997 adds 12x overhead, and valgrind memcheck adds 17x overhead
Recent Progress • CCured(2004),1.5xslowdown
• But no checking in libraries
• Compiler rejects many safe programs • Softbound/CETS(2010):2.16xslowdown
• Complete checking
• Highlyflexible
• Intel MPX hardware instruction support (2015) from Skylake
• Hardware support to make checking faster
• Intel has listed MPX as removed in 2019 and onward hardware (too many flaws in the approach)
Type Safety
• Each data object is ascribed a type
• Operations on the object are always compatible with the object’s type • Type safety is stronger than memory safety
C/C++ is not type safe
• C/C++ is designed for high performance
• Manual memory management: interaction with low-level memory
• Typical enforcement of type safety is expensive
• Garbage collection avoids temporal violations
• Bounds and null-pointer checks avoid spatial violations
• Hiding representation (next page) may inhibit optimisation
Dynamically Typed Languages
• Dynamically typed languages, e.g., Ruby and Python
• do not require declarations that identify types, can be viewed as type safe
• Each object has one type: Dynamic
• Each operation on a Dynamic object is permitted, but may be unimplemented (checked at the runtime)
Secure Coding in C
• Developers must use discipline, because the programming language itself provides few guarantees
• Good reference guide: CERT C Coding Standard
https://wiki.sei.cmu.edu/confluence/display/c
• Combine with advanced code review and testing (will talk about it later)
Design VS Implementation
• We strive to follow principles and rules
• A principle is a design goal with many possible manifestations
• A rule is a specific practice that is consonant with sound design principles
• Here, we look at rules for good C coding
• to avoid implementation errors that result in violations of memory safety
General Principle: Robust Coding
• Like defensive driving
• Avoid depending on anyone else around you
• If someone does something unexpected, your program will not crash (or worse) • It is about minimising trust!
• Each module pessimistically checks its assumed preconditions (on outside callers)
• Even if you “know” users input will not send a NULL pointer
• Sometimes, it is better to throw an exception (or even exit) than run malicious code
Rule: Enforce Input Compliance
read integer read message
sanitise input to be compliant
echo message
Rule: Use Safe String Functions
Traditional string library routines assume target buffers have sufficient length
Rule: Use Safe String Functions
Traditional string library routines assume target buffers have sufficient length
Safe versions check the destination length
• Replacements: strcat->strlcat, strcpy->strlcpy, strncat->strlcat, strncpy- >strlcpy, sprintf->snprintf, vsprintf->vsnprintf, get->fgets
Rule: Do not forget NUL terminator
Strings require one additional character to store the NUL terminator
Rule: Do not forget NUL terminator
Strings require one additional character to store Using safe string library calls will catch this the NUL terminator mistake
Rule: Understand Pointer Arithmetic
pointer arithmetic multiplies by the sizeof the type
Rule: Understand Pointer Arithmetic
pointer arithmetic multiplies by the sizeof the type use the right number
More Rules
• Use NULL after free
• int *p = malloc (sizeof(int)); free (p); p=NULL; // defend against bad deref
• Use safe libraries (despite some performance loss)
• safe string libs: C++ std::string, very secure ftp (vsftp) string lib
• networking: Google protocol buffers, Apache Thrift (ensuring input validation)
More Vulnerabilities
• Command injection • Race condition
SetUID: UNIX File Access Control
• Each file has owner and group • Permissions set by owner
• Read, write, execute
• Owner, group, other
• Represented by vector of four octal values (12 bits)
• Only owner, root can change permissions
• This privilege cannot be delegated or share
• Chmod is the commend to change the access permission to file system objects.
•Chmod 4755 program
• Each octal number of 4755 in binary
• “5”-> 101: users in the other groups with access r and x
• “5”-> 101: users in the same group of owner with access r and x
• “7”-> 111: owner has access r, w, and x
• “4” -> 100: setuid: when user runs the program, the runtime owner (root) permission is given for this program.
OS Command Injection
• Q: What does this program do?
• Q: What’s the vulnerability in this program?
OS Command Injection
• Allows to run a program in the current directory and report the execution time (by Unix time command).
• What happens if this program has its setuid bit set?
• implies that this program will run with the privileges of the owner – say root/administrator
• Consider the input to the program • xx;cat /etc/shadow
• You get the encrypted password file, since the programs runs with root privileges!
Prevent Command Injection
• Carefully sanitise all user input data.
• If you can avoid passing user-given arguments to OS programs, you should consider doing so.
• Solution: Use an OS command execution API that takes OS command and arguments as separate parameters: not to be interpreted as a command
• E.g., in C, use one of “exec” functions instead of “system”:
• E.g., int execl(char const *path, char const *arg0, char const *arg1, …);
• Alternately, if that is not possible, be sure to strip out potentially damaging characters such as semicolons, or other separators which can be used to run additional commands.
• In Unix, this includes pipes (|), and ampersand (&).
Prevent Command Injection
• The best way to accomplish this is with a white list.
• For the filename examples given earlier, maintain a list of acceptable file names (if that is possible) and check that the input matches an entry in this list exactly. Everything else needs to be discarded as an unsafe operation.
Race Condition Vulnerability
• Happens when:
• Multiple processes access and manipulate the same data concurrently. • The outcome of execution depends on a particular order.
• If a privileged program has a race condition, the attackers may be able to affect the output of the privileged program by putting influences on the uncontrollable events.
• A Special Type of Race Condition
• Time-Of-Check To Time-Of-Use (TOCTTOU)
• Occurs when checking for a condition before using a resource.
Race Condition Vulnerability
• Root-owned Set-UID program. • Effective UID : root
• Real User ID : seed
• The above program writes to a file in the /tmp directory (world-writable)
• As the root can write to any file, The program ensures that the real user has permissions to write to the
target file.
•access() system call checks if the Real User ID has write access to /tmp/X.
• After the check, the file is opened for writing.
• open() checks the effective user id which is 0 and hence file will be opened.
Race Condition Vulnerability
• Goal : To write to a protected file like /etc/passwd.
• To achieve this goal we need to make /etc/passwd as our target file without changing the file name in the program.
• Symbolic link (soft link) helps us to achieve it.
• It is a special kind of file that points to another file.
Race Condition Vulnerability
• As the program runs billions of instructions per second, the window between the time to check and time to use lasts for a very short period of time, making it impossible to change to a symbolic link
• If the change is too early, access() will fail.
• If the change is little late, the program will finish using the file.
Race Condition Vulnerability
• To win the race condition (TOCTTOU window), we need two processes :
• Run vulnerable program in a loop
• Run the attack program
Understanding the Attack
Let’s consider steps for two programs :
A1 : Make “/tmp/X” point to a file owned by us A2 : Make “/tmp/X” point to /etc/passwd
V1 : Check user’s permission on “/tmp/X”
V2 : Open the file
Attack program runs: A1,A2,A1,A2…….
Vulnerable program runs : V1,V2,V1,V2…..
As the programs are running simultaneously on a multi-core machine, the instructions will be interleaved (mixture of two sequences)
A1, V1 , A2, V2 : vulnerable prog opens /etc/passwd for editing.
Countermeasures
• Atomic Operations: To eliminate the window between check and use:
o E.g. f = open(file, O_CREAT | O_EXCL)
• Repeating Check and Use: To make it difficult to win the “race”.
o Check using access() more than one time.
• Sticky Symlink Protection: To prevent creating symbolic links.
• Principles of Least Privilege: To prevent the damages after the race is won by the attacker→ include temporary privileges within the vulnerable program (seteuid() function)
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com