Presentation is loading. Please wait.

Presentation is loading. Please wait.

Secure Coding Practices (and Other Good Things)

Similar presentations


Presentation on theme: "Secure Coding Practices (and Other Good Things)"— Presentation transcript:

1 Secure Coding Practices (and Other Good Things)
Vulnerability Assessment and Secure Coding Practices Secure Coding Practices (and Other Good Things) James A. Kupsch Barton P. Miller Computer Sciences Department University of Wisconsin Elisa Heymann Computer Architecture and Operating Systems Department Universitat Autònoma de Barcelona The 4th DIRAC User Workshop CERN May 28, 2014 1 1

2 Who we are Bart Miller Jim Kupsch Vamshi Basupalli Josef Burger
Elisa Heymann Eduardo Cesar Manuel Brugnoli Max Frydman 2

3 Vulnerability Assessment and Secure Coding Practices
What do we do Assess Middleware: Make cloud/grid software more secure Train:  We teach tutorials for users, developers, sys admins, and managers Research: Make in-depth assessments more automated and improve quality of automated code analysis Make cloud/grid software more secure Make in-depth assessments more automated Teach tutorials for users, developers, admin, managers: Security risks Vulnerability assessment Secure programming

4 Our experience Condor, University of Wisconsin Batch queuing workload management system 15 vulnerabilities KLOC of C and C++ SRB, SDSC Storage Resource Broker - data grid 5 vulnerabilities KLOC of C MyProxy, NCSA Credential Management System 5 vulnerabilities KLOC of C glExec, Nikhef Identity mapping service 5 vulnerabilities KLOC of C Gratia Condor Probe, FNAL and Open Science Grid Feeds Condor Usage into Gratia Accounting System 3 vulnerabilities KLOC of Perl and Bash Condor Quill, University of Wisconsin DBMS Storage of Condor Operational and Historical Data 6 vulnerabilities KLOC of C and C++ Note some just “admin” software. Assessed and remediated. 4 4 4

5 Our experience Wireshark, wireshark.org Network Protocol Analyzer 2 vulnerabilities KLOC of C Condor Privilege Separation, Univ. of Wisconsin Restricted Identity Switching Module 2 vulnerabilities KLOC of C and C++ VOMS Admin, INFN Web management interface to VOMS data vulnerabilities KLOC of Java and PHP CrossBroker, Universitat Autònoma de Barcelona Resource Mgr for Parallel & Interactive Applications 4 vulnerabilities KLOC of C++ ARGUS 1.2, HIP, INFN, NIKHEF, SWITCH gLite Authorization Service vulnerabilities KLOC of Java and C 5 5 5

6 Our experience VOMS Core INFN Virtual Organization Management System vulnerability 161 KLOC of Bourne Shell, C++ and C iRODS, DICE Data-management System vulnerabilities KLOC of C and C++ Google Chrome, Google Web browser vulnerability KLOC of C and C++ WMS, INFN Workload Management System in progress KLOC of Bourne Shell, C++, C, Python, Java, and Perl CREAM, INFN Computing Resource Execution And Management 5 vulnerabilities KLOC of Bourne Shell, Java, and C++ 6 6 6

7 Overview Some basics and terminology Thinking like an attacker
“Owning the bits” Thinking like an analyst A brief overview of in-depth vulnerability assessment Thinking like a programmer/designer Secure programming techniques One for each day! 7

8 What is Software Security?
Software security means protecting software against malicious attacks and other risks. Security is necessary to provide availability, confidentiality, and integrity. One for each day! 8

9 What is a Vulnerability?
“A vulnerability is a defect or weakness in system security procedures, design, implementation, or internal controls that can be exercised and result in a security breach or violation of security policy.” - Gary McGraw, Software Security One for each day! 9

10 What is a Vulnerability?
A weakness allowing a principal (e.g. a user) to gain access to or influence a system beyond the intended rights. Unauthorized user can gain access. Authorized user can: gain unintended privileges – e.g. root or admin. damage a system. gain unintended access to data or information. delete or change another user’s data. impersonate another user. One for each day! 10

11 What is a Weakness (or Defect or Bug)?
Software bugs are errors, mistakes, or oversights in programs that result in unexpected and typically undesirable behavior. The Art of Software Security Assessment Vulnerabilities are a subset of weaknesses. Almost all software analysis tools find weaknesses not vulnerabilities. One for each day! 11

12 What is an Exploit? The process of attacking a vulnerability in a program is called exploiting. The Art of Software Security Assessment The attack can come from a program or script human with interactive access One for each day! 12

13 Cost of Insufficient Security
Attacks are expensive and affect assets: Management. Organization. Process. Information and data. Software and applications. Infrastructure. Assets: Any resource or capability. Often they are given a financial value. Security is about protecting assets. Some assets are intangible: e.g. reputation. Reputation could very quickly be damaged if there were to be an incident leading to a large loss of data, or if the infrastructure were to be used to carry out a major cyber attack on other systems… Organization: Complex systems rely on widespread organization to keep everything working together. Access to resources by membership of a VO. Process: Defined process. E.g. Process for obtaining credentials. 13

14 Cost of Insufficient Security
Attacks are expensive and affect assets: Financial capital. Reputation. Intellectual property. Network resources. Digital identities. Services. Financial capital: Funding will happen if it’s felt that’s worth contributing. And confidence. And that benefits are worth the cost. Intellectual property: Includes copyrughted material and result of scientific work. Digital identities: Credentials and attributes enabling the authentication and authorization of users and services. Services: Provide access to, or privide information about, or control tangible assets. E.g. services neede to to use of some resources, to monitor them, also websites and wikis. 14

15 Vulnerability Assessment and Secure Coding Practices
Thinking about an Attack: Owning the Bits “Dark Arts” and “Defense Against the Dark Arts”

16 Learn to Think Like an Attacker

17 An Exploit through the Eyes of an Attacker
Vulnerability Assessment and Secure Coding Practices An Exploit through the Eyes of an Attacker Exploit, redefined: A manipulation of a program’s internal state in a way not anticipated (or desired) by the programmer. Start at the user’s entry point to the program: the attack surface: Network input buffer Field in a form Line in an input file Environment variable Program option Entry in a database Attack surface: the set of points in the program’s interface that can be controlled by the user.

18 Vulnerability Assessment and Secure Coding Practices
The Path of an Attack ... snprintf(buf,“/bin/mail %s”, argv[i]) p = requesttable; while (p != (struct table *)0) { if (p->entrytype == PEER_MEET) found = (!(strcmp (her, p->me)) && !(strcmp (me, p->her))); } else if (p->entrytype == PUTSERVER) found = !(strcmp (her, p->me)); if (found) return (p); else p = p->next; return ((struct table *) 0); The Attack Surface (user data enters here) The Impact Surface (bad thing happens) ... popen(buf, “w”)

19 Thinking Like an Analyst
Vulnerability Assessment and Secure Coding Practices Thinking Like an Analyst

20 Things That We All Know All software has vulnerabilities.
Critical infrastructure software is complex and large. Vulnerabilities can be exploited by both authorized users and by outsiders. VOY POR AQUÍ; PONER SLIDES RESUMEN DE FPVA. PONER Enganche con Secure Programing.

21 Key Issues for Security
Need independent assessment Software engineers have long known that testing groups must be independent of development groups Need an assessment process that is NOT based on known vulnerabilities Such approaches will not find new types and variations of attacks Street light story Everyone with a computer knows this. If you’re not seeing vulnerability reports and fixes for a piece of software, it doesn’t mean that it is secure. It probably means the opposite; they aren’t looking or aren’t telling. The grid community has been largely lucky (security through obscurity). Fact #1: Software engineers have long known that testing groups must be independent of development groups Fact #2: Designing for security and the use of secure practices and standards does not guarantee security Independent vulnerability assessment is crucial… …but it’s usually not done 21

22 Key Issues for Security
Automated Analysis Tools have Serious Limitations: While they help find some local errors, they MISS significant vulnerabilities (false negatives) Produce voluminous reports (false positives) Programmers must be security-aware Designing for security and the use of secure practices and standards does not guarantee security. Street light story Fact #1: Software engineers have long known that testing groups must be independent of development groups Fact #2: Designing for security and the use of secure practices and standards does not guarantee security Independent vulnerability assessment is crucial… …but it’s usually not done 22

23 Addressing these Issues
We must evaluate the security of our code The vulnerabilities are there and we want to find them first. Assessment isn’t cheap Automated tools create an illusion of security. You can’t take shortcuts Even if the development team is good at testing, they can’t do an effective assessment of their own code. If you want fillet mignon you can’t expect to pay hamburger prices. Doing tickles at yourself Fact #1: Software engineers have long known that testing groups must be independent of development groups Fact #2: Designing for security and the use of secure practices and standards does not guarantee security Independent vulnerability assessment is crucial… …but it’s usually not done 23

24 Addressing these Issues
Try First Principles Vulnerability Assessment A strategy that focuses on critical resources. A strategy that is not based on known vulnerabilities. We need to integrate assessment and remediation into the software development process. We have to be prepared to respond to the vulnerabilities we find. If you want fillet mignon you can’t expect to pay hamburger prices. Doing tickles at yourself Fact #1: Software engineers have long known that testing groups must be independent of development groups Fact #2: Designing for security and the use of secure practices and standards does not guarantee security Independent vulnerability assessment is crucial… …but it’s usually not done 24

25 Vulnerability Assessment and Secure Coding Practices
Roadmap Introduction Pointers and Strings Numeric Errors Race Conditions Exceptions Privilege, Sandboxing and Environment Injection Attacks Web Attacks

26 Discussion of the Practices
Vulnerability Assessment and Secure Coding Practices Discussion of the Practices Description of vulnerability Signs of presence in the code Mitigations Safer alternatives

27 Vulnerability Assessment and Secure Coding Practices
Pointers and Strings

28 Vulnerability Assessment and Secure Coding Practices
Buffer Overflows Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') Missing Authentication for Critical Function Missing Authorization Use of Hard-coded Credentials Missing Encryption of Sensitive Data Unrestricted Upload of File with Dangerous Type Reliance on Untrusted Inputs in a Security Decision The 2011 CWE/SANS Top 25 Most Dangerous Software Errors is a list of the most widespread and critical errors that can lead to serious vulnerabilities in software. They are often easy to find, and easy to exploit. They are dangerous because they will frequently allow attackers to completely take over the software, steal data, or prevent the software from working at all.

29 Vulnerability Assessment and Secure Coding Practices
Buffer Overflows Description Accessing locations of a buffer outside the boundaries of the buffer Common causes C-style strings Array access and pointer arithmetic in languages without bounds checking Off by one errors Fixed large buffer sizes (make it big and hope) Decoupled buffer pointer and its size If size unknown overflows are impossible to detect Require synchronization between the two Ok if size is implicitly known and every use knows it (hard)

30 Why Buffer Overflows are Dangerous
Vulnerability Assessment and Secure Coding Practices Why Buffer Overflows are Dangerous An overflow overwrites memory adjacent to a buffer This memory could be Unused Code Program data that can affect operations Internal data used by the runtime system Common result is a crash Specially crafted values can be used for an attack

31 Buffer Overflow of User Data Affecting Flow of Control
Vulnerability Assessment and Secure Coding Practices Buffer Overflow of User Data Affecting Flow of Control char id[8]; int validId = 0; /* not valid */ gets(id); /* reads "evillogin"*/ /* validId is now 110 decimal */ if (IsValid(id)) /* <- false */ validId = 1; /* not executed */ if (validId) /* <- true */ DoPrivilegedOp(); /* is executed */ id validId \0 id validId e v i l o g 110 ‘n’ \0

32 Vulnerability Assessment and Secure Coding Practices
Numeric Errors Pointers, strings are well known. Ints are easy, boring … but …there are opportunities there with ints!

33 Vulnerability Assessment and Secure Coding Practices
The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX. In both cases, errno is set to ERANGE. Precisely the same holds for strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX).

34 Integer Vulnerabilities
Vulnerability Assessment and Secure Coding Practices Integer Vulnerabilities Description In many programming languages (C, C++, Java, Perl, Python 2.x have problems; Python 3.x is OK), integers are module 2n, allow silent unexpected results Overflow Truncation Signed vs. unsigned representations Code may be secure on one platform, but silently vulnerable on another, due to different underlying integer types. General causes Not checking for overflow Mixing integer types of different ranges Mixing unsigned and signed integers

35 The Cost of Not Checking…
4 Jun 1996: An unchecked 64 bit floating point number assigned to a 16 bit integer Ariane 5 mission 501 Cost: Development cost: $7 billion Lost rocket and payload $500 million

36 Vulnerability Assessment and Secure Coding Practices
Race Conditions

37 Vulnerability Assessment and Secure Coding Practices
Race Conditions Description A race condition occurs when multiple threads of control try to perform a non-atomic operation on a shared object, such as Multithreaded applications accessing shared data Accessing external shared resources such as the file system General causes Threads or signal handlers without proper synchronization Non-reentrant functions (may have shared variables) Performing non-atomic sequences of operations on shared resources (file system, shared memory) and assuming they are atomic

38 Vulnerability Assessment and Secure Coding Practices
Race Condition on Data A program contains a data race if two threads simultaneously access the same variable, where at least one of these accesses is a write. Programs need to be race free to be safe. Subdirectory allows you to control which files get put there and prevents replacing them with symlinks. mkstemp - create a unique temporary file

39 Successful Race Condition Attack
Vulnerability Assessment and Secure Coding Practices Successful Race Condition Attack void TransFunds(Account srcAcct, Account dstAcct, int xfrAmt) { if (xfrAmt < 0) FatalError(); int srcAmt = srcAcct.getBal(); if (srcAmt - xfrAmt < 0) srcAcct.setBal(srcAmt - xfrAmt); dstAcct.setBal(dstAcct.getBal() + xfrAmt); } Balances Thread 1 Thread 2 Bob Ian XfrFunds(Bob, Ian, 100) 100 srcAmt = 100 srcAmt – 100 < 0 ? srcAcct.setBal(100 – 100) dst.setBal( ) 200 time 39

40 Mitigated Race Condition Attack
Vulnerability Assessment and Secure Coding Practices Mitigated Race Condition Attack public void TransFunds(Account srcAcct, Account dstAcct, int xfrAmt) { if (xfrAmt < 0) FatalError(); synchronized(srcAcct) { int srcAmt = srcAcct.getBal(); if (srcAmt - xfrAmt < 0) FatalError(); srcAcct.setBal(srcAmt - xfrAmt); } synchronized(dstAcct) { dstAcct.setBal(dstAcct.getBal() + xfrAmt); Thread 1 Thread 2 Bob Ian XfrFunds(Bob, Ian, 100) 100 In use srcAcct? No, proceed. In use srcAcct? Yes, wait. srcAmt = 100 srcAmt – 100 < 0 ? srcAcct.setBal(100 – 100) In use dstAcct? No, proceed. dst.setBal( ) srcAmt = 0 srcAmt – 100 < 0? Yes, fail time 40

41 File System Race Conditions
Vulnerability Assessment and Secure Coding Practices File System Race Conditions A file system maps a path name of a file or other object in the file system, to the internal identifier (device and inode) If an attacker can control any component of the path, multiple uses of a path can result in different file system objects Safe use of path eliminate race condition use only once use file descriptor for all other uses verify multiple uses are consistent

42 File System Race Examples
Vulnerability Assessment and Secure Coding Practices File System Race Examples Check properties of a file then open Bad: access or stat  open Safe: open  fstat Create file if it doesn’t exist Bad: if stat fails  creat(fn, mode) Safe: open(fn, O_CREAT|O_EXCL, mode) Never use O_CREAT without O_EXCL Better still use safefile library James A. Kupsch and Barton P. Miller, “How to Open a File and Not Get Hacked,” 2008 Third International Conference on Availability, Reliability and Security (ARES), Barcelona, Spain, March 2008. Stat: return info on a file. Fstat: same as stat but instead of a file name needs a file descriptor. O_EXCL: create the file only if it doesn't already exist. Race condition in SRB. Papers solving that were wrong. OSG uses our safefile library. O_CREAT w/o O_EXCL: don’t know if file already existed, if filename is symlink that doesn’t point to existing file, w/O_EXCL will fail w/o O_EXCL will create file in place pointed to by symlink

43 Race Condition Examples
Vulnerability Assessment and Secure Coding Practices Race Condition Examples Your Actions Attackers Action s=strdup("/tmp/zXXXXXX") tempnam(s) // s now "/tmp/zRANDOM" link = "/etc/passwd" file = "/tmp/zRANDOM" symlink(link, file) f = fopen(s, "w+") // writes now update // /etc/passwd time Safe Version fd = mkstemp(s) f = fdopen(fd, "w+") tempnam creates temporary file string. mkstemp makes a temp file name, creates the file and returns a fd, , uses O_EXCL tempnam - create a name for a temporary file int symlink(const char *oldpath, const char *newpath);

44 Vulnerability Assessment and Secure Coding Practices
Exceptions

45 Exception Vulnerabilities
Vulnerability Assessment and Secure Coding Practices Exception Vulnerabilities Exception are a nonlocal control flow mechanism, usually used to propagate error conditions in languages such as Java and C++. try { // code that generates exception } catch (Exception e) { // perform cleanup and error recovery } Common Vulnerabilities include: Ignoring (program terminates) Suppression (catch, but do not handled) Information leaks (sensitive information in error messages) Ignoring: can cause a crash. Crashes can cause big damage. Suppression: let the error happen and not do anything. In this example we only catch a possible exception from the URL class, we should also catch the one of the class of the file (by using IOException). We could use Exception as we catch either MalformedURLException or IOException since both of them are subclasses of Exception but that would make it difficult to diagnose a possible error so the best solution is to catch both in two different catches.

46 Proper Use of Exceptions
Vulnerability Assessment and Secure Coding Practices Proper Use of Exceptions Add proper exception handling Handle expected exceptions (i.e. check for errors) Don’t suppress: Do not catch just to make them go away Recover from the error or rethrow exception Include top level exception handler to avoid exiting: catch, log, and restart Do not disclose sensitive information in messages Only report non-sensitive data Log sensitive data to secure store, return id of data Don't report unnecessary sensitive internal state Stack traces Variable values Configuration data

47 Exception Suppression
Vulnerability Assessment and Secure Coding Practices Exception Suppression 1. User sends malicious data user="admin",pwd=null boolean Login(String user, String pwd){ boolean loggedIn = true; String realPwd = GetPwdFromDb(user); try { if (!GetMd5(pwd).equals(realPwd)) { loggedIn = false; } } catch (Exception e) { //this can not happen, ignore return loggedIn; In this example the programmer does not expect a NullPointerException to occur and simply swallows the Exception. This has the nasty side effect of granting admin access because the logedin variable has a default value of true 2. System grants access Login() returns true 47

48 Unusual or Exceptional Conditions Mitigation
Vulnerability Assessment and Secure Coding Practices Unusual or Exceptional Conditions Mitigation 1. User sends malicious data user=“admin”,pwd=null boolean Login(String user, String pwd){ boolean loggedIn = true; String realPwd = GetPwdFromDb(user); try { if (!GetMd5(pwd).equals(realPwd)) { loggedIn = false; } } catch (Exception e) { return loggedIn; We catch any possible exception with Exception so that if anything goes wrong we do not grant access to the system 2. System does not grant access Login() returns false 48

49 WTMI (Way Too Much Info)
Vulnerability Assessment and Secure Coding Practices WTMI (Way Too Much Info) Login(… user, … pwd) { try { ValidatePwd(user, pwd); } catch (Exception e) { print("Login failed.\n"); print(e + "\n"); e.printStackTrace(); return; } void ValidatePwd(… user, … pwd) throws BadUser, BadPwd { realPwd = GetPwdFromDb(user); if (realPwd == null) throw BadUser("user=" + user); if (!pwd.equals(realPwd)) throw BadPwd("user=" + user + " pwd=" + pwd + " expected=" + realPwd); User exists Entered pwd User's actual password ?!? (passwords aren't hashed) Login failed. BadPwd: user=bob pwd=x expected=password BadPwd: at Auth.ValidatePwd (Auth.java:92) at Auth.Login (Auth.java:197) com.foo.BadFramework(BadFramework.java:71) ... Note: The web application is storing the password in clear text. When a web application reveals this kind of information, it tends to be a LOT. Reveals internal structure (libraries used, call structure, version information) 49

50 The Right Amount of Information
Vulnerability Assessment and Secure Coding Practices The Right Amount of Information Login { try { ValidatePwd(user, pwd); } catch (Exception e) { logId = LogError(e); // write exception and return log ID. print("Login failed, username or password is invalid.\n"); print("Contact support referencing problem id " + logId + " if the problem persists"); return; } void ValidatePwd(… user, … pwd) throws BadUser, BadPwd { realPwdHash = GetPwdHashFromDb(user) if (realPwdHash == null) throw BadUser("user=" + HashUser(user)); if (!HashPwd(user, pwd).equals(realPwdHash)) throw BadPwdExcept("user=" + HashUser(user)); Log sensitive information Generic error message (id links sensitive information) User and password are hashed (minimizes damage if breached) 50

51 Privilege, Sandboxing, and Environment
Vulnerability Assessment and Secure Coding Practices Privilege, Sandboxing, and Environment Switch

52 Vulnerability Assessment and Secure Coding Practices
Trusted Directory Vulnerability Assessment and Secure Coding Practices A trusted directory is one where only trusted users can update the contents of anything in the directory or any of its ancestors all the way to the root A trusted path needs to check all components of the path including symbolic links referents for trust A trusted path is immune to TOCTOU attacks from untrusted users This is extremely tricky to get right! safefile library Determines trust based on trusted users & groups

53 Vulnerability Assessment and Secure Coding Practices
Directory Traversal Description When user data is used to create a pathname to a file system object that is supposed to be restricted to a particular set of paths or path prefixes, but which the user can circumvent General causes Not checking for path components that are empty, "." or ".." Not creating the canonical form of the pathname (there is an infinite number of distinct strings for the same object) Not accounting for symbolic links

54 Directory Traversal Mitigation
Vulnerability Assessment and Secure Coding Practices Directory Traversal Mitigation Use realpath or something similar to create canonical pathnames Use the canonical pathname when comparing filenames or prefixes If using prefix matching to check if a path is within directory tree, also check that the next character in the path is the directory separator or '\0'

55 Directory Traversal (Path Injection)
Vulnerability Assessment and Secure Coding Practices Directory Traversal (Path Injection) User supplied data is used to create a path, and program security requires but does not verify that the path is in a particular subtree of the directory structure, allowing unintended access to files and directories that can compromise the security of the system. Usually <program-defined-path-prefix> + "/" + <user-data> Mitigations Validate final path is in required directory using canonical paths (realpath) Do not allow above patterns to appear in user supplied part (if symbolic links exists in the safe directory tree, they can be used to escape) Use chroot or other OS mechanisms <user-data> Directory Movement ../ up ./ or empty string none <dir>/ down

56 Vulnerability Assessment and Secure Coding Practices
Command Line Description Convention is that argv[0] is the path to the executable Shells enforce this behavior, but it can be set to anything if you control the parent process General causes Using argv[0] as a path to find other files such as configuration data Process needs to be setuid or setgid to be a useful attack

57 Vulnerability Assessment and Secure Coding Practices
Environment List of (name, value) string pairs Available to program to read Used by programs, libraries and runtime environment to affect program behavior Mitigations: Clean environment to just safe names & values Don’t assume the length of strings No user control of PATH, LD_LIBRARY_PATH, and other variables that are directory lists used to look for execs and libs

58 Vulnerability Assessment and Secure Coding Practices
Injection Attacks

59 Vulnerability Assessment and Secure Coding Practices
Injection Attacks Description A string constructed with user input, that is then interpreted by another function, where the string is not parsed as expected Command injection (in a shell) Format string attacks (in printf/scanf) SQL injection Cross-site scripting or XSS (in HTML) General causes Allowing metacharacters Not properly neutralizing user data if metacharacters are allowed

60 Vulnerability Assessment and Secure Coding Practices
SQL Injections User supplied values used in SQL command must be validated, quoted, or prepared statements must be used Signs of vulnerability Uses a database mgmt system (DBMS) Creates SQL statements at run-time Inserts user supplied data directly into statement without validation

61 SQL Injections: attacks and mitigations
Vulnerability Assessment and Secure Coding Practices SQL Injections: attacks and mitigations Dynamically generated SQL without validation or quoting is vulnerable $u = " '; drop table t --"; $sth = $dbh->do("select * from t where u = '$u'"); Database sees two statements: select * from t where u = ' '; drop table t --' Use prepared statements to mitigate $sth = $dbh->do("select * from t where u = ?", $u); SQL statement template and value sent to database No mismatch between intention and use $ is var in perl $dbh is database handle var. “do” executes command on db. Returns “statement handle” that you can iterate over to get each row. Single quote part of SQL.

62 Vulnerability Assessment and Secure Coding Practices

63 Vulnerability Assessment and Secure Coding Practices
Command Injections User supplied data used to create a string that is the interpreted by command shell such as /bin/sh Signs of vulnerability Use of popen, or system exec of a shell such as sh, or csh Argument injections, allowing arguments to begin with "-" can be dangerous Usually done to start another program That has no C API Out of laziness popen forks off a shell, connect via a pipe and returns a FILE * to that is connected to standard input and output of the new process.

64 Command Injection Mitigations
Vulnerability Assessment and Secure Coding Practices Command Injection Mitigations Check user input for metacharacters Neutralize those that can’t be eliminated or rejected replace single quotes with the four characters, '\'', and enclose each argument in single quotes Use fork, drop privileges and exec for more control Avoid if at all possible Use C API if possible

65 Perl Command Injection Examples
Vulnerability Assessment and Secure Coding Practices Perl Command Injection Examples open(CMD, "|/bin/mail -s $sub $to"); Unsafe if $to is rm -rf /" open(CMD, “|/bin/mail -s '$sub' '$to'"); Unsafe if $to is rm -rf /'" ($qSub = $sub) =~ s/'/'\\''/g; ($qTo = $to) =~ s/'/'\\''/g; open(CMD, "|/bin/mail -s '$qSub' '$qTo'"); Safe from command injection open(cmd, "|-", "/bin/mail", "-s", $sub, $to); Safe and simpler: use this whenever possible.

66 Vulnerability Assessment and Secure Coding Practices
Eval Injections A string formed from user supplied input that is used as an argument that is interpreted by the language running the code Usually allowed in scripting languages such as Perl, sh and SQL In Perl eval($s) and s/$pat/$replace/ee $s and $replace are evaluated as perl code s/X/Y/ee e = execute $replace and use result as replacement string. ee = take result from “e” and execute it, getting new result as replacement string. (ad nauseum)

67 Python Command Injection Danger Signs
Vulnerability Assessment and Secure Coding Practices Python Command Injection Danger Signs Python Functions prone to injection attacks: exec() # dynamic execution of Python code eval() # returns the value of an expression or # code object os.system() # execute a command in a subshell os.popen() # open a pipe to/from a command execfile() # reads & executes Python script from # a file. input() # equivalent to eval(raw_input()) compile() # compile the source string into a code # object that can be executed Os.system: Executes a command/string in a subshell Eval: evaluates the source in the context of globals and locals. The source may be a string with a Python expression or a code object as retturned by compile(). Sensitive sinks: Python interpreter, browser, OS interpreter, SQL interpreter.

68 Successful OS Injection Attack
Vulnerability Assessment and Secure Coding Practices Successful OS Injection Attack 1. User sends malicious data hostname="x.com;rm –rf /*" 2. Application uses nslookup to get DNS records String rDomainName(String hostname) { String cmd = "/usr/bin/nslookup " + hostname; Process p = Runtime.getRuntime().exec(cmd); Runtime: class to access system functions. getRuntime: method to get object to call system functions 3. System executes nslookup x.com;rm –rf /* 4. All files possible are deleted 68

69 Mitigated OS Injection Attack
Vulnerability Assessment and Secure Coding Practices Mitigated OS Injection Attack 1. User sends malicious data hostname="x.com;rm –rf /*" 2. Application uses nslookup only if input validates String rDomainName(String hostname) { if (hostname.matches("[A-Za-z][A-Za-z0-9.-]*")) { String cmd = "/usr/bin/nslookup " + hostname); Process p = Runtime.getRuntime().exec(cmd); } else { System.out.println(“Invalid host name”); No matter what password the admin user has. If the user exists, the query will always return true and the attacker will log in. 3. System returns error "Invalid host name" 69

70 Vulnerability Assessment and Secure Coding Practices
Code Injection Cause Program generates source code from template User supplied data is injected in template Failure to neutralized user supplied data Proper quoting or escaping Only allowing expected data Source code compiled and executed Very dangerous – high consequences for getting it wrong: arbitrary code execution

71 Code Injection Vulnerability
Vulnerability Assessment and Secure Coding Practices Python 1. logfile – name's value is user controlled Perl name = John Smith name = ');import os;os.system('evilprog');# Read logfile 2. Perl log processing code – uses Python to do real work %data = ReadLogFile('logfile'); PH = open("|/usr/bin/python"); print PH "import LogIt\n";w while (($k, $v) = (each %data)) { if ($k eq 'name') { print PH "LogIt.Name('$v')"; } Start Python, program sent on stdin # = Python comment 1 Entry (name) goes into a log. 2 Perl log processor puts names into a hash (key/value pairs) 3. Forks a Python interpreter. 3 Then uses names to build Python commands 3. Python source executed – 2nd LogIt executes arbitrary code import LogIt; LogIt.Name('John Smith') LogIt.Name('');import os;os.system('evilprog');#')

72 Code Injection Mitigated
Vulnerability Assessment and Secure Coding Practices Python 1. logfile – name's value is user controlled Perl name = John Smith name = ');import os;os.system('evilprog');# 2. Perl log processing code – use QuotePyString to safely create string literal %data = ReadLogFile('logfile'); PH = open("|/usr/bin/python"); print PH "import LogIt\n";w while (($k, $v) = (each %data)) { if ($k eq 'name') { $q = QuotePyString($v); print PH "LogIt.Name($q)"; } sub QuotePyString { my $s = shift; $s =~ s/\\/\\\\/g; # \  \\ $s =~ s/'/\\'/g; # '  \' $s =~ s/\n/\\n/g; # NL  \n return "'$s'"; # add quotes } Only single-quote escape needed in this example. Programmers often ignore the others (to their detriment) 3. Python source executed – 2nd LogIt is now safe import LogIt; LogIt.Name('John Smith') LogIt.Name('\');import os;os.system(\'evilprog\');#')

73 Vulnerability Assessment and Secure Coding Practices
Web Attacks

74 Cross Site Scripting (XSS)
Vulnerability Assessment and Secure Coding Practices Cross Site Scripting (XSS) Injection into an HTML page HTML tags JavaScript code Reflected (from URL) or persistent (stored from prior attacker visit) Web application fails to neutralize special characters in user supplied data Mitigate by preventing or encoding/escaping special characters Special characters and encoding depends on context HTML text HTML tag attribute HTML URL

75 Reflected Cross Site Scripting (XSS)
Vulnerability Assessment and Secure Coding Practices Reflected Cross Site Scripting (XSS) 3. Generated HTML displayed by browser <html> ••• You searched for: widget </html> 1. Browser sends request to web server 2. Web server code handles request ••• String query = request.getParameter("q"); if (query != null) { out.writeln("You searched for:\n" + query); }

76 Reflected Cross Site Scripting (XSS)
Vulnerability Assessment and Secure Coding Practices Reflected Cross Site Scripting (XSS) 3. Generated HTML displayed by browser <html> ••• You searched for: <script>alert('Boo!')</script> </html> 1. Browser sends request to web server 2. Web server code handles request This example show a method (code that get executed on the web server). It takes one parameter “q”. In this example, some JavaScript passed as the argument “q” is injected into the resulting HTML. This is why this is called “reflected.” The JavaScript in this example will just pop up a window with the message “Boo!” displayed. A persistent XSS would be where one session with the web server would store a value in a database, and a second session would make a request which uses the data stored in the database with neutralizing the special characters. An example would be a poorly written message board where a malicious user could post a comment containing bad data, which would then attack any user that viewed the comment. Longer examples of JavaScript could be used to redirect the web browser to an entirely different site, which is often used in phishing attacks (malicious sites mimicking a valid site such as a bank). An example of this would be <script>window.location=“ JavaScript could also be used to manipulate other aspects of the page, or to return sensitive bits of information on the page or stored in cookies to an attacker. Without using JavaScript this attack could replace the remainder of the HTML page returned by closing and opening HTML tags as required and commenting out the remainder of the page. This would allowing an attacker to replace parts of the page that a user might trust, such as sidebar links or footer links. If the web browser or its plug-ins contain exploitable vulnerabilities (which is a frequent occurrence), this attack could also be used to gain access to the user’s operating system. This is an example of a trust boundary problem, in that the web browser expects “q” parameter sent by the user to not contain character interpreted specially by HTML, and the web browser does not verify this fact. The users browser also trusts the HTML returned by the web browser not to contain malicious code or text, but it is impossible for the web browser to verify this, so the mitigation must occur in the web server code. ••• String query = request.getParameter("q"); if (query != null) { out.writeln("You searched for:\n" + query); }

77 Vulnerability Assessment and Secure Coding Practices
XSS Mitigation 3. Generated HTML displayed by browser <html> ••• Invalid query </html> 1. Browser sends request to web server 2. Web server code correctly handles request ••• String query = request.getParameter("q"); if (query != null) { if (query.matches("^\\w*$")) { out.writeln("You searched for:\n" + query); } else { out.writeln("Invalid query"); } The query.matches is a regular expression match. It matches a string that consists of only \w characters (alphanumeric characters and underscore) The parameter given does not match, so the error page is returned.

78 Cross Site Request Forgery (CSRF)
Vulnerability Assessment and Secure Coding Practices Cross Site Request Forgery (CSRF) CSRF is when loading a web pages causes a malicious request to another server Requests made using URLs or forms (also transmits any cookies for the site, such as session or auth cookies) HTTP GET method <form action=/xfer method=POST> HTTP POST method <input type=text name=amt> <input type=text name=toAcct> </form> Web application fails to distinguish between a user initiated request and an attack Mitigate by using a large random nonce In this example the bank.com web server has a method found at the path /xfer that takes two parameters “amt” and “toAcct”. It is assumed the user had previously logged in and has session information that is stored a cookie to authenticate the request. Cookies are automatically sent with all requests to a particular server. Web server request object abstracts away the differences between GET and POST. Developer often doesn’t care which method was used.

79 Cross Site Request Forgery (CSRF)
Vulnerability Assessment and Secure Coding Practices Cross Site Request Forgery (CSRF) User loads bad page from web server XSS – Fake server Bad guy’s server – Compromised server Web browser makes a request to the victim web server directed by bad page Tags such as <img src=‘ JavaScript Victim web server processes request and assumes request from browser is valid Session IDs in cookies are automatically sent along SSL does not help – channel security is not an issue here This example would transfer $1000 from the users account to the account ‘evil37’. The same type thing could be done using JavaScript, although JavaScript can also perform POST requests instead of just GET requests with a URL

80 Successful CSRF Attack
Vulnerability Assessment and Secure Coding Practices Successful CSRF Attack 1. User visits evil.com 2. evil.com returns HTML <html> ••• <img src=‘ </html> 3. Browser sends attack 4. bank.com server code handles request ••• String id = response.getCookie(“user”); userAcct = GetAcct(id); If (userAcct != null) { deposits.xfer(userAcct, toAcct, amount); }

81 Vulnerability Assessment and Secure Coding Practices
CSRF Mitigation Very unlikely attacker will provide correct nonce 1. User visits evil.com 2. evil.com returns HTML 3. Browser sends attack 4. bank.com server code correctly handles request ••• String nonce = (String)session.getAttribute(“nonce”); String id = response.getCookie(“user”); if (Utils.isEmpty(nonce) || !nonce.equals(getParameter(“nonce”) { Login(); // no nonce or bad nonce, force login return; // do NOT perform request } // nonce added to all URLs and forms userAcct = GetAcct(id); if (userAcct != null) { deposits.xfer(userAcct, toAcct, amount); } This mitigation works by using a nonce. The attacker easily knows the method name, parameters and their values. The authentication information is stored in cookies, but the attacker doesn’t know the nonce and without it the server will redirect the user to a login page as the request is coming from a source that is not properly logged in. During the login process the nonce is stored in the persistent (with timeout) structure on the web server. When a request is made the code checks for a nonce and that it match the previously stored value. If this is then the request is executed. The server must add the nonce value to every form and URL that needs authentication, and it must not be stored in a cookie as cookies are automatically sent along with requests. It is important that the nonce has a low probability of an attacker guessing or discovering (i.e. it should be large and random, have a short lifetime, and not be reused).

82 Vulnerability Assessment and Secure Coding Practices
Session Hijacking Session IDs identify a user’s session in web applications. Obtaining the session ID allows impersonation Attack vectors: Intercept the traffic that contains the ID value Guess a valid ID value (weak randomness) Discover other logic flaws in the sessions handling process To understand how the application handles sessions and find its weakness an attacker will create a valid one.

83 Good Session ID Properties
Vulnerability Assessment and Secure Coding Practices Good Session ID Properties Hard to guess Large entropy (big random number) No patterns in IDs issued No reuse

84 Session Hijacking Mitigation
Vulnerability Assessment and Secure Coding Practices Session Hijacking Mitigation Create new session id after Authentication switching encryption on other attributes indicate a host change (IP address change) Encrypt to prevent obtaining session ID through eavesdropping Expire IDs after short inactivity to limit exposure of guessing or reuse of illicitly obtained IDs Entropy should be large to prevent guessing Invalidate session IDs on logout and provide logout functionality

85 Session Hijacking Example
Vulnerability Assessment and Secure Coding Practices Session Hijacking Example An insecure web application accepts and reuses a session ID supplied to a login page. Attacker tricked user visits the web site using attacker chosen session ID User logs in to the application Application creates a session using attacker supplied session ID to identify the user The attacker uses session ID to impersonate the user If the server accepts arbitrary IDs generated by the user we just need to trick the user to visit a url to the target site with a random ID value, otherwise we firstly have to do a valid request to the target site and use the session ID that the server will assign us. Depending on how the targeted system works we will need to trick the user to login with the malicious URL that the attacker provides, or we will just need to ensure that the user visits the site if the system stores the session ID in a cookie. If the targeted site had a XSS vulnerability, we could take advantage of this to trick the user browser to store a persistent cookie with our ID.

86 Successful Hijacking Attack
Vulnerability Assessment and Secure Coding Practices Successful Hijacking Attack 1. Tricks user to visit 2. User Logs In 4. Impersonates the user Cookie: JSESSIONID=123 The problem in that the server code is that it checks if the user has a session id, and if he does not it creates a new one (before authenticating him). 3. Creates the session if(HttpServletRequest.getRequestedSessionId() == null) { HttpServletRequest.getSession(true); } ... HTTP/ OK Set-Cookie: JSESSIONID=123

87 Mitigated Hijacking Attack
Vulnerability Assessment and Secure Coding Practices Mitigated Hijacking Attack 1. Tricks user to visit 2. User Logs In 4. Impersonates the user Cookie: JSESSIONID=123 In each request we will create a new session vale, which will be transmitted in a secure channel (ssl) in a cookie and will expire in a reasonable period of time. 3. Creates the session HTTP/ OK Set-Cookie: JSESSIONID=XXX HttpServletRequest.invalidate(); HttpServletRequest.getSession(true); ...

88 Secure Coding Practices (and Other Good Things)
Vulnerability Assessment and Secure Coding Practices Secure Coding Practices (and Other Good Things) James A. Kupsch Barton P. Miller Elisa Heymann 88 88


Download ppt "Secure Coding Practices (and Other Good Things)"

Similar presentations


Ads by Google