FIT5003 Software Security
Software Security In a Nutshell
Apostolos Fournaris
1
Software Security
Renewed interest
“idea of engineering software so that it continues to function correctly under malicious attack”
Existing software is riddled with design flaws and implementation bugs
“any program, no matter how innocuous it seems, can harbor security holes”
2
Threat Modelling (Architectural Risk Analysis)
STRIDE Approach
• Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege
• To follow STRIDE, you decompose your system into relevant components, analyse each component for susceptibility to threats, and mitigate them
4
Threat Modelling Process
5
Level 1 Diagram
6
Standard Mitigations
7
Attacks and Defenses
Attack Methodology
STRIDE Threat Model
Threat
Spoofing
Tampering Repudiation Information Disclosure Denial of Service Elevation of Privilege
Property we want
Authentication Integrity Nonrepudiation Confidentiality Availability Authorization
9
Attack Methodology (STRIDE)
Spoofing
Impersonating another person/process
Cookie Replay / Session Hijacking CSRF (Cross-site request forgery)
10
Attack Methodology (STRIDE)
Tampering
Unauthorized alternations
XSS
SQL Injection
11
Attack Methodology (STRIDE)
Repudiation
Denying claims/unproven actions
Audit Log Deletion Insecure Backup
12
Attack Methodology (STRIDE)
Information Disclosure
Exposure to unauthorized person/process
Eavesdropping Verbose Exception
13
Attack Methodology (STRIDE)
Denial of Service (DOS)
Service unavailability Website defacement
14
Attack Methodology (STRIDE)
Elevation of Privilege
Increasing person/process access level Logic Flow Attacks
15
Buffer Overflow Attack
stack grows
malicious
code
main()’s
stack
foo()’s
stack
overwrite
Trigger the
execution of
malicious payloads
overwrite
new address
overwrite
buffer[11] ……
buffer[0]
buffer copy
16
Countermeasures
Developer approaches:
• Use of safer functions like strncpy(), strncat() etc, safer dynamic link libraries that check the length of the data before copying.
OS approaches:
• ASLR (Address Space Layout Randomization)
Compiler approaches:
• Stack-Guard-> Stack Canaries
Hardware approaches:
• Non-Executable bit (NX bit) Stack
Return Oriented Programming Attacks
Chain gadgets to execute malicious code.
A gadget is a suite of instructions which end by the branch
●
instruction ret (Intel) or the equivalent on ARM.
– Intel examples: ● pop eax ; ret
● xor ebx, ebx ; ret
– ARM examples: ● pop {r4, pc}
● str r1, [r0] ; bx lr
Objective: Use gadgets instead of classical shellcode Why?
Gadgets are mainly located on segments without ASLR and on pages marked as executables – It can bypass the ASLR
– It can bypass the NX bit
ROP Attack process
Attack Road map:
• Find your gadgets
• Store your gadgets addresses on the stack
You must to overwrite the saved eip with the address of your first gadget
Example on x86 (figure)
Gadget1 is executed and returns Gadget2 is executed and returns Gadget3 is executed and returns
And so on until all instructions that you want are executed
So, the real assembly code execution is: pop eax
xor edx, edx inc ecx
Obfuscation
Obfuscation is the obscuring of the
intended meaning of communication by making the message difficult to understand, usually
with confusing and ambiguous language.
In network security, obfuscation refers to methods used to obscure an attack payload from inspection by network protection systems.
20
Obfuscation
int main()
{ Abstraction
Destroy module structure, classes, functions, etc.!
Replace data structures with new representations!
………… }
Transformation
Data Transformation
Control Transformation
Dynamic Transformation
Destroy if-, while-, repeat-, et}c.!
Make the program change at runtime!
21
Java Security (Now)
Bootstrap class files
System class files
User class files
CodeSource(URL, Certificates)
Policy Database Permissions
Bytecode Verifier
Bootstrap ClassLoader
System ClassLoader
ClassLoader
Security Manager Protection Domains
AccessController
Operating System
Keystore
Hardware
22
Java Security
Security Manager
The class java.lang.SecurityManager is the focal point of authorization.
SecurityManager is concrete, with a public constructor and appropriate checks in place to ensure that it can be invoked in an authorized manner.
It consists of a number of check methods, e.g,: CheckPermission method is used to check to see if the requested access has the given permission based on policy.
23
Java Security
Bootstrap Class Loader
The bootstrap classloader is platform specific machine instructions that kick off the whole classloading process.
Bootstrap classes – Classes that comprise the Java platform, including the classes in rt.jar and several other important jar files.
The bootstrap classloader also takes care of loading all of the code needed to support the basic Java Runtime Environment (JRE), including classes in the java.util and the java.lang packages.
24
Java Security
System Class Loader
classes from the system class path, which are set by the CLASSPATH environment variable
java -Djava.system.class.loader=com.test.MyClassLoader MyApplication
25
Java Security
Class Loader
Customized ClassLoader or a subclass from java.security.SecureClassLoader provides security features beyond the standard Java2 security model.
ClassLoader loads classes into VM and is responsible for the namespaces at runtime. Namespaces as identically named identifiers can reference different objects.
Primordial class loader loads bootstrap classes in a platform-dependent manner.
System classes, some classes in java.* package are essential to the JVM and the runtime system are loaded by System ClassLoader.
when are classes loaded?
1. when the new bytecode is executed (for example, FooClass f = new FooClass();) 2. when the bytecodes make a static reference to a class (for example, System.out).
26
Java Security
Byte Code Verifier
Checks a classfile for validity:
Code should have only valid instructions and register use.
Code does not overflow/underflow stack.
Does not convert data types illegally.
Accesses objects correct types.
Method calls use correct number and types of parameters.
References to other classes use legal names.
27
Java Security
CodeSource
Java Code is downloaded over a network, so the code’s signature and author are critical to maintain a secure environment.
The object java.security.CodeSource describes a piece of code.
CodeSource encapsulates the code’s origin, which is specified as an URL.
Set of digital certificates containing public keys corresponding to the set of private keys are used to sign the code
28
Java Security
Keystore
Keystore is a password-protected database that holds private keys and certificates.
The password is selected at the time of creation.
Each database entry can be guarded by its own password
for extra security.
Certificates accepted into the keystore are considered to be trusted.
29
Access Policy
The policy file(s) specify what permissions
are allowed for code from a specified code
source, and executed by a specified
principal.
$ /usr/libexec/java_home
/Library/Java/JavaVirtualMachines/
jdk1.8.0_152.jdk/Contents/Home
$JAVA_HOME/jre/lib/security/java.security
$JAVA_HOME/jre/lib/security/java.policy
30
Access Policy
$JAVA_HOME/jre/lib/security/java.security
$JAVA_HOME/jre/lib/security/java.policy
policy.url.1=file:${java.home}/lib/security/java.policy policy.url.2=file:${user.home}/.java.policy
grant codeBase “file:${{java.ext.dirs}}/*” { };permission java.security.AllPermission;
grant {
permission java.util.PropertyPermission “java.version”,
“read”; };
31
Access Controller
static boolean unaligned() {
if (unalignedKnown)
return unaligned;
String arch = AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(“os.arch”));
unaligned = arch.equals(“i386”) || arch.equals(“x86”) || arch.equals(“amd64”) || arch.equals(“x86_64”);
unalignedKnown = true;
return unaligned;
}
get_property permission
32
Access Controller
static boolean unaligned() {
if (unalignedKnown)
return unaligned;
String arch = AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(“os.arch”));
unaligned = arch.equals(“i386”) || arch.equals(“x86”) || arch.equals(“amd64”) || arch.equals(“x86_64”);
unalignedKnown = true;
return unaligned;
}
get_property permission
33
Reflection
Class Method Constructor Field Modifier Others
Reflection
Method[] methods = MyObject.class.getMethods();
for(Method method : methods){
System.out.println(“method = ” + method.getName());
}
This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.
Reflection
How to get Metadata of Class?
}
import java.io.Serializable;
public abstract class fit5003base implements Serializable,Cloneable {
213 4
1 cls.getName();
2 cls.getModifiers();
3 cls.getInterfaces();
4 cls.getSuperclass().getName();
Reflection
How to get Metadata of Variable?
from the specified class as well as from its super
class
Field[] field1 = cls.getFields();
//from the specified class only
Field[] fiel2 = cls.getDeclaredFields();
Java Deserialization in a Nutshell
Serializable creates:
•a public hidden constructor
•a public interface to all fields of that class
Deserialization is Object Creation and Initialization •Without invoking the actual class’s constructor
Any available class can be deserialized
•Calling ObjectInputStream.readObject() using untrusted data
can result in malicious behavior
Public Key Encryption
Generating Key
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(“RSA”); keyGen.initialize(512);
KeyPair pair = keyGen.generateKeyPair();
PublicKey publicKey = pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
Cipher cipher = Cipher.getInstance(“RSA”); cipher.init(Cipher.ENCRYPT_MODE, publickey); byte[] buf = cipher.doFinal(“xyz”.getBytes()); System.out.println(new String(buf));
Cipher cipher2 = Cipher.getInstance(“RSA”); cipher2.init(Cipher.DECRYPT_MODE, privatekey); byte[] buf2 = cipher2.doFinal(buf); System.out.println(new String(buf2));
publicKey
Encrypt
privateKey
Decrypt
39
Android Basics
Component
Activity
Service
Broadcast Receiver
Content Provider
40
Explicit vs. Implicit Intents
– Explicit
– The intent “explicitly” specifies which component it wants to talk to – It specifies the target’s full package name / component
– Implicit
– The intent just describes the type of action to perform (and, optionally, some
data)
– Good source of info / tutorial: link
41
Implicit Intent (example)
Activity1
Activity2
ICC methods:
e.g., startActivity(Intent)
Action: test.ACTION Category: test.CATEGORY
Activity3
42
Explicit Intent (example)
Activity1
Activity2
ICC methods:
e.g., startActivity(Intent)
destComp: Activity2
Activity3
43
ICC Issues
Activity1
Want to Send SMS but does not declare SEND_SMS permission
Activity2
Declared SEND_SMS permission
MaliciousActivity
Exploit
SEND_SMS
44
ICC Issues
Activity Hijacking
Service Hijacking
Broadcast Theft
Hijacking
Malicious Components
Component2
Component1
Launch
Activity Launch
Service Launch
Broadcast Injection
Malicious Components
45
Android Permission System
activity
restricts access to the activity
checked when starting activity
throw SecurityException if caller does not have required permission
service
restricts who can start, stop or bind to the service
receiver
restricts who can send broadcasts to the BroadcastReceiver checked at delivery, after broadcast was sent
does not throw exception in case of permission failure
provider
restrict who can access the data
read and write permissions
checked when performing operations(e.g. query, insert)
46
Permission Request
…
47
Clone Detection
Original App
Carrier
Hook
Malicious Piggybacked Payload App
Rider
Wu Zhou, Yajin Zhou, Michael Grace, Xuxian Jiang, and Shihong Zou. Fast, scalable detection of “piggybacked” mobile applications. In CODASPY ’13, pages 185–196, New York, NY, USA, 2013
48
Clone Detection
Similarity Comparison
Symptom Discovery
(Un)Supervised Learning Runtime Monitoring
49
Privacy Leak
Taint Analysis
source
sink
50
Privacy Leak
public class Activity_A { void onCreate(Bundle b) {
String id = telManager.getDeviceId(); //…
String alias = id;
String number = “+3524666445556”;
}}sms.sendTextMessage(number, null, alias, null, null);
source
sink
51
Security Testing (Methodology)
White Box:
Static Code Analysis
Black Box Fuzzing
52
Static Code Analysis
Goals:
Find common bugs quickly
Allow humans to focus on parts of code likely to be risky
Limitations
Cannot find design level vulnerabilities
Cannot make a judgement of importance of a found vulnerability
Only detect vulnerabilities in tool’s “rule database” Suffer from errors:
False positive: reported bugs are not really bugs False negative: missed reporting a real bug
53
Control-Flow Graph (CFG)
Exercise!
read(x);
while (X<10){
X←X-1;
A[X]←10;
if (X=4)
B0: ENTRY
B1:
;
read(x)
if (x
0)
goto
X=x
>=
goto
B
2
B4: Y=x+5
B5: EXIT
54
1
B
4
B2:
X=X
–
1 A[X]=10
;
If (
X=4)
3
;
}; X←X-2; B3: Y←X+5;
–
Static Code Analysis
Simple (usually free) search-based tools
Examples: FlawFinder, RATS, ITS4, …
Search source file for “dangerous functions” known to cause common vulnerabilities
e.g. strcpy(), gets() for buffer overflows Produces list of “hits” and ranks them by risk Better than just pure search
Ignores commented code Ignores strings
Some risk ranking
But little attempt to analyze relationships within code 55
Fuzz Testing
Automaticaly generate test cases
Many slightly anomalous test cases are input
into a target interface
Application is monitored for errors
Inputs are generally either file based (.pdf, .png, .wav, .mpg)
Or network based… http, SNMP, SOAP
Or other…
e.g. crashme()
56
Fuzz Testing (Mutation)
Strengths
Super easy to setup and automate
Little to no protocol knowledge required Weaknesses
Limited by initial corpus
May fail for protocols with checksums, those which depend on challenge response, etc.
57
Fuzz Testing (Generation-based)
Strengths
Completeness
Can deal with complex dependencies e.g. checksums
Weaknesses
Have to have spec of protocol
Often can find good tools for existing protocols e.g. http, SNMP Writing generator can be labor intensive for complex
protocols
The spec is not the code
58
Web Technologies
Web Security Overview
3-Tier Web Architecture: Client-Server-Database
Interface tier
Logic tier
Storage tier
Client Web Browser
(IE, Chrome, Firefox,… )
Web Server
(IIS, Apache, …)
Database / Backend server
(MySQL, MS-SQL, Oracle, …)
HTTP / HTTPS
Javascript, VBScript, DOM/Ajax/ JSON/XML, browser extensions: Java applets, ActiveX,Flash,Silverlight,
…)
SQL, SOAP /XML,…
Browser script (HTML / HTML5, CSS,
Server Script (PHP, Java,
ASP.NET, Python, Perl, …)
Database language
(MySQL,
MS-SQL, Oracle, …)
59
Web Security (Server Side)
Server Side: Database Query Languages
• Structured Query Language (SQL)
• Variants: Oracle, MS-SQL, MySQL
• SQL manages relational databases:
• Database consists of tables
• Each table has a number of rows (database records) , e.g. a row per user
• Each row has a number of columns (data fields), e.g. “email address”, “name”, “age”,…
• SQL language queries: read, update, add, or delete data
• E.g. SELECT email FROM users WHERE name = ‘Li’
• Returns email column value for rows in users table where the name column value = ‘Li’. 60
Web Security (Browser Side)
Client Side: Browser Security Policy
• Browser security goals:
• User can safely visit any web site
• Even malicious web sites cannot access / modify client’s local disk / memory information without user’s permission
• Browser runs Javascript in a sandbox – access OS / file system via API enforcing access control
• E.g. Upload authorization via file picker dialog.
• However, a web site can still track users (e.g. cookies,…)!
• User can safely visit multiple web sites in same browser:
• Open page from site X cannot interfere (read/write) with open page
from site Y
• E.g. banking site window should not be read by script in social networking window
• Enforced via the browser Same Origin Policy
61
SQL Injection Vulnerabilities
• Another method to bypass escaping: second-order SQLi
• Suppose ‘ character in user input string was escaped (replaced by
’’) by web application
A second-order vulnerability for string inputs may still be exploitable:
• Consider app registering users in database and then retrieving
• Attack first phase: attacker registers escaped input into database
• Attacker registers into database user name such as • bob‘ OR5=5–
• Due to escaping of ‘ character, this user name is processed correctly, and inserted into database
• No injected code execution in phase 1. But now the stored username string is bob‘ OR 5=5 — without escaping…
62
SQL Injection Vulnerabilities
• How to defend effectively against SQLi?
• Filtering / escaping is tricky / can often be bypassed
• Preferred robust solution: parameterized queries
• A.k.a prepared statements
• Fix root cause of injection problem: SQL database treating user data as code
• Idea: Application passes the SQL statement to SQL server in two distinct phases:
• Phase 1 (pass code): Pass desired SQL statement with placeholders (? Symbol) for data values, e.g.
$stmt = $mysqli->prepare(“SELECT District FROM City WHERE name=?”);
• Phase 2 (pass data): Pass the data values for placeholders, e.g.: $stmt->bind_param(“s”, $name);
• Finally, execute and get result, e.g.:
•$stmt->execute(); /* This executes the prepared statement $stmt */ •$result = $stmt->get_result(); /* Get result into $result */ •$stmt->close(); /* This completes the prepared statement */
• Any malicious user data passed in Phase 2 will be interpreted as data, not code. 63
REFLECTED XSS
6
Another Practical example
https://excess-xss.com/
1. The attacker crafts a URL containing a malicious string and sends it to the victim.
2. The victim is tricked by the attacker into requesting the URL from the website.
3. The website includes the malicious string from the URL in the response.
4. The victim’s browser executes the malicious script inside the response, sending the victim’s cookies to the attacker’s server.
ATTACK SCENARIO
The steps involved in a stored XSS attack
A Practical Example
https://excess-xss.com/
1. The attacker uses one of the website’s forms to insert a malicious string into the website’s database.
2. The victim requests a page from the website.
3. The website includes the malicious string from the database in the response and sends it to the victim.
4. The victim’s browser executes the malicious script inside the response, sending the victim’s cookies to the attacker’s server.
DOM-BASED XSS
Attacker can craft a URL containing JavaScript code as the value of the message parameter
This code will be dynamically written into the page and executed in the same way as if the server had returned it
E.g.
http://domain- a.net/error/18/Error.ashx?message=
28
Another Practical example
https://excess-xss.com/
1. The attacker crafts a URL containing a malicious string and sends it to the victim.
2. The victim is tricked by the attacker into requesting the URL from the website.
3. The website receives the request, but does not include the malicious string in the response.
4. The victim’s browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page.
5. The victim’s browser executes the malicious script inserted into the page, sending the victim’s cookies to the attacker’s server.
Cross-Site Request Forgeries (CSRF)
• Recall: Cross-Site Scripting (XSS) vulnerabilities need attacker script to be reflected back from application (step 4):
• XSS prevented if application output is filtered/encoded to avoid reflecting attacker script – step 4 is blocked.
• BUT, steps 2 and 3 still possible! Can this still be exploited? • Sometimes, YES, via OSRF/CSRF vulnerabilities
70
Cross-Site Request Forgeries (CSRF)
71
Session Management
• Session Fixation Vulnerabilities • Suppose:
• same session token used for all requests
• session token = URL parameter in user request • Attack:
1. Attacker logs in anonymously to http://amazon.com
• Obtains session token: SESS=2as435sdf34251sdg
2. Attacker sends user john a URL with attacker’s session token • E.g. user gets email with URL
http://amazon.com/login.php?SESS=2as435sdf34251sdg
3. User clicks attacker’s URL and logs in to Amazon:
• Amazon associates attacker’s token with logged in user john
4. Attacker uses token to hijack user’s session: • Attacker requests
http://amazon.com/browse.php?SESS=2as435sdf34251sd g• Gets access to john’s amazon session
• Defense: John gets new session token from Amazon at step 3, attacker’s session id not accepted in step 4.
72
Blockchain
73
Smart Contract
Block Mining
Tx-1
Block
Previous block A set of TXs
Nonce
Verify transactions & execute all code to update the state
Tx-2
Tx-n
New State Root Receipt Root
Broadcast Block
Miners
SHA3(Block) < D
74
Smart Contract
Code execution
• Every (full) node on the blockchain processes every transaction and stores the entire state
This is a new block!
P1 P6
P2 P3
This is a new block!
This is a new block!
This is a new block!
I’m a leader
This is a new block!
P5
This is a new block!
P4
75
Smart Contract
• Halting problem
• Cannot tell whether or not a program will run infinitely
• A malicious miner can DoS attack full nodes by including
lots of computation in their txs
• Full nodes attacked when verifying the block
uint i = 1; while (i++ > 0) {
donothing();
}
76
Smart Contract
Solution: Gas
Charge fee per computational step (“gas”). Special gas fees for operations that take up storage
Sender has to pay for the gas
77
The DAO Attack
A DAO is a Decentralized Autonomous Organization. Its goal is to codify the rules and decision making apparatus of an organization, eliminating the need for documents and people in governing, creating a structure with decentralized control.
78
Unchecked CALL Return Values
The return value of
send() is not checked
79
eEXAMs
eAssessment Platform on 23rd of June (a 2h 10min exam) Sample eExam next week
Consultations next week and on the 22nd of June
10 MCQs and 6-8 Short Essay Questions
Related to lectures AND the tutorials/labs
The answers can be derived from the slides/labs but you will have to make some critical reflection on the existing resources.
80
Thank you!
Hope you enjoyed the Unit
81