FIT5003 Software Security
Java Security II April 2020
1
Java Basics
Access Control
Class or Interface Accessibility
Member (Field or Method) Accessibility
Modifier
Public
All
All if class or interface is accessible; interface members always public
Protected
N/A
Same package OR subclass
“default” (Package private)
Same package
Same package
Private
N/A
Only same class (not subclass)
2
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
3
Java Basics
public class CreditCard {
public String acctNo = “1234”; }
private
javac CreditCard.java
java –pc . Test
CreditCard.class
4
Java Basics
public class CreditCard {
public String acctNo = “1234”; }
private
5
Reflection
Reflection is a Java feature that allows developers to manipulate things that already exist and, normally, are set.
It also has the ability to dynamically change what things are, regardless of how they were written!
It can even modify objects at runtime.
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 complete information about a class
public class Example{
public static void main (String[] args){
//1 – By using Class.forname() method
Class c1 = Class.forName(“Example”);
//2- By using getClass() method
Example exObj= new Example();
Class c2 = exObj.getClass();
//3- By using .class
Class c3= Example.class;
}
}
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 Class?
import java.lang.reflect.Modifier; public class fit5003classMetaData {
public static void main (String [] args) throws ClassNotFoundException { // Create Class object for Guru99Base.class
Class
// Print name of the class
System.out.println(“Name of the class is : ” +fit5003classObj.getName());
// Print Super class name System.out.println(“Name of the super class is : ” +
fit5003classObj.getSuperclass().getName());
// Get the list of implemented interfaces in the form of Class array using getInterface() method Class[] fit5003InterfaceList = fit5003classObj.getInterfaces();
// Print the implemented interfaces using foreach loop System.out.print(“Implemented interfaces are : “);
for (Class fit5003class1 : fit5003InterfaceList) {
} System.out.println(fit5003class1.getName() + ” “);
System.out.println();
//Access modifiers: get Modifiers() method and toString() of java.lang.reflect.Modifier class int fit5003AccessModifier= fit5003classObj.getModifiers();
// Print the access modifiers System.out.println(“Access modifiers of the class are : ” +
Modifier.toString(fit5003AccessModifier));
} }
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();
Reflection
Reflection
How to get Metadata of Method?
from the specified class as well as from its super
class
Method[] methods1 = cls.getMethods();
//from the specified class only
Method[] methods2 = cls.getDeclaredMethods();
Reflection
Reflection
Access private field
Class> clazz = Child.class; Object cc = clazz.newInstance();
Field f1 = cc.getClass().getSuperclass(). getDeclaredField(“a_field”);
f1.setAccessible(true); f1.set(cc, “reflecting on life”);
String str1 = (String) f1.get(cc); System.out.println(“field: ” + str1);
Reflection
Access private method
Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true); Object r = method.invoke(object);
fit5003AccessModifier
Realistic attack example:
https://cwe.mitre.org/data/definitions/470.html
Reflection vulnerability security issues
Security Manager:
enabled
Restrict permissions accordingly in security policy:
Watch out for the ReflectPermission permission
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
Java Deserialization in a Nutshell
Java Deserialization in a Nutshell
Attackers find dangerous classes available in the system
•Not necessarily used by the system
• Dangerous classes (NOT necessarily vulnerable)
•extend Serializable or Externalizable •utilize their member fields during or after deserialization
•no input validation
• Known as gadget classes
Abusing “magic methods” of gadgets which have dangerous code: • Attacker controls member fields / fields’ values of serialized object
• Upon deserialization .readObject() / .readResolve() is invoked
• Implementation of this method in gadget class uses attacker-controlled fields
Aside from the classic ones also lesser-known “magic methods” help: • .validateObject() as part of validation (which does not prevent attacks)
• .readObjectNoData() upon deserialization conflicts • .finalize() as part of GC (even after errors)
Crude Example
public class SomeClass implements Serializable {
private String cmd;
private void readObject( ObjectInputStream stream ) throws Exception {
stream.defaultReadObject();
} }
Remote Shell
Runtime.getRuntime().exec( cmd );
Java Security
Security
Scenarios?
23
Java Cryptography
Symmetric Key Encryption Public/Private Key Cryptography Keytool & KeyStore
24
Symmetric Key Encryption
25
Symmetric Key Encryption
Generating Key
KeyGenerator keyGenerator = KeyGenerator.getInstance(“AES”); keyGenerator.init(128);
SecretKey key = keyGenerator.generateKey();
AES: Advanced Encryption Standard DES: Data Encryption Standard BlowFish
RC4
26
Symmetric Key Encryption
Generating Key
KeyGenerator keyGenerator = KeyGenerator.getInstance(“AES”); keyGenerator.init(128);
SecretKey key = keyGenerator.generateKey();
Encrypt
Cipher cipher = Cipher.getInstance(“AES”); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] buf = cipher.doFinal(“xyz”.getBytes()); System.out.println(new String(buf));
27
Symmetric Key Encryption
Generating Key
KeyGenerator keyGenerator = KeyGenerator.getInstance(“AES”); keyGenerator.init(128);
SecretKey key = keyGenerator.generateKey();
Encrypt
Cipher cipher = Cipher.getInstance(“AES”); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] buf = cipher.doFinal(“xyz”.getBytes()); System.out.println(new String(buf));
Cipher cipher2 = Cipher.getInstance(“AES”); cipher2.init(Cipher.DECRYPT_MODE, key); byte[] buf2 = cipher2.doFinal(buf); System.out.println(new String(buf2));
Decrypt
28
Public Key Encryption
29
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();
RSA
most common public key, based on factoring large primes
Diffie-Hellman Elliptic Curve
30
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
31
Public Key Encryption
How to make sure the public keys are real?
public key of A B
32
Public Key Encryption
How to make sure the public keys are real?
Certificate
Certificate Authority (CA) verifies the identity of A
public key of A
public key of A
Digital signature of the CA
Validity: 2019
33
Public Key Encryption
public key of A
private static boolean test(
Certificate target,
Certificate signer) {
PublicKey pubKey =signer.getPublicKey();
target.verify(pubKey);
}
Digital signature of the CA
Validity: 2019
34
Public Key Encryption
How can user B trust the CA?
What if the verified certificate is revoked?
35
Keytool & KeyStore
Most Java programs use existing keys rather than create keys themselves.
password protected private keys and public keys as certificates.
36
Keytool & KeyStore
keytool -help
37
Keytool & KeyStore
keytool -list –v
38
Keytool & KeyStore
keytool -genkey -alias li -keyalg RSA -keypass 123456
By default: the generated key will be stored at ~/.keystore
39
Keytool & KeyStore
keytool -list –v
40
Keytool & KeyStore
keytool -list –v
41
Keytool & KeyStore
keytool -export -alias li -file joey.crt
keytool -printcert -file joey.crt
42
Keytool & KeyStore
How can joey.crt be trusted?
User
certreq
CRT file
CA-certified certificate
importcert
Trusted Certificate
Authority (CA)
CSR file
Certificate sign request
gencert
43
Keytool & KeyStore
Default Keystore location: JAVA_HOME/jre/lib/security/cacerts. Create KeyStore
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
Load KeyStore
FileInputStream fis = new
FileInputStream(“/Users/clii0040/Projects/JavaExamples/ca_test.keystore”);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(fis, “storepass”.toCharArray());
44
Keytool & KeyStore
Get Private Key
String alias = “ca2”;
PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, “keypass”.toCharArray());
Because it needs to have the key password to retrieve the private key, only the owner of the certificate can obtain it and use it.
45
Keytool & KeyStore
Get Public Key
Certificate cert = keystore.getCertificate(alias); PublicKey publicKey = cert.getPublicKey();
Password is not needed for obtaining the public key. Anyone can retrieve it and use it.
46
Summary
Java Security
Application-level Security Concurrency
Reflection
Architecture-level Security
Security Manager and Access Controller Encryption
Keytool and KeyStore
47