程序代写代做代考 c/c++ database compiler Java graph concurrency jvm html chain C algorithm FIT5003 Software Security

FIT5003 Software Security
Java Security I April 2020
1

Java Basics
Source code
Compiler
Class files
Libraries
➢ object-oriented
➢ multi-threaded ➢strongly typed ➢exception handling
➢very similar to C/C++, but cleaner and simpler
➢ no more struct and union
➢ no more (stand alone) functions ➢ no more multiple inheritance
➢ no more operator overloading ➢ no more pointers
➢garbage collection
➢ objects no longer in use are removed automatically from memory
Virtual Machine
2
User Developer

Java Basics
Access Control
Modifier
Class or Interface Accessibility
Member (Field or Method) Accessibility
Public
All
All if class or interface is accessible; interface members always public
Protected
N/A
Same package OR subclass
“default”
Same package
Same package
(Package private)
Private
N/A
Only same class (not subclass)
3

Java Basics
public class CreditCard {
public String acctNo = “1234”;
}
public class Test {
public static void main(String[] args) {
CreditCard cc = new CreditCard();
System.out.println(“account is ” + cc.acctNo); }
}
javac CreditCard.java
javac Test.java
java –pc . Test
CreditCard.class
Test.class
4

Java Basics
public class CreditCard {
public String acctNo = “1234”;
}
private
javac CreditCard.java
java –pc . Test
CreditCard.class
5

Java Basics
public class CreditCard {
public String acctNo = “1234”;
}
private
Security
6

Java Basics
public class CreditCard {
public void transfer500AUD () {
transfer(500); }
}
5
We should never assume that third-party
code is secure.
7

Java Basics
Security
8

Threads
– Threads allow the program to run tasks in parallel
– In many cases threads need to be synchronized, that is, be kept not to handle the same data in memory concurrently
– There are cases in which a thread needs to wait for another thread before proceeding
Never use thread-per-session – this is a wrong and un-scaled architecture – use instead Thread Pools
9

Threads
The operation we want to be threaded:
public class PrintNumbers {
static public void printNumbers() {
for(int i=0; i<1000; i++) { System.out.println( } } } Thread.currentThread().getId() + ": " + i); 10 Threads Option 1 – extending class Thread: public class Thread1 extends Thread { @Override public void run() { System.out.println("Thread1 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers.printNumbers(); // the super doesn't anything, // but just for the courtesy and good practice super.run(); } } 11 Threads Option 1 – extending class Thread (cont’): static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread1().start(); // don't call run! // (if you want a separate thread) } printNumbers(); } 12 Threads Threads in Java Option 2 – implementing Runnable: public class Thread2 implements Runnable { @Override public void run() { System.out.println("Thread2 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers.printNumbers(); } } Runnable interface is the primary template for any object that is intended to be executed by a thread. It defines a single method run(), which is meant to contain the code that is executed by the thread. Any class whose instance needs to be executed by a thread should implement the Runnable interface. 13 Threads Threads in Java Option 2 – implementing Runnable (cont’): static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread(new Thread2()).start(); // again, don't call run! // (if you want a separate thread) } printNumbers(); } 14 Threads Threads in Java Option 3 – implementing Runnable as Anonymous: static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); new Thread(new Runnable() { @Override public void run() { System.out.println("Thread3 ThreadId: " + Thread.currentThread().getId()); // do our thing printNumbers(); } }).start(); // don't call run! ... printNumbers(); } 15 Threads (Synchronization) Synchronization Synchronization of threads is needed for in order to control threads coordination, mainly in order to prevent simultaneous operations on data For simple synchronization Java provides the synchronized keyword For more sophisticated locking mechanisms, starting from Java 5, the package java.concurrent.locks provides additional locking options, see: http://java.sun.com/javase/6/docs/api/java/util/concurrent/ locks/package-summary.html 16 Threads (Synchronization) Synchronization Example 1 – synchronizing methods: public class SynchronizedCounter { private int c = 0; } public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } The synchronized keyword on a method means that if this is already locked anywhere (on this method or elsewhere) by another thread, we need to wait till this is unlocked before entering the method Reentrant is allowed 17 Threads (Synchronization) Synchronization Example 2 – synchronizing blocks: public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); } When synchronizing a block, key for the locking should be supplied (usually would be this) The advantage of not synchronizing the entire method is efficiency 18 Threads (Synchronization) Synchronization Example 3 – synchronizing using different locks: public class TwoCounters { private long c1 = 0, c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; } } public void inc2() { synchronized(lock2) { c2++; } } } You must be absolutely sure that there is no tie between c1 and c2 19 Threads (Synchronization) Synchronization Example 4 – synchronizing static methods: public class Screen { private static Screen theScreen; private Screen(){...} // private c’tor public static synchronized getScreen() { if(theScreen == null) { theScreen = new Screen(); } return theScreen; } } This is a Singleton example It is not the most efficient way to implement Singleton in Java 20 Threads (Synchronization) Synchronization Example 4 – synchronizing static methods ... Having a static method be synchronized means that ALL objects of this type are locked on the method and can get in one thread at a time. The lock is the Class object representing this class. The performance penalty might be sometimes too high – needs careful attention! 21 Threads (Synchronization) Synchronization Example 4’ – a better singleton: public class Screen { private static Screen theScreen = new Screen(); private Screen(){...} // private c’tor } No synchronization public static getScreen() { return theScreen; } 22 Threads (ThreadPools) Thread Pools Prevent the thread-per-session pitfall! Class ThreadPoolExecutor: http://java.sun.com/javase/6/docs/api/java/util/concurrent/ ThreadPoolExecutor.html https://www.owasp.org/images/8/8e/OWASP_NZDay_2011_Br ettMoore_ConcurrencyVulnerabilities.pdf 23 Threads (Security) Thread Pools Exercise Design a bank transaction system to deal with funds transferring 1) different users may transfer simultaneously. userA → 500 → userB userB → 1000 → userC 24 Java Security Security When running unknown Java programs, e.g., may contain malicious payloads, we need to control the execution of the programs. 25 Java Security ➢ ➢ ➢ ➢ ➢ Java Technology uses three mechanisms to ensure safety. Language design features(bounds checking on arrays,legal type conversions etc). An access control mechanism that controls what the code can do(file access, network access etc). Code signing: code authors can use standard cryptographic algorithms to authenticate java programming language code. Users of the code can determine who created the code and whether the code is altered or not after it was signed. 26 Java Security Access Controller ➢ To decide whether access to a critical system resource should be allowed or denied, based on the security policy currently in effect. ➢ To mark code as privileged, thus affecting subsequent access determinations. ➢ To obtain a snapshot of the current calling context, so access-control decisions from a different context can be made with respect to the saved context. 27 Java Security (History) limit the resources that can be accessed by applets JVM sandbox resources local code remote code (applets) https://docs.oracle.com/javase/6/docs/technotes/guides/security/spec/secur ity-spec.doc2.html 28 Java Security (History) every code (remote or local) has access to the system resources based on what is defined in a policy file local or remote code (signed or unsigned) JVM class loaders policy file resources 29 Java Security (Now) Bootstrap class files System class files User class files CodeSource(URL, Certificates) Security Manager Protection Domains Bytecode Verifier Policy Database Permissions Bootstrap ClassLoader System ClassLoader ClassLoader AccessController Operating System Keystore Hardware 30 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. 31 Java Security Security Manager ➢ the JVM allows only one SM to be active at a time ➢ there is a default SM provided by the JDK ➢ Java programs (applications, applets, beans, ...) can replace the default SM by their own SM only if they have permission to do so ➢invoking the SecurityManager constructor or the setSecurityManager() method will call the checkPermissions() method of the current SM and verify if the caller has the needed permissions 32 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. 33 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 34 Java Security Class Loader ➢ Is an important link in security chain and loads java byte codes into the JVM. ➢ It works in conjunction with the security manager and access controller to enforce security rules. ➢ It is involved in enforcing some security decisions earlier in an objects lifetime than the security manager. ➢ Information about the URL from which the code is originated and the code’s signers is initially available to the ClassLoader. 35 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). 36 Java Security Class Loader ➢ separate name spaces (1) classes loaded by a class loader instance belong to the same name space (2) since classes with the same name may exist on different Web sites, different Web sites are handled by different instances of the applet class loader (3) a class in one name space cannot access a class in another name space, e.g., classes from different Web sites cannot access each other ➢ establish the protection domain (set of permissions) for a loaded class ➢ enforce a search order that prevents trusted system classes from being replaced by classes from less trusted sources 37 Java Security Class Loader JVM: invokes the class loader associated with the requesting program class loader: has the class already been loaded? yes: does the program have permission to access the class? yes: return object reference no: security exception no: does the program have permission to create the requested class? yes: first delegate loading task to parent if parent returns success, then return (class is loaded) if parent returned failure, then load class and return no: security exception 38 Java Security Class Loader 4a boot class path Bootstrap class loader (searches on the boot class path) 3 4b failure loads class from a class loader instance started at JVM startup (searches on the class path) 2 5b success / failure 5a class path loads class from a class loader instance associated with a URL (searches on the site specified by the URL) 6 loads class from URL 39 1 class request 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. 40 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 41 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. 42 Java Security Keystore keytool -genkey -alias mykey -keyalg RSA -keypass changeit -keystore keystore.jks -storepass changeit 43 Java Security Security Policy ➢ SecureClassLoader assigns permissions when loading classes, by asking policy object to look up the permissions for the code source of each class. ➢ Own Policy class can be installed to carry out mapping from code sources to permissions. 44 Java Security Permission ➢ Permission classes represent access to various system resources such as files, sockets and so on. ➢ Collection of permissions can be construed as a customizable security policy for an installation. ➢ Permission classes represent approvals, but not denials. ➢ Permissions granted to a ProtectionDomain also called "privileges" 45 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 46 Access Policy $JAVA_HOME/jre/lib/security/java.security policy.url.1=file:${java.home}/lib/security/java.policy policy.url.2=file:${user.home}/.java.policy $JAVA_HOME/jre/lib/security/java.policy grant codeBase "file:${{java.ext.dirs}}/*" { permission java.security.AllPermission; }; grant { permission java.util.PropertyPermission "java.version", "read"; }; 47 Access Policy dir/ : all .class files, does not include .jar files dir/* : all .class and .jar files, does not include sub-dir files dir/- : all .class and .jar files, including sub-dir ones ➢ The permission is not granted if not configured ➢ The permission can only be configured so as to be granted, cannot be disabled ➢ The same permission can have multiple configurations. The union results will be recognized. 48 Access Policy import java.io.*; import java.security.*; public class TestPolicy { public static void main(String[] args) { String javaVersion=System.getProperty("java.version"); System.err.println(javaVersion); System.setProperty("java.version","1.7.0_45"); String javaNewVersion=System.getProperty("java.version"); System.err.println(javaNewVersion); } } java TestPolicy Security Manager is disabled by default! 1.8.0_152 1.7.0_45 49 Access Policy import java.io.*; import java.security.*; public class TestPolicy { public static void main(String[] args) { String javaVersion=System.getProperty("java.version"); System.err.println(javaVersion); System.setProperty("java.version","1.7.0_45"); String javaNewVersion=System.getProperty("java.version"); System.err.println(javaNewVersion); } } java -Djava.security.manager TestPolicy 50 Access Policy $JAVA_HOME/jre/lib/security/java.policy grant codeBase "file:${{java.ext.dirs}}/*" { permission java.security.AllPermission; }; grant { permission java.util.PropertyPermission "java.version", "read"; }; No ”write” permission java -Djava.security.manager TestPolicy 51 Access Policy test.policy grant { permission java.util.PropertyPermission "java.version", "read"; permission java.util.PropertyPermission "java.version", "write"; }; java -Djava.security.manager -Djava.security.policy=test.policy TestPolicy 52 Access Controller ➢ Permission-based stack inspection ➢ each method is associated with a fixed set of permissions ➢ permissions of method calls are tracked in a stack during execution – the stack is inspected before accessing a security-sensitive operation 53 Access Controller 54 Access Controller 55 Access Controller 56 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 57 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 58 Access Policy Problem: Untrusted Programs can abuse the granted permissions. Write property permission Write anything such as invalid value 59 Access Policy Problem: Untrusted Programs can abuse the granted permissions. Solution: Delegation Write property permission Write Controlled value 60 Access Policy Problem: Untrusted Programs can abuse the granted permissions. Cannot access because the caller does not have appropriate permission Write property permission Write Controlled value 61 Access Policy Problem: Untrusted Programs can abuse the granted permissions. AccessController.doPrivileged() { } 62 Access Policy If the Method object on which invoke() in called is user controlled, the user can call any method with all privileges. AccessController.doPrivileged() { java.lang.reflect.Method.invoke() System.setSecurityManager(null) } The sandbox can be completely disabled by calling System.setSecurityManager(null) from a privileged context. 63 Access Policy Apache Tomcat google.com facebook.com twitter.com //JSP <% System.exit(1); %>
Not only twitter is shut down,
both Google and Facebook are also shut down.
64