SlideShare uma empresa Scribd logo
1 de 60
Introduction to Systems Security Ben Livshits 10/16/2010 Some slides are borrowed from CS 155 at Stanford
Organization General introduction to security What is system security? Threats Trends Approaches to finding vulnerabilities Security vulnerabilities Memory-based exploits Web application vulnerabilities
What is Security? System correctness If user supplies expected input, system generates desired output Security If attacker supplies unexpected input, system does not fail in certain ways Goal of the attacker is to make the system fail in “interesting ways”
What is security? System correctness Good input  Good output Think “verification” Security Bad input  Bad output Think “not exploitable”
What is security? System correctness More features: better Security More features: can be worse
Security properties Confidentiality	 Information about system or its users cannot be learned by an attacker Integrity The system continues to operate properly, only reaching states that would occur if there were no attacker Availability Actions by an attacker do not prevent users from having access to use of the system
General picture System Attacker Alice Security is about Honest user (e.g., Alice, Bob, …) Dishonest Attacker How the Attacker  Disrupts honest user’s use of the system  (Integrity, Availability) Learns information intended for Alice only (Confidentiality)
Network security Network Attacker Intercepts and controls network communication System Alice
Web security System Web Attacker Sets up malicious site visited by victim; no control of network Alice
Operating system security OS Attacker Controls malicious files and applications Alice
System Attacker Alice Confidentiality: Attacker does not learn Alice’s secrets Integrity: Attacker does not undetectably corrupt system’s function for Alice Availability: Attacker does not keep system from being useful to Alice
Current Trends
Historical hackers  (prior to 2000) Profile: Male Between 14 and 34 years of age Computer addicted No permanent girlfriend No  Commercial  Interest  !!! Source: Raimund Genes
Typical Botherder: 0x80" (pronounced X-eighty) Washington Post: Invasion of the Computer Snatchers High school dropout “…most of these people I infect are so stupid they really ain't got no business being on the Internet in the first place.“ Working hours: approx. 2 minutes/day to manage Botnet Monthly earnings: $6,800 on average Daily Activities:  Chatting with people while his bots make him money Recently paid $800 for an hour alone in a VIP room with several dancers Job Description:  Controls 13,000+ computers in more than 20 countries  Infected Bot PCs download Adware then search for new victim PCs Adware displays ads and mines data on victim's online browsing habits. Bots collect password, e-mail address, SS#, credit and banking data Gets paid by companies like TopConverting.com, GammaCash.com, Loudcash, or 180Solutions. 14
Some things in the news Nigerian letter (419 Scams) still works: Michigan Treasurer Sends 1.2MUSD of State Funds !!! Many zero-day attacks Google, Excel, Word, Powerpoint, Office … Criminal access to important devices Numerous lost, stolen laptops, storage media, containing customer information Second-hand computers (hard drives) pose risk Vint Cerf estimates ¼ of PCs on Internet are bots 15
Trends for 2010 Malware, worms, and Trojan horses spread by email, instant messaging, malicious or infected websites Botnets and zombies improving their encryption capabilities, more difficult to detect Scareware – fake/rogue security software  Attacks on client-side software browsers, media players, PDF readers, etc.  Ransom attacks malware encrypts hard drives, or DDOS attack Social network attacks  Users’ trust in online friends makes these networks a prime target.  Cloud Computing - growing use will make this a prime target for attack.  Web Applications - developed with inadequate security controls  Budget cuts - problem for security personnel and a boon to cyber criminals.  Texas CISO, Feb 2010 Same list in Oklahoma Monthly Security Tips Newsletter
Trends
Operating system vulnerabilities
Reported Web Vulnerabilities "In the Wild" Data from aggregator and validator of  NVD-reported vulnerabilities
Web vs System vulnerabilities XSS peak
Web attack toolkit: MPack Basic setup Toolkit hosted on web server Infects pages on that server Page visitors get infected Features Customized: determines exploit on the fly, based on user’s OS, browser, etc Easy to use: management console provides stats on infection rates Customer care toolkit can be purchased with one-year support contract! 21
Finding Vulnerabilities  Static analysis Abstract interpretation Dataflow Pointer analysis etc. Runtime analysis  Fuzzing Testing Simulation Symbolic execution Model checking
Necessary BackgroundonMemory Exploits and Web Application Vulnerabilities 23
Outline 24 Memory safety attacks Buffer overruns Format string vulnerabilities Web application vulnerabilities SQL injections Cross-site scripting attacks
Buffer Overflows 25
Buffer Overrun Example 26 Frame 1 Frame 2 str ret sfp local str ret sfp local void lame (void) {  char small[30];  	gets(small);  printf("%s", small);  }
Input Validation Classifying vulnerabilities: Buffer overflows can be viewed as an example of improper input validation Another related type of vulnerability is information leaks Other notable examples: Format string vulnerabilities SQL injection attacks Cross-site scripting attacks Mechanisms to prevent attacks Better input validation Safe programming techniques Techniques for detecting potential buffer overflows in code Static analysis Runtime analysis Fuzzing/penetration testing Write-box fuzzing etc. 27
Secure Programming Techniques Validate all input Easier said than done Why is that? Avoid buffer overflows Use safe string manipulation functions  Careful length checking Avoid statically declared arrays etc. Or use a memory-safe language Java or C# JavaScript (not type-safe) 28
Validating Input Determine acceptable input, check for match --- don’t just check against list of “non-matches” Limit maximum length Watch out for special characters, escape chars. Check bounds on integer values Check for negative inputs Check for large inputs that might cause overflow! 29
Avoid strcpy, … We have seen that strcpy is unsafe strcpy(buf, str) simply copies memory contents into buf starting from *str until “” is encountered, ignoring the size of buf Avoid strcpy(), strcat(), gets(), etc. Use strncpy(), strncat(), instead Still, computing proper bounds is difficult in practice Easy to mess up, off-by-one errors are common 30
Static and Dynamic Analysis Static analysis: run on the source code prior to deployment; check for known flaws e.g., flawfinder, cqual Or Prefix/Prefast Or Coverityor Fortify tools Will look at some more recent work in this course as well as older stuff Dynamic analysis: try to catch (potential) buffer overflows during program execution Soundness Precision Comparison? Static analysis very useful, but not perfect False positives False negatives Dynamic analysis can be better (in tandem with static analysis), but can slow down execution Historically of great importance, drove adoption of type-safe languages such as Java and C# 31
Dynamic analysis: Libsafe Very simple example of what can be done at runtime Intercepts all calls to, e.g., strcpy(dest, src) Validates sufficient space in current stack frame:	|frame-pointer – dest| > strlen(src) If so, executes strcpy; otherwise, terminates application 32
Preventing Buffer Overflows Operating system support: Can mark stack segment as non-executable Randomize stack location Problems: Does not defend against `return-to-libc’ exploit Overflow sets ret-addr to address of libc function Does not prevent general buffer overflow flaws, or heap overflow Basic heap overflows can be helped with ALSR 33
Heap-based Buffer Overruns and Heap Spraying 34 Buffer overruns consist of two steps Introduce the payload Cause the program to jump to it Can put the payload/shellcode in the heap Arbitrary amounts of code Doesn’t work with heap randomization Location of the payload changes every time Heap spraying: Allocate multiple copies of the payload When the jump happens, it hits the payload with a high probability
StackGuard Embed random “canaries” in stack frames and verify their integrity prior to function return This is actually used! Helpful, but not foolproof… Frame 1 Frame 2 str ret sfp local canary str ret sfp local canary 35
More Methods …  Address obfuscation Encrypt return address on stack by XORing with random string.  Decrypt just before returning from function Attacker needs decryption key to set return address to desired value 36
More Input Validation Flaws 37
Format String Vulnerabilities What is the difference between printf(buf);andprintf(“%s”, buf);? What if buf holds %x ? Look at memory, and what printf expects… 38
Format String Exploits Technique: Declare a variable of type int in line 4 and call it bytes_formatted Line 6 the format string specifies that 20 characters should be formatted in hexadecimal (“%.20x”) using buffer When this is done, due to the “%n” specifier write the value 20 to bytes_formatted Result: This means that we have written a value to another memory location Very definition of violating memory safety May be possible to gain control over a program’s execution #include <stdio.h> int main() { intbytes_formatted=0;     char buffer[28]=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”;  printf(“%.20x%n”,buffer,&bytes_formatted); printf(      “The number of bytes formatted in the previous printf statement  	was %d”,bytes_formatted);    return 0; }  39
Other Input Validation Bugs Integer overflow… Consider the code:strncpy(msg+offset, str, slen); 	where the adversary may control offset By setting the value high enough, it will wrap around and be treated as a negative integer! Write into the msg buffer instead of after it 40
Web Application Vulnerabilities 41
SQL Injection Attacks Affect applications that use untrusted input as part of an SQL query to a back-end database Specific case of a more general problem: using untrusted input in commands 42
SQL Injection: Example Consider a browser form, e.g.: When the user enters a number and clicks the button, this generates an http request like       https://www.pizza.com/show_orders?month=10 43
Example Continued… Upon receiving the request, a Java program might produce an SQL query as follows: A normal query would look like: sql_query       = "SELECT pizza, quantity, order_day "           + "FROM orders "            + "WHERE userid=" + session.getCurrentUserId()           + " AND order_month= "           + request.getParameter("month"); SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10 44
Example Continued… What if the user makes a modified http request:https://www.pizza.com/show_orders?month=0%20OR%201%3D1 (Parameters transferred in URL-encoded form, where meta-characters are encoded in ASCII) This has the effect of settingrequest.getParameter(“month”)equal to the string0 OR 1=1 45
Example Continued So the script generates the following SQL query: Since AND takes precedence over OR, the above always evaluates to TRUE The attacker gets every entry in the database! SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 OR 1=1 ( ) 46
Even Worse… Craft an http request that generates an SQL query like the following: Attacker gets the entire credit card database as well! SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 OR 1=0UNION SELECT cardholder, number, exp_dateFROM creditcards 47
More Damage… SQL queries can encode multiple commands, separated by ‘;’ Craft an http request that generates an SQL query like the following: Credit card table deleted! DoS attack SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 ;DROP TABLE creditcards 48
More Damage… Craft an http request that generates an SQL query like the following: User (with chosen password) entered as an administrator! Database owned! SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 ;INSERT INTO admin VALUES (‘hacker’, ...) 49
May Need to be More Clever… Consider the following script for text queries: Previous attacks will not work directly, since the commands will be quoted But easy to deal with this… sql_query       = "SELECT pizza, quantity, order_day "           + "FROM orders "            + "WHERE userid=" + session.getCurrentUserId()           + " AND topping= ‘ "           + request.getParameter(“topping") + “’” 50
Example Continued… Craft an http request where          request.getParameter(“topping”)is set toabc’; DROP TABLE creditcards; -- The effect is to generate the SQL query: (‘--’ represents an SQL comment) SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND toppings=‘abc’;DROP TABLE creditcards ; --’ 51
Source: http://xkcd.com/327/ 52
Solutions? Blacklisting Whitelisting Encoding routines Prepared statements/bind variables Mitigate the impact of SQL injection 53
Blacklisting? I.e., searching for/preventing ‘bad’ inputs E.g., for previous example: …where kill_chars() deletes, e.g., quotes and semicolons sql_query       = "SELECT pizza, quantity, order_day "           + "FROM orders "            + "WHERE userid=" + session.getCurrentUserId()           + " AND topping= ‘ "           + kill_chars(request.getParameter(“topping"))          + “’” 54
Drawbacks of Blacklisting How do you know if/when you’ve eliminated all possible ‘bad’ strings? If you miss one, could allow successful attack Does not prevent first set of attacks (numeric values) Although similar approach could be used, starts to get complex! May conflict with functionality of the database E.g., user with name O’Brien 55
Whitelisting Check that user-provided input is in some set of values known to be safe E.g., check that month is an integer in the right range If invalid input detected, better to reject it than to try to fix it Fixes may introduce vulnerabilities Principle of fail-safe defaults 56
Prepared Statements/bind Variables Prepared statements: static queries with bind variables Variables not involved in query parsing Bind variables: placeholders guaranteed to be data in correct format 57
A SQL Injection Example in Java PreparedStatementps = db.prepareStatement(                "SELECT pizza, quantity, order_day "                 + "FROM orders WHERE userid=?                 AND order_month=?"); ps.setInt(1, session.getCurrentUserId()); ps.setInt(2, Integer.parseInt(request.getParameter("month"))); ResultSet res = ps.executeQuery(); Bind variables 58
There’s Even More 59 Practical SQL Injection: Bit by Bit Overall, SQL injection is easy to fix by banning certain APIs Prevent queryExecute-type calls with non-constant arguments Very easy to automate See a tool like LAPSE that does it for Java
Cross-site Scripting 60 If the application is not careful to encode its output data, an attacker can inject script into the output out.writeln(“<div>”); out.writeln(req.getParameter(“name”)); out.writeln(“</div>”); name:  <script>…; xhr.send(document.cookie);</script> Simplest version called reflected or type-1 XSS

Mais conteúdo relacionado

Mais procurados

CoinMiners are Evasive - BsidesTLV
CoinMiners are Evasive - BsidesTLVCoinMiners are Evasive - BsidesTLV
CoinMiners are Evasive - BsidesTLVThomas Roccia
 
Exploitation techniques and fuzzing
Exploitation techniques and fuzzingExploitation techniques and fuzzing
Exploitation techniques and fuzzingG Prachi
 
Reconnaissance not always about resources
Reconnaissance not always about resourcesReconnaissance not always about resources
Reconnaissance not always about resourcesidsecconf
 
Software Security (Vulnerabilities) And Physical Security
Software Security (Vulnerabilities) And Physical SecuritySoftware Security (Vulnerabilities) And Physical Security
Software Security (Vulnerabilities) And Physical SecurityNicholas Davis
 
Cyber threat-hunting---part-2-25062021-095909pm
Cyber threat-hunting---part-2-25062021-095909pmCyber threat-hunting---part-2-25062021-095909pm
Cyber threat-hunting---part-2-25062021-095909pmMuhammadJalalShah1
 
Buffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the StackBuffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the StackironSource
 
Ceh v8 labs module 02 footprinting and reconnaissance
Ceh v8 labs module 02 footprinting and reconnaissanceCeh v8 labs module 02 footprinting and reconnaissance
Ceh v8 labs module 02 footprinting and reconnaissanceAsep Sopyan
 
Malware Detection - A Machine Learning Perspective
Malware Detection - A Machine Learning PerspectiveMalware Detection - A Machine Learning Perspective
Malware Detection - A Machine Learning PerspectiveChong-Kuan Chen
 
Understanding the fundamentals of attacks
Understanding the fundamentals of attacksUnderstanding the fundamentals of attacks
Understanding the fundamentals of attacksCyber Security Alliance
 
Malware Classification and Analysis
Malware Classification and AnalysisMalware Classification and Analysis
Malware Classification and AnalysisPrashant Chopra
 
HackInBo2k16 - Threat Intelligence and Malware Analysis
HackInBo2k16 - Threat Intelligence and Malware AnalysisHackInBo2k16 - Threat Intelligence and Malware Analysis
HackInBo2k16 - Threat Intelligence and Malware AnalysisAntonio Parata
 
Accurately detecting source code of attacks that increase privilege
Accurately detecting source code of attacks that increase privilegeAccurately detecting source code of attacks that increase privilege
Accurately detecting source code of attacks that increase privilegeUltraUploader
 
BSides IR in Heterogeneous Environment
BSides IR in Heterogeneous EnvironmentBSides IR in Heterogeneous Environment
BSides IR in Heterogeneous EnvironmentStefano Maccaglia
 
Light, Dark and... a Sunburst... dissection of a very sophisticated attack.
Light, Dark and... a Sunburst... dissection of a very sophisticated attack.Light, Dark and... a Sunburst... dissection of a very sophisticated attack.
Light, Dark and... a Sunburst... dissection of a very sophisticated attack.Stefano Maccaglia
 
Ceh v8 labs module 11 session hijacking
Ceh v8 labs module 11 session hijackingCeh v8 labs module 11 session hijacking
Ceh v8 labs module 11 session hijackingAsep Sopyan
 
Buffer overflow attacks
Buffer overflow attacksBuffer overflow attacks
Buffer overflow attacksKapil Nagrale
 
Threat hunting for Beginners
Threat hunting for BeginnersThreat hunting for Beginners
Threat hunting for BeginnersSKMohamedKasim
 
Ceh v8 labs module 10 denial of service
Ceh v8 labs module 10 denial of serviceCeh v8 labs module 10 denial of service
Ceh v8 labs module 10 denial of serviceAsep Sopyan
 

Mais procurados (20)

CoinMiners are Evasive - BsidesTLV
CoinMiners are Evasive - BsidesTLVCoinMiners are Evasive - BsidesTLV
CoinMiners are Evasive - BsidesTLV
 
Exploitation techniques and fuzzing
Exploitation techniques and fuzzingExploitation techniques and fuzzing
Exploitation techniques and fuzzing
 
Reconnaissance not always about resources
Reconnaissance not always about resourcesReconnaissance not always about resources
Reconnaissance not always about resources
 
Software Security (Vulnerabilities) And Physical Security
Software Security (Vulnerabilities) And Physical SecuritySoftware Security (Vulnerabilities) And Physical Security
Software Security (Vulnerabilities) And Physical Security
 
Cyber threat-hunting---part-2-25062021-095909pm
Cyber threat-hunting---part-2-25062021-095909pmCyber threat-hunting---part-2-25062021-095909pm
Cyber threat-hunting---part-2-25062021-095909pm
 
.NET for hackers
.NET for hackers.NET for hackers
.NET for hackers
 
Buffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the StackBuffer Overflow - Smashing the Stack
Buffer Overflow - Smashing the Stack
 
Ceh v8 labs module 02 footprinting and reconnaissance
Ceh v8 labs module 02 footprinting and reconnaissanceCeh v8 labs module 02 footprinting and reconnaissance
Ceh v8 labs module 02 footprinting and reconnaissance
 
Malware Detection - A Machine Learning Perspective
Malware Detection - A Machine Learning PerspectiveMalware Detection - A Machine Learning Perspective
Malware Detection - A Machine Learning Perspective
 
Understanding the fundamentals of attacks
Understanding the fundamentals of attacksUnderstanding the fundamentals of attacks
Understanding the fundamentals of attacks
 
Malware Classification and Analysis
Malware Classification and AnalysisMalware Classification and Analysis
Malware Classification and Analysis
 
HackInBo2k16 - Threat Intelligence and Malware Analysis
HackInBo2k16 - Threat Intelligence and Malware AnalysisHackInBo2k16 - Threat Intelligence and Malware Analysis
HackInBo2k16 - Threat Intelligence and Malware Analysis
 
Accurately detecting source code of attacks that increase privilege
Accurately detecting source code of attacks that increase privilegeAccurately detecting source code of attacks that increase privilege
Accurately detecting source code of attacks that increase privilege
 
BSides IR in Heterogeneous Environment
BSides IR in Heterogeneous EnvironmentBSides IR in Heterogeneous Environment
BSides IR in Heterogeneous Environment
 
Light, Dark and... a Sunburst... dissection of a very sophisticated attack.
Light, Dark and... a Sunburst... dissection of a very sophisticated attack.Light, Dark and... a Sunburst... dissection of a very sophisticated attack.
Light, Dark and... a Sunburst... dissection of a very sophisticated attack.
 
Ceh v8 labs module 11 session hijacking
Ceh v8 labs module 11 session hijackingCeh v8 labs module 11 session hijacking
Ceh v8 labs module 11 session hijacking
 
Buffer overflow attacks
Buffer overflow attacksBuffer overflow attacks
Buffer overflow attacks
 
Threat hunting for Beginners
Threat hunting for BeginnersThreat hunting for Beginners
Threat hunting for Beginners
 
A Threat Hunter Himself
A Threat Hunter HimselfA Threat Hunter Himself
A Threat Hunter Himself
 
Ceh v8 labs module 10 denial of service
Ceh v8 labs module 10 denial of serviceCeh v8 labs module 10 denial of service
Ceh v8 labs module 10 denial of service
 

Semelhante a 20101017 program analysis_for_security_livshits_lecture03_security

Semelhante a 20101017 program analysis_for_security_livshits_lecture03_security (20)

AI for Cybersecurity Innovation
AI for Cybersecurity InnovationAI for Cybersecurity Innovation
AI for Cybersecurity Innovation
 
Hacking 1224807880385377-9
Hacking 1224807880385377-9Hacking 1224807880385377-9
Hacking 1224807880385377-9
 
We cant hack ourselves secure
We cant hack ourselves secureWe cant hack ourselves secure
We cant hack ourselves secure
 
Hacking Presentation
Hacking PresentationHacking Presentation
Hacking Presentation
 
Super1
Super1Super1
Super1
 
Creating Your Own Threat Intel Through Hunting & Visualization
Creating Your Own Threat Intel Through Hunting & VisualizationCreating Your Own Threat Intel Through Hunting & Visualization
Creating Your Own Threat Intel Through Hunting & Visualization
 
Introduction To Ethical Hacking
Introduction To Ethical HackingIntroduction To Ethical Hacking
Introduction To Ethical Hacking
 
Hacking by Pratyush Gupta
Hacking by Pratyush GuptaHacking by Pratyush Gupta
Hacking by Pratyush Gupta
 
Penetration Testing Basics
Penetration Testing BasicsPenetration Testing Basics
Penetration Testing Basics
 
BSidesJXN 2017 - Improving Vulnerability Management
BSidesJXN 2017 - Improving Vulnerability ManagementBSidesJXN 2017 - Improving Vulnerability Management
BSidesJXN 2017 - Improving Vulnerability Management
 
Ethical_Hacking_ppt
Ethical_Hacking_pptEthical_Hacking_ppt
Ethical_Hacking_ppt
 
Hacking and its Defence
Hacking and its DefenceHacking and its Defence
Hacking and its Defence
 
Hack the hack
Hack the hackHack the hack
Hack the hack
 
Modern Malware and Threats
Modern Malware and ThreatsModern Malware and Threats
Modern Malware and Threats
 
Hacking
HackingHacking
Hacking
 
Hacking
HackingHacking
Hacking
 
Network security
Network securityNetwork security
Network security
 
Ethical Hacking
Ethical HackingEthical Hacking
Ethical Hacking
 
Web security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-kearyWeb security-–-everything-we-know-is-wrong-eoin-keary
Web security-–-everything-we-know-is-wrong-eoin-keary
 
Hacking In Detail
Hacking In DetailHacking In Detail
Hacking In Detail
 

Mais de Computer Science Club

20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugsComputer Science Club
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugsComputer Science Club
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugsComputer Science Club
 
20140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture1220140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture12Computer Science Club
 
20140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture1120140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture11Computer Science Club
 
20140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture1020140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture10Computer Science Club
 
20140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture0920140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture09Computer Science Club
 
20140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture0220140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture02Computer Science Club
 
20140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture0120140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture01Computer Science Club
 
20140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-0420140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-04Computer Science Club
 
20140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture0120140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture01Computer Science Club
 

Mais de Computer Science Club (20)

20141223 kuznetsov distributed
20141223 kuznetsov distributed20141223 kuznetsov distributed
20141223 kuznetsov distributed
 
Computer Vision
Computer VisionComputer Vision
Computer Vision
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs
 
20140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture1220140511 parallel programming_kalishenko_lecture12
20140511 parallel programming_kalishenko_lecture12
 
20140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture1120140427 parallel programming_zlobin_lecture11
20140427 parallel programming_zlobin_lecture11
 
20140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture1020140420 parallel programming_kalishenko_lecture10
20140420 parallel programming_kalishenko_lecture10
 
20140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture0920140413 parallel programming_kalishenko_lecture09
20140413 parallel programming_kalishenko_lecture09
 
20140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture0220140329 graph drawing_dainiak_lecture02
20140329 graph drawing_dainiak_lecture02
 
20140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture0120140329 graph drawing_dainiak_lecture01
20140329 graph drawing_dainiak_lecture01
 
20140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-0420140310 parallel programming_kalishenko_lecture03-04
20140310 parallel programming_kalishenko_lecture03-04
 
20140223-SuffixTrees-lecture01-03
20140223-SuffixTrees-lecture01-0320140223-SuffixTrees-lecture01-03
20140223-SuffixTrees-lecture01-03
 
20140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture0120140216 parallel programming_kalishenko_lecture01
20140216 parallel programming_kalishenko_lecture01
 
20131106 h10 lecture6_matiyasevich
20131106 h10 lecture6_matiyasevich20131106 h10 lecture6_matiyasevich
20131106 h10 lecture6_matiyasevich
 
20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich
 
20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich20131027 h10 lecture5_matiyasevich
20131027 h10 lecture5_matiyasevich
 
20131013 h10 lecture4_matiyasevich
20131013 h10 lecture4_matiyasevich20131013 h10 lecture4_matiyasevich
20131013 h10 lecture4_matiyasevich
 
20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich
 
20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich20131006 h10 lecture3_matiyasevich
20131006 h10 lecture3_matiyasevich
 

20101017 program analysis_for_security_livshits_lecture03_security

  • 1. Introduction to Systems Security Ben Livshits 10/16/2010 Some slides are borrowed from CS 155 at Stanford
  • 2. Organization General introduction to security What is system security? Threats Trends Approaches to finding vulnerabilities Security vulnerabilities Memory-based exploits Web application vulnerabilities
  • 3. What is Security? System correctness If user supplies expected input, system generates desired output Security If attacker supplies unexpected input, system does not fail in certain ways Goal of the attacker is to make the system fail in “interesting ways”
  • 4. What is security? System correctness Good input  Good output Think “verification” Security Bad input  Bad output Think “not exploitable”
  • 5. What is security? System correctness More features: better Security More features: can be worse
  • 6. Security properties Confidentiality Information about system or its users cannot be learned by an attacker Integrity The system continues to operate properly, only reaching states that would occur if there were no attacker Availability Actions by an attacker do not prevent users from having access to use of the system
  • 7. General picture System Attacker Alice Security is about Honest user (e.g., Alice, Bob, …) Dishonest Attacker How the Attacker Disrupts honest user’s use of the system (Integrity, Availability) Learns information intended for Alice only (Confidentiality)
  • 8. Network security Network Attacker Intercepts and controls network communication System Alice
  • 9. Web security System Web Attacker Sets up malicious site visited by victim; no control of network Alice
  • 10. Operating system security OS Attacker Controls malicious files and applications Alice
  • 11. System Attacker Alice Confidentiality: Attacker does not learn Alice’s secrets Integrity: Attacker does not undetectably corrupt system’s function for Alice Availability: Attacker does not keep system from being useful to Alice
  • 13. Historical hackers (prior to 2000) Profile: Male Between 14 and 34 years of age Computer addicted No permanent girlfriend No Commercial Interest !!! Source: Raimund Genes
  • 14. Typical Botherder: 0x80" (pronounced X-eighty) Washington Post: Invasion of the Computer Snatchers High school dropout “…most of these people I infect are so stupid they really ain't got no business being on the Internet in the first place.“ Working hours: approx. 2 minutes/day to manage Botnet Monthly earnings: $6,800 on average Daily Activities: Chatting with people while his bots make him money Recently paid $800 for an hour alone in a VIP room with several dancers Job Description: Controls 13,000+ computers in more than 20 countries Infected Bot PCs download Adware then search for new victim PCs Adware displays ads and mines data on victim's online browsing habits. Bots collect password, e-mail address, SS#, credit and banking data Gets paid by companies like TopConverting.com, GammaCash.com, Loudcash, or 180Solutions. 14
  • 15. Some things in the news Nigerian letter (419 Scams) still works: Michigan Treasurer Sends 1.2MUSD of State Funds !!! Many zero-day attacks Google, Excel, Word, Powerpoint, Office … Criminal access to important devices Numerous lost, stolen laptops, storage media, containing customer information Second-hand computers (hard drives) pose risk Vint Cerf estimates ¼ of PCs on Internet are bots 15
  • 16. Trends for 2010 Malware, worms, and Trojan horses spread by email, instant messaging, malicious or infected websites Botnets and zombies improving their encryption capabilities, more difficult to detect Scareware – fake/rogue security software Attacks on client-side software browsers, media players, PDF readers, etc. Ransom attacks malware encrypts hard drives, or DDOS attack Social network attacks Users’ trust in online friends makes these networks a prime target. Cloud Computing - growing use will make this a prime target for attack. Web Applications - developed with inadequate security controls Budget cuts - problem for security personnel and a boon to cyber criminals. Texas CISO, Feb 2010 Same list in Oklahoma Monthly Security Tips Newsletter
  • 19. Reported Web Vulnerabilities "In the Wild" Data from aggregator and validator of  NVD-reported vulnerabilities
  • 20. Web vs System vulnerabilities XSS peak
  • 21. Web attack toolkit: MPack Basic setup Toolkit hosted on web server Infects pages on that server Page visitors get infected Features Customized: determines exploit on the fly, based on user’s OS, browser, etc Easy to use: management console provides stats on infection rates Customer care toolkit can be purchased with one-year support contract! 21
  • 22. Finding Vulnerabilities Static analysis Abstract interpretation Dataflow Pointer analysis etc. Runtime analysis Fuzzing Testing Simulation Symbolic execution Model checking
  • 23. Necessary BackgroundonMemory Exploits and Web Application Vulnerabilities 23
  • 24. Outline 24 Memory safety attacks Buffer overruns Format string vulnerabilities Web application vulnerabilities SQL injections Cross-site scripting attacks
  • 26. Buffer Overrun Example 26 Frame 1 Frame 2 str ret sfp local str ret sfp local void lame (void) { char small[30]; gets(small); printf("%s", small); }
  • 27. Input Validation Classifying vulnerabilities: Buffer overflows can be viewed as an example of improper input validation Another related type of vulnerability is information leaks Other notable examples: Format string vulnerabilities SQL injection attacks Cross-site scripting attacks Mechanisms to prevent attacks Better input validation Safe programming techniques Techniques for detecting potential buffer overflows in code Static analysis Runtime analysis Fuzzing/penetration testing Write-box fuzzing etc. 27
  • 28. Secure Programming Techniques Validate all input Easier said than done Why is that? Avoid buffer overflows Use safe string manipulation functions Careful length checking Avoid statically declared arrays etc. Or use a memory-safe language Java or C# JavaScript (not type-safe) 28
  • 29. Validating Input Determine acceptable input, check for match --- don’t just check against list of “non-matches” Limit maximum length Watch out for special characters, escape chars. Check bounds on integer values Check for negative inputs Check for large inputs that might cause overflow! 29
  • 30. Avoid strcpy, … We have seen that strcpy is unsafe strcpy(buf, str) simply copies memory contents into buf starting from *str until “” is encountered, ignoring the size of buf Avoid strcpy(), strcat(), gets(), etc. Use strncpy(), strncat(), instead Still, computing proper bounds is difficult in practice Easy to mess up, off-by-one errors are common 30
  • 31. Static and Dynamic Analysis Static analysis: run on the source code prior to deployment; check for known flaws e.g., flawfinder, cqual Or Prefix/Prefast Or Coverityor Fortify tools Will look at some more recent work in this course as well as older stuff Dynamic analysis: try to catch (potential) buffer overflows during program execution Soundness Precision Comparison? Static analysis very useful, but not perfect False positives False negatives Dynamic analysis can be better (in tandem with static analysis), but can slow down execution Historically of great importance, drove adoption of type-safe languages such as Java and C# 31
  • 32. Dynamic analysis: Libsafe Very simple example of what can be done at runtime Intercepts all calls to, e.g., strcpy(dest, src) Validates sufficient space in current stack frame: |frame-pointer – dest| > strlen(src) If so, executes strcpy; otherwise, terminates application 32
  • 33. Preventing Buffer Overflows Operating system support: Can mark stack segment as non-executable Randomize stack location Problems: Does not defend against `return-to-libc’ exploit Overflow sets ret-addr to address of libc function Does not prevent general buffer overflow flaws, or heap overflow Basic heap overflows can be helped with ALSR 33
  • 34. Heap-based Buffer Overruns and Heap Spraying 34 Buffer overruns consist of two steps Introduce the payload Cause the program to jump to it Can put the payload/shellcode in the heap Arbitrary amounts of code Doesn’t work with heap randomization Location of the payload changes every time Heap spraying: Allocate multiple copies of the payload When the jump happens, it hits the payload with a high probability
  • 35. StackGuard Embed random “canaries” in stack frames and verify their integrity prior to function return This is actually used! Helpful, but not foolproof… Frame 1 Frame 2 str ret sfp local canary str ret sfp local canary 35
  • 36. More Methods … Address obfuscation Encrypt return address on stack by XORing with random string. Decrypt just before returning from function Attacker needs decryption key to set return address to desired value 36
  • 38. Format String Vulnerabilities What is the difference between printf(buf);andprintf(“%s”, buf);? What if buf holds %x ? Look at memory, and what printf expects… 38
  • 39. Format String Exploits Technique: Declare a variable of type int in line 4 and call it bytes_formatted Line 6 the format string specifies that 20 characters should be formatted in hexadecimal (“%.20x”) using buffer When this is done, due to the “%n” specifier write the value 20 to bytes_formatted Result: This means that we have written a value to another memory location Very definition of violating memory safety May be possible to gain control over a program’s execution #include <stdio.h> int main() { intbytes_formatted=0; char buffer[28]=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”;  printf(“%.20x%n”,buffer,&bytes_formatted); printf( “The number of bytes formatted in the previous printf statement was %d”,bytes_formatted);  return 0; }  39
  • 40. Other Input Validation Bugs Integer overflow… Consider the code:strncpy(msg+offset, str, slen); where the adversary may control offset By setting the value high enough, it will wrap around and be treated as a negative integer! Write into the msg buffer instead of after it 40
  • 42. SQL Injection Attacks Affect applications that use untrusted input as part of an SQL query to a back-end database Specific case of a more general problem: using untrusted input in commands 42
  • 43. SQL Injection: Example Consider a browser form, e.g.: When the user enters a number and clicks the button, this generates an http request like https://www.pizza.com/show_orders?month=10 43
  • 44. Example Continued… Upon receiving the request, a Java program might produce an SQL query as follows: A normal query would look like: sql_query = "SELECT pizza, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " AND order_month= " + request.getParameter("month"); SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10 44
  • 45. Example Continued… What if the user makes a modified http request:https://www.pizza.com/show_orders?month=0%20OR%201%3D1 (Parameters transferred in URL-encoded form, where meta-characters are encoded in ASCII) This has the effect of settingrequest.getParameter(“month”)equal to the string0 OR 1=1 45
  • 46. Example Continued So the script generates the following SQL query: Since AND takes precedence over OR, the above always evaluates to TRUE The attacker gets every entry in the database! SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 OR 1=1 ( ) 46
  • 47. Even Worse… Craft an http request that generates an SQL query like the following: Attacker gets the entire credit card database as well! SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 OR 1=0UNION SELECT cardholder, number, exp_dateFROM creditcards 47
  • 48. More Damage… SQL queries can encode multiple commands, separated by ‘;’ Craft an http request that generates an SQL query like the following: Credit card table deleted! DoS attack SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 ;DROP TABLE creditcards 48
  • 49. More Damage… Craft an http request that generates an SQL query like the following: User (with chosen password) entered as an administrator! Database owned! SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 ;INSERT INTO admin VALUES (‘hacker’, ...) 49
  • 50. May Need to be More Clever… Consider the following script for text queries: Previous attacks will not work directly, since the commands will be quoted But easy to deal with this… sql_query = "SELECT pizza, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " AND topping= ‘ " + request.getParameter(“topping") + “’” 50
  • 51. Example Continued… Craft an http request where request.getParameter(“topping”)is set toabc’; DROP TABLE creditcards; -- The effect is to generate the SQL query: (‘--’ represents an SQL comment) SELECT pizza, quantity, order_day FROM orders WHERE userid=4123 AND toppings=‘abc’;DROP TABLE creditcards ; --’ 51
  • 53. Solutions? Blacklisting Whitelisting Encoding routines Prepared statements/bind variables Mitigate the impact of SQL injection 53
  • 54. Blacklisting? I.e., searching for/preventing ‘bad’ inputs E.g., for previous example: …where kill_chars() deletes, e.g., quotes and semicolons sql_query = "SELECT pizza, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " AND topping= ‘ " + kill_chars(request.getParameter(“topping")) + “’” 54
  • 55. Drawbacks of Blacklisting How do you know if/when you’ve eliminated all possible ‘bad’ strings? If you miss one, could allow successful attack Does not prevent first set of attacks (numeric values) Although similar approach could be used, starts to get complex! May conflict with functionality of the database E.g., user with name O’Brien 55
  • 56. Whitelisting Check that user-provided input is in some set of values known to be safe E.g., check that month is an integer in the right range If invalid input detected, better to reject it than to try to fix it Fixes may introduce vulnerabilities Principle of fail-safe defaults 56
  • 57. Prepared Statements/bind Variables Prepared statements: static queries with bind variables Variables not involved in query parsing Bind variables: placeholders guaranteed to be data in correct format 57
  • 58. A SQL Injection Example in Java PreparedStatementps = db.prepareStatement( "SELECT pizza, quantity, order_day " + "FROM orders WHERE userid=? AND order_month=?"); ps.setInt(1, session.getCurrentUserId()); ps.setInt(2, Integer.parseInt(request.getParameter("month"))); ResultSet res = ps.executeQuery(); Bind variables 58
  • 59. There’s Even More 59 Practical SQL Injection: Bit by Bit Overall, SQL injection is easy to fix by banning certain APIs Prevent queryExecute-type calls with non-constant arguments Very easy to automate See a tool like LAPSE that does it for Java
  • 60. Cross-site Scripting 60 If the application is not careful to encode its output data, an attacker can inject script into the output out.writeln(“<div>”); out.writeln(req.getParameter(“name”)); out.writeln(“</div>”); name: <script>…; xhr.send(document.cookie);</script> Simplest version called reflected or type-1 XSS
  • 61. Memory Exploits and Web App Vulnerabilities Compared Buffer overruns Stack-based Return-to-libc, etc. Heap-based Heap spraying attacks Requires careful programming or memory-safe languages Don’t always help as in the case of JavaScript-based spraying Static analysis tools Format string vulnerabilies Generally, better, more restrictive APIs are enough Simple static tools help Cross-site scripting XSS-0, -1, -2, -3 Requires careful programming Static analysis tools SQL injection Generally, better, more restrictive APIs are enough Simple static tools help 61