csc 382: computer securityslide #1 csc 382 secure programming

78
CSC 382: Computer Security Slide #1 CSC 382 Secure Programming

Upload: leslie-horn

Post on 24-Dec-2015

254 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #1

CSC 382

Secure Programming

Page 2: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #2

Topics

1. Code Reviews.

2. Integer Overflows.

3. Race Conditions.

4. Secure File Usage.

5. Canonicalization.

Page 3: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #3

Code Auditing

Why code reviews?– HP and AT&T claim 20-30X more effective

than testing alone.– IBM discovers 82% of defects in reviews

before testing.

Code reviews are good for finding– Requirements errors.– Design flaws.

Page 4: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #4

Code Reviews: People

1. Moderator– Manages meeting; follows up on issues.

2. Reader– Paraphrases code during meeting.

– Not the author.

3. Recorder– Records bugs discovered.

4. Author– Provides context for code; answers questions.

– Makes corrections after code review.

Page 5: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #5

Code Review: Process• Initiation

– Author submits code for review.– Code must compile (w/o warnings), pass unit tests.

• Preparation– Reviewers read code and mark concerns.

• Meeting– 150-200 lines/hour.

• Rework– Author makes corrections based on bugs found in review.

• Followup– Moderator checks corrections.– Code sent to testing if corrections good.

Page 6: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #6

Code Review: ChecklistsSecurity reviews should include checklists ofcommon problems, including:

1. buffer overflows

2. integer overflows

3. input validation

4. checking return values

5. resource name canonicalization

6. race conditions

Page 7: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #7

Code Review: Problems

1. Requires substantial expertise in area of coding and security to be effective.

2. Human readers are fallible, and will miss mistakes.

Page 8: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #8

Static AnalyisSolution: Let a program analyze your sourcecode for security flaws.Range of approaches

1. Standard compiler warnings and type checking.

2. Lexing source checkers that look for bad names like strcpy() and gets().

3. Parsing source code checkers.4. Parsing checkers with annotations.5. Formal proof based program verification.

Page 9: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #9

Static Analysis Tools

Lexing source code checkers.– flawfinder– ITS4– RATS

Parsing checkers + annotation.– cqual– Fortify– splint

Page 10: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #10

login.cint validatePassword(const char *plain_pass) { return !strcmp( cipher_pass, crypt(plain_pass, cipher_pass) );}int login() {

int nAttempts=0;int maxAttempts=3;char password[64];int success=0; do { printf( "\npassword: " ); gets( password ); success = validatePassword( password ); if( success ) break; } while( ++nAttempts < maxAttempts ); return success;}void main(int argc, char *argv[]) { int success = 0; char username[64]; strcpy( username, argv[1] ); success = login(); if( success ) printf( "Login successful, %s!\n", username ); else printf( "Too many failed login attempts.\n" ); return( success );}

Page 11: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #11

login.c: splint outputSplint 3.1.1 --- 15 Jun 2004

login.c: (in function validatePassword)login.c:22:13: Operand of ! is non-boolean (int): !strcmp(cipher_pass,

crypt(plain_pass, cipher_pass)) The operand of a boolean operator is not a

boolean. Use +ptrnegate to allow ! to be used on pointers. (Use -boolops to

inhibit warning)login.c:22:12: Return value type boolean does not

match declared type int: !strcmp(cipher_pass,

crypt(plain_pass, cipher_pass)) To make bool and int types equivalent, use

+boolint.

Page 12: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #12

login.c: splint outputlogin.c: (in function login)login.c:34:9: Use of gets leads to a buffer

overflow vulnerability. Use fgets instead: gets Use of function that may lead to buffer

overflow. (Use -bufferoverflowhigh to inhibit warning)login.c:34:9: Return value (type char *) ignored:

gets(password) Result returned by function call is not used.

If this is intended, can cast result to (void) to eliminate message. (Use -

retvalother to inhibit warning)login.c:36:13: Test expression for if not

boolean, type int: success Test expression type is not boolean or int.

(Use -predboolint to inhibit warning)

Page 13: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #13

login.c: splint outputlogin.c:43:6: Function main declared to return

void, should return int The function main does not match the expected

type. (Use -maintype to inhibit warning)login.c: (in function main)login.c:51:9: Test expression for if not boolean,

type int: successlogin.c:56:11: Return expression from function

declared void: (success) Types are incompatible. (Use -type to inhibit

warning)

Page 14: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #14

login.c: splint outputlogin.c:19:6: Variable exported but not used

outside login: cipher_pass A declaration is exported, but not used outside

this module. Declaration can use static qualifier. (Use -exportlocal to

inhibit warning)login.c:21:5: Function exported but not used

outside login: validatePassword login.c:23:1: Definition of validatePasswordlogin.c:25:5: Function exported but not used

outside login: login login.c:41:1: Definition of login

Finished checking --- 12 code warnings

Page 15: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #15

splint: Annotations

Annotations encoded as special comments.– /*@annotation@*/

Types of annotations– Add or suppress warning messages.– NULL pointer checking via /*@notnull@*/– Bounds checking:

• strcpy: /*@requires maxSet(s1) >= maxRead(s2) @*/

– User-defined• /*@tainted@*/ attribute

Page 16: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #16

What’s an Integer Overflow?

An integer overflow is when integer operations produce a value that exceeds the computer’s maximum integer value, causing the value to “wrap around” to a negative value or zero.

Page 17: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #17

Are Integer Overflows Important?

Broward County November 2004 election– Amendment 4 vote was reported as tied.– Software from ES&S Systems reported a large

negative number of votes.– Discovery revealed that Amendment 4 had

passed by a margin of over 60,000 votes.

Page 18: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #18

Computer Integers

Computer integers aren’t math integers– Limited precision: 8-bit to 64-bit

• See limits.h for min and max values.

– ISO C99 does not specify what happens when you store a value too large or too small.

• Most compilers ignore.

Two’s Complement Signed Integers– –x = (complement x) + 1– High bit is the sign bit.– Range: -2n .. 2n - 1

Page 19: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #19

32-bit Integer Quiz

1. What two non-zero integers x and y satisfy the equation x * y = 0?

2. What negative integer (-x) has no corresponding positive integer (x)?

3. List two integers x and y, such that x + y < 0.

4. What is the unique negative integer x that has the propery x + x = 0?

Page 20: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #20

Quiz Answers

1. 65536 * 65536 = 0

or 256 * 16777256 = 0

or any x * y = 232

2. -2147483648

3. 2147483647 + 1 = -2147483648

4. -2147483648 + -2147483648 = 0

Page 21: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #21

Why are Integer Overflows Dangerous?

1. Difficult to detect after they’ve happened.– C/C++ compilers generally ignore them.– Assembly code can check carry flag, but

C/C++ cannot without calling to assembly code.

2. Difficult to avoid.– Subtle bugs can result in integer overflows.

3. Often used to bypass security checks.– To permit buffer overflow attacks.

Page 22: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #22

Integer Comparisons

What’s wrong with the following code?

int safeStringCopy(char *str, int size) {char buf[64];if(size < sizeof(buf))

strcpy(buf, str);return buf;

}

Page 23: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #23

Integer Multiplication

What’s wrong with the following code?

int copyArray(int *array, int len){ int *myarray, i; myarray = malloc(len * sizeof(int)); if(myarray == NULL)

return -1;for(i = 0; i < len; i++)

myarray[i] = array[i];return myarray;

}

Page 24: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #24

Integer Addition

What’s wrong with the following code?

char *safeStrCat(char *s1, size_t len1, char *s2, size_t len2)

{ if( len1 + len2 + 1 > 512 ) return NULL; char *out=(char*)malloc(len1+len2+1); strcpy(out, s1); strcat(out, s2); return out;}

Page 25: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #25

MS JScript Overflow Attack

• JScript sparse arraysvar arr = new Array();arr[1] = 1;arr[2] = 2;arr[0x40000001] = 3;

• C++ code that implements sort methodbuf = (Element *)malloc(ElementCount * sizeof(Element));

• What happens ?0x40000001 * 0x00000014 = 0x00000014

Only 20 bytes allocated for buffer.

Page 26: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #26

Integer Overflow Defence

1. Safe unsigned addition (x+y)– Test if x + y > MAX_INT– How can we do the test and avoid overflows?

• x > MAX_INT - y

2. Safe unsigned subtraction (x-y)– Check if x < y

3. Safe unsigned multiplication (x*y)– Check if x > MAX_INT/y

4. Signed arithmetic more complex

Page 27: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #27

Integer Overflow Defence

Use a safer language– Most languages (C/C++, Java, etc) vulnerable.– Python is not vulnerable.

Use a safe library– David LeBlanc’s SafeInt class for C++

Page 28: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #28

What is a Race Condition?

• Incorrect behavior arising from unexpected dependency on relative timing of events.– Timing of events on multitasking system depends on

system load.

– Events generally happen in the expected order.

• On multitasking system, processes can be interrupted between any two instructions.– Private resources (memory) are protected.

– Shared resources (filesystem, network) can be modified by interrupting process.

Page 29: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #29

Java Servlet Hit Counter// Example from BSS, pp. 210-211public class Counter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest in,

HttpServletResponse out) throws ServletException, IOException {

out.setContentType("text/plain"); Printwriter p = out.getWriter(); count++; p.println(count + " hits so far!"); }}

Page 30: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #30

Analysis of Hit Counter

Assumes variable count does not change between incrementing and printing.– What if users A + B hit page at approximately

the same time?– A is first, count = 1– B is second, before println occurs, count = 2– A sees “2 hits so far”– B sees “2 hits so far”

Page 31: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #31

Window of Vulnerability

• Period of time when violating assumption about order of events will produce incorrect behavior.

• Generally <1s under ordinary conditions.

• What if web site is popular?

• What if attacker can send many requests?

Page 32: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #32

Window of Vulnerability

1. Attacker can increase increase size of window by slowing down system.

2. Attacker can increase window size by controlling execution with SIGSTOP/SIGCONT.

3. Attacker can attempt exploit many times.

Page 33: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #33

Window of Vulnerability

You must reduce the window of vulnerability to zero for system to be secure.

Page 34: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #34

Critical Sections

• Segment of code which may only be executed by one thread at a time.

• Critical Section executes atomically from viewpoint of other threads.

• Performance Impact– Other threads must wait for thread in critical

section to finish executing.– Limit critical section size.

Page 35: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #35

Synchronized Hit Counter// Example from BSS, p. 213public class Counter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest in, HttpServletResponse

out) throws ServletException, IOException { int mycount; out.setContentType("text/plain"); Printwriter p = out.getWriter(); synchronized(this) { mycount = ++count; } p.println(mycount + " hits so far!"); }}

Page 36: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #36

Time of Check, Time of Use

TOCTOU Security Flaw:1. Check security of resource.

2. Use resource.

What if attacker invalidates security– After security check– Before use

Page 37: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #37

UNIX Exampleint main( int argc, char *argv[] ){if(access( argv[1], W_OK ) == 0)

{fd = open( argv[1], O_WRONLY );writeFile(fd);

} else {perror(“Permission denied.\n”);exit(1);

}}

Page 38: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #38

Analysis

• Window of Vulnerability– Time between access() and open()

• Exploit: rebind filename– Give filename as argument: /tmp/x– After access(),

• delete /tmp/x• create link named /tmp/x pointing at root-owned

file like /etc/passwd, /.rhosts

• Example: xterm log file race condition

Page 39: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #39

ex: passwd [Bishop, 1996]

passwd: allows user-specified passwd file

Normal functioning1. opens passwd file + reads user entry; closes

2. creates + opens temp file ptmp in same directory

3. opens passwd file again, then copies contents to ptmp with user changes

4. closes both passwd and ptmp files; renames ptmp to passwd

Page 40: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #40

ex: passwd (cont.)

Attacker Goal: rewrite /user/.rhosts– contents: localhost attacker :::::– exploit: rlogin –l user localhost

Plan of Attack– Create exploit .rhosts file in attack directory– Specify passwd file to be in attack directory– steps 1 + 3: directory containing passwd file is

attack directory– steps 2 + 4: directory containing passwd:/user

Page 41: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #41

passwd attack setupmkdir attackdirecho “localhost attacker :::::” > attack/.rhosts

# want link to point to attackdir for step 1

ln –s attackdir link# specify password file using symlink dirpasswd link/.rhosts

Page 42: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #42

passwd: step by step

1. passwd program opens + reads link/.rhostsactual file: attackdir/.rhosts

2. Attacker changes link to point to /user

3. passwd program creates + opens link/ptmpactual file: /user/ptmp

4. Attacker changes link to point to attackdir

Page 43: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #43

passwd: step by step

• passwd program opens link/.rhosts– actual file: attackdir/.rhosts

• passwd program copies contents to ptmp– actual file: /user/ptmp

• Attacker changes link to point to /user

Page 44: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #44

passwd: step by step

• passwd program closes link/.rhosts + ptmp

• passwd program renames ptmp to link/.rhosts– actual file: /user/.rhosts

• “Password” file is now target user’s .rhosts– We can now rlogin to their account without

needing a password

Page 45: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #45

UNIX File Binding

UNIX provides two forms of naming– pathname

• universal mapping of names to objects

• indirect: requires parent directories to identify file

• mapping can be changed by another process

– file descriptor• per-process mapping of identifiers to objects

• direct: file descriptor points directly to object

• mapping cannot be changed by another process

Page 46: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #46

TOCTOU Binding Flaws

• Occur with two sequential system calls:– both refer to same object by pathname: insecure– one binds file descriptor to pathname, other

uses that file descriptor: secure– one uses file descriptor, other uses pathname:

insecure

• Solution: use calls that use file descriptors• Problem: sometimes no alternative to

pathnames

Page 47: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #47

TOCTOU Binding Flaws

Solution: use calls that use file descriptors– fchmod() instead of chmod()– fchown() instead of chown()– fstat() instead of stat()

Problem: sometimes no alternative to pathnames– link(), unlink(), symlink()– mkdir(), rmdir()

Page 48: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #48

Safe File Open

1. lstat() file before opening, saving stat structure

2. open() file, obtaining file descriptor• use O_CREAT | O_EXCL flags

• specify permissions in open() call or use safe umask

3. fstat() on file descriptor, saving stat structure

4. Compare permissions (st_mode), inode (st_ino), and device (st_dev) of two stat structures. If identical, we know lstat() happened on file we opened and that we did not follow a link.

Page 49: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #49

Safe setuid File Operations

• access() is insecure, what else is there?

• Change process EUID/EGID to the real UID/GID we want to use for check– setreuid( EUID, UID )

• Perform file operations (access checks will apply as normal to EUID/EGID).

• Change back to privileged EUID/EGID when privileges needed again– setreuid( UID, EUID )

Page 50: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #50

When you have to use pathnames

• Keep files in their own, safe directory.– only UID of program can access

• Ensure attacker cannot modify parent directories.– mkdir safe directory– chdir safe directory

– chdir .. + check permissions until reach root

Page 51: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #51

Temporary Files

• C library tmpfile(), mkstemp() insecure

• Use safe open techniques.

• If you must use shared directory:– Create unique name

• application prefix

• base64-encoded random suffix

– Use safe umask: 0066– Delete file immediately with unlink()

Page 52: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #52

Non-File Race Conditions

Replicated Database Servers– Spend money on one server, then another

before replication occurs.

Page 53: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #53

Discussion Problem You discover a flaw in a program that you use for

your job. The flaw will let an unauthorized user usurp control of the system. Do you keep quiet to avoid letting anyone else know about the flaw, or do you notify your company, notify the software vendor, or post the flaw to the Internet?

1. What if the flaw could be eliminated by proper configuration of the program? How would that change your answer?

2. What if exploitation of the flaw cannot be blocked by configuration and cannot be detected by the software’s auditing features? How would that change your answer?

Page 54: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #54

The Problem with Names

Resources can be referenced by many different names:– config– ./config– /etc/program/config– ../program/config– /tmp/../etc/program/config

Page 55: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #55

The Problem with Names

• How do you make correct access control decisions when there are so many names?

• Canonical Name: standard form of a name– Generally simplest form

• Canonicalization: resolving a different form of a name into the canonical form

Page 56: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #56

Common Naming Issues

• . represents current directory

• .. previous directory

• Case sensitivity

• PATH variables

• Windows 8.3 representation of long names

• URL encoding

Page 57: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #57

A Problem

• Ftp access control– /home/ftp/public: anonymous access– /home/ftp/private: requires password

• What happens when user requests:– /home/ftp/public/../private

• “..” allows user to step out of public directory, then back into private

Page 58: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #58

Solutions

• Add /home/ftp/public/../private to ACL

• Remove “..” characters from filenames

• What about “.”?

• What about symbolic links?

Page 59: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #59

Another problem

What happens when user requests?– /home/PrivaTe

Is filesystem case sensitive?– HFS+ filesystem case insensitive– Apache web server case sensitive– Bypass Apache access control on “private” by

specifying “PrivaTe”

Page 60: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #60

Never trust $PATH

• Don’t use bare filenames for programs– PATH will be used to find them– What if attacker sets PATH=/home/hacked/bin?

• Use “/bin/passwd” instead of “passwd”• What if program you call uses bare filenames?• Set PATH in your code to safe value:

– PATH=/bin:/usr/bin

Page 61: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #61

Win/32 Long Filenames

• FAT32/NTFS autogenerate 8.3 backwards compatible name– 1st 6 chars, ~, counter digit, 1st 3 chars of ext– Illegal characters (i.e., spaces) removed too

• File can be accessed with both names– If you only protect the long name, attacker can

access file using the short 8.3 format name

Page 62: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #62

Trailing Characters

• Win32 allows trailing dot (.) or backslash(\) on filenames– Opening file “file.exe.” actually opens “file.exe”

• Trailing dot(.) in DNS names– Dot(.) is the DNS root, but usually omitted

– Web browsers accept “www.google.com.” as “www.google.com”

Page 63: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #63

URLs

<scheme>://<authority><path>?<query> – <scheme> required

• examples: ftp, http, https

– <authority>: <userinfo>@<host>:<port>• <userinfo> and <port> are optional

• example: username:[email protected]:8001

• <userinfo> often ignored by non-auth servers

• <host> can be encoded as DNS name or IP address

Page 64: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #64

URLs

<path>– Case sensitivity is OS/server dependent

– OSes use different special chars: / versus \

– Backtracking: “..”

– Special characters (e.g., space) must be escaped

– Any character can be escaped: %5C = \

<query>– Any character can be escaped, including “?” separating

<path> and <query> components

Page 65: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #65

Win/Apache Directory Traversal

• Apache 2.0.39 and earlier

• To view the file winnt\win.ini: http://127.0.0.1/error/%5c%2e%2e%5c%2e%2e%5c%2e%2e%5c%2e%2e%5cwinnt%5cwin.ini

which is the escaped form of

• http://127.0.0.1/error/\..\..\..\..\winnt\win.ini

Page 66: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #66

More URL Tricks

IP address representations– Dotted quad (decimal, octal, hexadecimal)– Hexadecimal without dots (with left padding)– dword (32-bit int)

Examples: www.eecs.utoledo.edu– 131.183.19.14 (dotted quad)– 0xDEDA83B7130E (hexadecimal + padding)– 2209813262 (dword)

Page 67: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #67

Humans Use Names Too

The Phishing Scam– Phisher spams internet with emails asking user

to click to update profile/perform transaction– Link is obfuscated with <userinfo>

• www.citibank.com%01@ 2209813262 /login.hml

• IE will not display URL after %01 character

– Link sends user to site designed to look like real site, but that will collect info for phisher

Page 68: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #68

Internationalization Issues

UTF-8: Unicode Transformation Format– Alternative to UTF-16/32, allowing ASCII

characters to be expressed unchanged– Characters may be from 1 to 6 bytes long– Multibyte characters have MSB set (80-FF)– Problem: Multibyte encoding offers multiple

ways to encode ASCII characters

Page 69: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #69

Internationalization Issues

UTF-8 multibyte LF (0A) sequences:– 0xC0 0x8A – 0xE0 0x80 0x8A – 0xF0 0x80 0x80 0x8A – 0xF8 0x80 0x80 0x80 0x8A – 0xFC 0x80 0x80 0x80 0x80 0x8A

Many parsers accept overlong sequences

Page 70: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #70

IIS Directory Traversal

• MS Internet Information Server 4 + 5

• Execute shell command: http://127.0.0.1/scripts/..%c0%af../winnt/system32/cmd.exe

• where %c0%af is the 2-byte UTF-8 encodingof “/”

Page 71: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #71

Naïve Solution to Name Issues

Remove or check for known insecure elements in original pathname.– “..”– “/cgi-bin” or other protected directories– “.exe” or other special filename extensions– Trailing “.” or “\”– URI-escaped characters

Page 72: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #72

Problems with Naïve Approach

• Too many ways to represent the name.

• Attempts to deny bad names instead of allowing known valid names.– You will miss boundary cases.

• Operating systems have different ways of representing filenames—what about multi-platform applications?

Page 73: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #73

Don’t Use Names

• Avoid canonicalization issues entirely by not basing access control on names.– Filesystem ACLs instead of access control

inside your application.– IP addresses instead of DNS names.

• However, you may need to use names for some purposes…

Page 74: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #74

Canonicalization

1. Resolve all names to canonical name using operating system functions.

2. Use standard OS function where available.

3. Allow access to correct canonical name.

4. Deny access to all other names.

Page 75: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #75

UNIX Canonicalizationrealpath() resolves all links, symbolic links, relativepaths, as well as “.” and “..”

#include <stdlib.h> #include <sys/param.h>

char *realpath (const char *file_name, char *resolved_name);

resolved_name must be MAXPATHLEN bytes long to avoid apotential buffer overflow.

Page 76: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #76

Win32 Canonicalization

• Resolve links, “..”, trailing dot(.), and spaces– GetFullPathName()

• Canonicalize 8.3 format names– GetLongPathName()

• Check path length < MAX_PATH• Full checking is complex

– CleanCanon.cpp: Howard & Leblanc, Writing Secure Code, pp. 386-390

Page 77: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #77

Key Points

1. Integer overflows.– Understand binary arithmetic properties.

2. Race conditions.– TOCTOU security flaws.

3. Secure file usage.– Canonicalize names.– Never deference a file by name more than once.– Never trust a world-writable directory.

Page 78: CSC 382: Computer SecuritySlide #1 CSC 382 Secure Programming

CSC 382: Computer Security Slide #78

References1. “Broward Vote-Counting Blunder Changes Amendment Result,”

http://www.news4jax.com/politics/3890292/detail.html, 2004.2. “How to Obscure Any URL: How Spammers And Scammers Hide and Confuse,”

http://www.pc-help.org/obscure.htm3. blexim, “Basic Integer Overflows,” Phrack 60, 2002.4. Bishop, Matt, Introduction to Computer Security, Addison-Wesley, 2005.5. Carbullito, Ken, [letter from ES&S to Guilford BOard of Elections],

http://dream.sims.berkeley.edu/~jhall/nqb2/index.php?title=guilford_ess_letter, 2004.6. Graff, Mark and van Wyk, Kenneth, Secure Coding: Principles & Practices, O’Reilly, 2003.7. Howard, Michael, “Reviewing Code for Integer Manipulation Vulnerabilities,”

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/secure04102003.asp, 2003.

8. Howard, Michael and LeBlanc, David, Writing Secure Code, 2nd edition, Microsoft Press, 2003.9. LeBlanc, David, “Integer Handling with the C++ SafeInt Class,”

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/secure01142004.asp?frame=true&hidetoc=true

10. Viega, John, and McGraw, Gary, Building Secure Software, Addison-Wesley, 2002.11. Wheeler, David, Secure Programming for UNIX and Linux HOWTO,

http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/index.html, 2003.